diff --git "a/2512.jsonl" "b/2512.jsonl" new file mode 100644--- /dev/null +++ "b/2512.jsonl" @@ -0,0 +1,505 @@ +{"seq_id":"23349075782","text":"import RPi.GPIO as GPIO\nimport time\nimport math\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\n\nmyStep = .1\n\n\n\nGPIO.setup(12,GPIO.OUT)\nservo0 = GPIO.PWM(12,50)\nservo0.start(0)\n\ninput0 = 0\n\n\ndef cosineMap(pos):\n mappedPos = math.cos(pos)\n return mappedPos\n\ndef myMapValues(variable,oldLow,oldHigh,newLow,newHigh):\n variable = (variable - oldLow) / (oldHigh - oldLow) * (newHigh - newLow) + newLow\n return variable\n \n\n\nwhile True:\n output0 = cosineMap(input0 + myStep)\n \n \n desiredLow=0\n desiredHigh=180\n output0 = myMapValues(output0, -1,1,desiredLow,desiredHigh)\n #print(\"Post-Map output: \" + str(output0))\n \n \n \n servoWriteOutput0 = 2+(output0/18)\n #print(\"servoWriteOutput0: \" + str(servoWriteOutput0))\n \n \n servo0.ChangeDutyCycle(servoWriteOutput0)\n \n \n \n time.sleep(.05)\n servo0.ChangeDutyCycle(0)\n \n \n \n \n input0 = input0 + myStep\n \n \n \n \n \n\n","repo_name":"glenert41/ANTLA","sub_path":"1ServoSineTestingPython.py","file_name":"1ServoSineTestingPython.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"27225909262","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # import required library\n\n# In[1]:\n\n\n# Import numpy, pandas for data manipulation\nimport numpy as np\nimport pandas as pd\n\n# Import matplotlib, seaborn for visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# In[2]:\n\n\n# Import the data\nweather_data = pd.read_csv('weather.csv')\nweather_data.head()\n\n\n# In[8]:\n\n\nrain_df = weather_data[['Date','Rainfall']]\nrain_df.head()\n\n\n# In[9]:\n\n\nrain_df.shape\n\n\n# In[10]:\n\n\nrain_df.info()\n\n\n# **Using 50 values**\n\n# In[15]:\n\n\nrain_df = rain_df.loc[:49]\nrain_df.head()\n\n\n# In[16]:\n\n\nrain_df.shape\n\n\n# In[17]:\n\n\n# Convert the time column into datetime\nrain_df['Date'] = pd.to_datetime(rain_df['Date'])\nrain_df['Date'].head()\n\n\n# In[18]:\n\n\nrain_df.info()\n\n\n# In[24]:\n\n\n# fill the empty row\nrain_df = rain_df.fillna(rain_df['Rainfall'].mean())\nrain_df.head()\n\n\n# ### Dataset Explanation\n\n# In[27]:\n\n\nrain_df.describe()\n\n\n# In[29]:\n\n\n# Output the maximum and minimum rain date\nprint(rain_df.loc[rain_df[\"Rainfall\"] == rain_df[\"Rainfall\"].max()])\nprint(rain_df.loc[rain_df[\"Rainfall\"] == rain_df[\"Rainfall\"].min()])\n\n\n# In[30]:\n\n\n# Reset the index \nrain_df.set_index(\"Date\", inplace=True)\n\n\n# ### Data Visualization\n\n# In[32]:\n\n\n# Plot the daily temperature change \nplt.figure(figsize=(16,10), dpi=100)\nplt.plot(rain_df.index, rain_df.Rainfall, color='tab:red')\nplt.gca().set(title=\"Daily Rain\", xlabel='Date', ylabel=\"rain value\")\nplt.show()\n\n\n# In[35]:\n\n\n# Apply the Moving Average function by a subset of size 10 days.\nrain_df_mean = rain_df.Rainfall.rolling(window=10).mean()\nrain_df_mean.plot(figsize=(16,10))\nplt.show()\n\n\n# In[37]:\n\n\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n\n# Additive Decomposition\nresult_add = seasonal_decompose(rain_df.Rainfall, model='additive', extrapolate_trend=0)\n\n# Plot\nplt.rcParams.update({'figure.figsize': (10,10)})\nresult_add.plot().suptitle('Additive Decomposition', fontsize=22)\nplt.show()\n\n\n# ### Baseline Model\n\n# In[38]:\n\n\n# Shift the current rain to the next day. \npredicted_df = rain_df[\"Rainfall\"].to_frame().shift(1).rename(columns = {\"Rainfall\": \"rain_pred\" })\nactual_df = rain_df[\"Rainfall\"].to_frame().rename(columns = {\"Rainfall\": \"rain_actual\" })\n\n# Concatenate the actual and predicted rain\none_step_df = pd.concat([actual_df,predicted_df],axis=1)\n\n# Select from the second row, because there is no prediction for today due to shifting.\none_step_df = one_step_df[1:]\none_step_df.head(10)\n\n\n# > Here you can the we have two column one is our **actual rain** column and othe is **predicted rain** column that we use next model \n\n# We could validate how well our model is by looking at the Root Mean Squared Error(RMSE) between the predicted and actual rain\n\n# In[41]:\n\n\nfrom sklearn.metrics import mean_squared_error as MSE\nfrom math import sqrt\n\n# Calculate the RMSE\nrain_pred_err = MSE(one_step_df.rain_actual, one_step_df.rain_pred, squared=False)\nprint(\"The RMSE is\",rain_pred_err)\n\n\n# > Our RMSE value is 4.002 is arround 4 that are pretty good for model.\n\n# ## Using SARIMA model\n\n# ### Parameter Selection\n# #### Grid Search\n# We are going to apply one of the most commonly used method for time-series forecasting, known as SARIMA, which stands for Seasonal Autoregressive Integrated Moving Average. SARIMA models are denoted with the notation SARIMA(p,d,q)(P,D,Q,s). These three parameters account for seasonality, trend, and noise in data:\n# \n# We will use a “grid search” to iteratively explore different combinations of parameters. For each combination of parameters, we fit a new seasonal SARIMA model with the SARIMAX() function from the statsmodels module and assess its overall quality.\n\n# In[42]:\n\n\nimport itertools\n\n# Define the p, d and q parameters to take any value between 0 and 2\np = d = q = range(0, 2)\n\n# Generate all different combinations of p, q and q triplets\npdq = list(itertools.product(p, d, q))\n\n# Generate all different combinations of seasonal p, q and q triplets\nseasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]\n\nprint('Examples of parameter combinations for Seasonal ARIMA...')\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1]))\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4]))\n\n\n# In[43]:\n\n\nfor param in pdq:\n for param_seasonal in seasonal_pdq:\n try:\n mod = sm.tsa.statespace.SARIMAX(one_step_df.rain_actual,\n order=param,\n seasonal_order=param_seasonal,\n enforce_stationarity=False,\n enforce_invertibility=False)\n\n results = mod.fit()\n\n print('SARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))\n except:\n continue\n\n\n# ### Fitting the Model\n\n# In[47]:\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\") # specify to ignore warning messages\n# Import the statsmodels library for using SARIMAX model\nimport statsmodels.api as sm\n\n# Fit the SARIMAX model using optimal parameters\nmod = sm.tsa.statespace.SARIMAX(one_step_df.rain_actual,\n order=(1,1,1),\n seasonal_order=(1,1,1,12),\n enforce_stationarity=False,\n enforce_invertibility=False)\n\n\n# In[48]:\n\n\nresults = mod.fit()\n\n\n# In[49]:\n\n\nresults.summary()\n\n\n# **Predictions**\n\n# In[51]:\n\n\npred = results.predict(start=0,end=49)[1:]\npred\n\n\n# In[52]:\n\n\npred = results.get_prediction(start=0,end = 49, dynamic=False)\npred_ci = pred.conf_int()\n\n\n# In[53]:\n\n\npred_ci.head()\n\n\n# In[55]:\n\n\nprint(pred)\n\n\n# In[58]:\n\n\nax = one_step_df.rain_actual.plot(label='observed',figsize=(16,10))\nax.set_xlabel('Date')\nax.set_ylabel('value')\nplt.ylim([0,2.0])\nplt.legend()\nplt.show()\n\n\n# ### Forecast Diagnostic\n# It is also useful to quantify the accuracy of our forecasts. We will use the MSE (Mean Squared Error), in which for each predicted value, we compute its distance to the true value and square the result\n\n# In[65]:\n\n\ny_forecasted = pred.predicted_mean[:49]\ny_truth = one_step_df.rain_actual\nprint(y_forecasted.shape)\nprint(y_truth.shape)\n# Compute the mean square error\nmse = MSE(y_truth, y_forecasted, squared=True)\nprint('The Mean Squared Error of our forecasts is {}'.format(round(mse, 2)))\n\n\n# Amazziingggg! Our forecast model forecasts the rain with only an error of 25.85. \n# \n# In the weather forecast field, the prediction error of 2.19 degrees seems promising and sufficient, as there are many other factors that contribute to the change in rain, including but not limited to the wind speed, the air pressure, etc.\n\n# ### Validating the Dynamic Forecast\n\n# In this case, we only use information from the time series up to a certain point, and after that, forecasts are generated using values from previous forecasted time points.\n# \n\n# In[66]:\n\n\npred_dynamic = results.get_prediction(start=0,end = 49, dynamic=True, full_results=True)\npred_dynamic_ci = pred_dynamic.conf_int()\n\n\n# In[67]:\n\n\npred_dynamic_ci.head()\n\n\n# Once again, we plot the real and forecasted values of the average daily rain to assess how well we did:\n\n# In[71]:\n\n\nax = one_step_df.rain_actual.plot(label='observed', figsize=(15, 11))\npred_dynamic.predicted_mean.plot(label='Dynamic Forecast', ax=ax)\n\nax.fill_between(pred_dynamic_ci.index,\n pred_dynamic_ci.iloc[:, 0],\n pred_dynamic_ci.iloc[:, 1], color='k', alpha=.25)\n\n\nax.set_xlabel('Date')\nax.set_ylabel('Temperature (in Celsius)')\nplt.ylim([0,2.0])\nplt.legend()\nplt.show()\n\n\n# > In this case, the model seems to predict the rain inaccurately, with major fluctuations between the true value and the predicted value.\n\n# ### Forecast Diagnostic\n\n# In[73]:\n\n\n# Extract the predicted and true values of our time series\ny_forecasted = pred_dynamic.predicted_mean[:49]\ny_truth = one_step_df.rain_actual\n\n# Compute the mean square error\nmse = sqrt(MSE(y_truth, y_forecasted).mean())\nprint('The Root Mean Squared Error of our forecasts is {}'.format(round(mse, 2)))\n\n\n# The **predicted** values obtained from the dynamic forecasts yield an MSE of 3.68. This is significantly higher than the one-step ahead, which is to be expected given that we are relying on less historical data from the time series.\n\n# # Conclusion\n\n# I described how to implement a seasonal SARIMA model in Python. I made extensive use of the pandas and statsmodels libraries and showed how to run model diagnostics, as well as how to produce forecasts of the Rain.\n\n# Recall that in the assumption I made in the section 2.2 Baseline Model, I could even reinforce our assumption and continue our belief that the rainfall today depends on the rainfall yesterday, the rainfall yesterday depends on the day before yesterday, and so on. \n# \n# It is the best so far to use the history up to the point that we would like to make **predictions** on. Especially it holds for weather forecasting, where the rainfall today does not change much from yesterday, and the transition to another season signaling through the rainfall should gradually occur, unless there is any disastrous factors such as storm, drought, etc.\n","repo_name":"shreejitverma/Data-Scientist","sub_path":"Time Series Analysis/Weather Forecasting using SRIMAX Model/weather prediction.py","file_name":"weather prediction.py","file_ext":"py","file_size_in_byte":9365,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"85"} +{"seq_id":"28692992124","text":"import argparse\nimport hashlib\nimport itertools\nimport json\nimport logging\nimport math\nimport uuid\nimport warnings\nfrom os import environ, listdir, makedirs\nfrom os.path import basename, join\nfrom pathlib import Path\nfrom typing import List\n\nimport datasets\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.utils.checkpoint\nimport transformers\nfrom accelerate import Accelerator\nfrom accelerate.logging import get_logger\nfrom accelerate.utils import ProjectConfiguration, set_seed\nfrom huggingface_hub import create_repo, upload_folder\nfrom PIL import Image\nfrom torch import dtype\nfrom torch.nn import Module\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom tqdm.auto import tqdm\nfrom transformers import AutoTokenizer, PretrainedConfig\n\nimport diffusers\nfrom diffusers import (\n AutoencoderKL,\n DDPMScheduler,\n DiffusionPipeline,\n DPMSolverMultistepScheduler,\n UNet2DConditionModel,\n)\nfrom diffusers.optimization import get_scheduler\nfrom diffusers.utils import check_min_version, is_wandb_available\nfrom diffusers.utils.import_utils import is_xformers_available\n\n\nif is_wandb_available():\n import wandb\n\n# Will error if the minimal version of diffusers is not installed. Remove at your own risks.\ncheck_min_version(\"0.13.0.dev0\")\n\nlogger = get_logger(__name__)\n\n\ndef log_validation_images_to_tracker(\n images: List[np.array], label: str, validation_prompt: str, accelerator: Accelerator, epoch: int\n):\n logger.info(f\"Logging images to tracker for validation prompt: {validation_prompt}.\")\n\n for tracker in accelerator.trackers:\n if tracker.name == \"tensorboard\":\n np_images = np.stack([np.asarray(img) for img in images])\n tracker.writer.add_images(\"validation\", np_images, epoch, dataformats=\"NHWC\")\n if tracker.name == \"wandb\":\n tracker.log(\n {\n \"validation\": [\n wandb.Image(image, caption=f\"{label}_{epoch}_{i}: {validation_prompt}\")\n for i, image in enumerate(images)\n ]\n }\n )\n\n\n# TODO: Add `prompt_embeds` and `negative_prompt_embeds` parameters to the function when `pre_compute_text_embeddings`\n# argument is implemented.\ndef generate_validation_images(\n text_encoder: Module,\n tokenizer: Module,\n unet: Module,\n vae: Module,\n arguments: argparse.Namespace,\n accelerator: Accelerator,\n weight_dtype: dtype,\n):\n logger.info(\"Running validation images.\")\n\n pipeline_args = {}\n\n if text_encoder is not None:\n pipeline_args[\"text_encoder\"] = accelerator.unwrap_model(text_encoder)\n\n if vae is not None:\n pipeline_args[\"vae\"] = vae\n\n # create pipeline (note: unet and vae are loaded again in float32)\n pipeline = DiffusionPipeline.from_pretrained(\n arguments.pretrained_model_name_or_path,\n tokenizer=tokenizer,\n unet=accelerator.unwrap_model(unet),\n revision=arguments.revision,\n torch_dtype=weight_dtype,\n **pipeline_args,\n )\n\n # We train on the simplified learning objective. If we were previously predicting a variance, we need the\n # scheduler to ignore it\n scheduler_args = {}\n\n if \"variance_type\" in pipeline.scheduler.config:\n variance_type = pipeline.scheduler.config.variance_type\n\n if variance_type in [\"learned\", \"learned_range\"]:\n variance_type = \"fixed_small\"\n\n scheduler_args[\"variance_type\"] = variance_type\n\n pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, **scheduler_args)\n pipeline = pipeline.to(accelerator.device)\n pipeline.set_progress_bar_config(disable=True)\n\n generator = (\n None if arguments.seed is None else torch.Generator(device=accelerator.device).manual_seed(arguments.seed)\n )\n\n images_sets = []\n for vp, nvi, vnp, vis, vgs in zip(\n arguments.validation_prompt,\n arguments.validation_number_images,\n arguments.validation_negative_prompt,\n arguments.validation_inference_steps,\n arguments.validation_guidance_scale,\n ):\n images = []\n if vp is not None:\n logger.info(\n f\"Generating {nvi} images with prompt: '{vp}', negative prompt: '{vnp}', inference steps: {vis}, \"\n f\"guidance scale: {vgs}.\"\n )\n\n pipeline_args = {\"prompt\": vp, \"negative_prompt\": vnp, \"num_inference_steps\": vis, \"guidance_scale\": vgs}\n\n # run inference\n # TODO: it would be good to measure whether it's faster to run inference on all images at once, one at a\n # time or in small batches\n for _ in range(nvi):\n with torch.autocast(\"cuda\"):\n image = pipeline(**pipeline_args, num_images_per_prompt=1, generator=generator).images[0]\n images.append(image)\n\n images_sets.append(images)\n\n del pipeline\n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n\n return images_sets\n\n\ndef import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):\n text_encoder_config = PretrainedConfig.from_pretrained(\n pretrained_model_name_or_path,\n subfolder=\"text_encoder\",\n revision=revision,\n )\n model_class = text_encoder_config.architectures[0]\n\n if model_class == \"CLIPTextModel\":\n from transformers import CLIPTextModel\n\n return CLIPTextModel\n elif model_class == \"RobertaSeriesModelWithTransformation\":\n from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation\n\n return RobertaSeriesModelWithTransformation\n else:\n raise ValueError(f\"{model_class} is not supported.\")\n\n\ndef parse_args(input_args=None):\n parser = argparse.ArgumentParser(description=\"Simple example of a training script.\")\n parser.add_argument(\n \"--pretrained_model_name_or_path\",\n type=str,\n default=None,\n required=True,\n help=\"Path to pretrained model or model identifier from huggingface.co/models.\",\n )\n parser.add_argument(\n \"--revision\",\n type=str,\n default=None,\n required=False,\n help=\"Revision of pretrained model identifier from huggingface.co/models.\",\n )\n parser.add_argument(\n \"--tokenizer_name\",\n type=str,\n default=None,\n help=\"Pretrained tokenizer name or path if not the same as model_name\",\n )\n parser.add_argument(\n \"--instance_data_dir\",\n type=str,\n default=None,\n required=False,\n help=\"A folder containing the training data of instance images.\",\n )\n parser.add_argument(\n \"--class_data_dir\",\n type=str,\n default=None,\n required=False,\n help=\"A folder containing the training data of class images.\",\n )\n parser.add_argument(\n \"--instance_prompt\",\n type=str,\n default=None,\n required=False,\n help=\"The prompt with identifier specifying the instance\",\n )\n parser.add_argument(\n \"--class_prompt\",\n type=str,\n default=None,\n help=\"The prompt to specify images in the same class as provided instance images.\",\n )\n parser.add_argument(\n \"--with_prior_preservation\",\n default=False,\n action=\"store_true\",\n help=\"Flag to add prior preservation loss.\",\n )\n parser.add_argument(\"--prior_loss_weight\", type=float, default=1.0, help=\"The weight of prior preservation loss.\")\n parser.add_argument(\n \"--num_class_images\",\n type=int,\n default=100,\n help=(\n \"Minimal class images for prior preservation loss. If there are not enough images already present in\"\n \" class_data_dir, additional images will be sampled with class_prompt.\"\n ),\n )\n parser.add_argument(\n \"--output_dir\",\n type=str,\n default=\"text-inversion-model\",\n help=\"The output directory where the model predictions and checkpoints will be written.\",\n )\n parser.add_argument(\"--seed\", type=int, default=None, help=\"A seed for reproducible training.\")\n parser.add_argument(\n \"--resolution\",\n type=int,\n default=512,\n help=(\n \"The resolution for input images, all the images in the train/validation dataset will be resized to this\"\n \" resolution\"\n ),\n )\n parser.add_argument(\n \"--center_crop\",\n default=False,\n action=\"store_true\",\n help=(\n \"Whether to center crop the input images to the resolution. If not set, the images will be randomly\"\n \" cropped. The images will be resized to the resolution first before cropping.\"\n ),\n )\n parser.add_argument(\"--train_text_encoder\", action=\"store_true\", help=\"Whether to train the text encoder\")\n parser.add_argument(\n \"--train_batch_size\", type=int, default=4, help=\"Batch size (per device) for the training dataloader.\"\n )\n parser.add_argument(\n \"--sample_batch_size\", type=int, default=4, help=\"Batch size (per device) for sampling images.\"\n )\n parser.add_argument(\"--num_train_epochs\", type=int, default=1)\n parser.add_argument(\n \"--max_train_steps\",\n type=int,\n default=None,\n help=\"Total number of training steps to perform. If provided, overrides num_train_epochs.\",\n )\n parser.add_argument(\n \"--checkpointing_steps\",\n type=int,\n default=500,\n help=(\n \"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final\"\n \" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming\"\n \" training using `--resume_from_checkpoint`.\"\n ),\n )\n parser.add_argument(\n \"--checkpoints_total_limit\",\n type=int,\n default=None,\n help=(\n \"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`.\"\n \" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state\"\n \" for more docs\"\n ),\n )\n parser.add_argument(\n \"--resume_from_checkpoint\",\n type=str,\n default=None,\n help=(\n \"Whether training should be resumed from a previous checkpoint. Use a path saved by\"\n ' `--checkpointing_steps`, or `\"latest\"` to automatically select the last available checkpoint.'\n ),\n )\n parser.add_argument(\n \"--gradient_accumulation_steps\",\n type=int,\n default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\",\n )\n parser.add_argument(\n \"--gradient_checkpointing\",\n action=\"store_true\",\n help=\"Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.\",\n )\n parser.add_argument(\n \"--learning_rate\",\n type=float,\n default=5e-6,\n help=\"Initial learning rate (after the potential warmup period) to use.\",\n )\n parser.add_argument(\n \"--scale_lr\",\n action=\"store_true\",\n default=False,\n help=\"Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.\",\n )\n parser.add_argument(\n \"--lr_scheduler\",\n type=str,\n default=\"constant\",\n help=(\n 'The scheduler type to use. Choose between [\"linear\", \"cosine\", \"cosine_with_restarts\", \"polynomial\",'\n ' \"constant\", \"constant_with_warmup\"]'\n ),\n )\n parser.add_argument(\n \"--lr_warmup_steps\", type=int, default=500, help=\"Number of steps for the warmup in the lr scheduler.\"\n )\n parser.add_argument(\n \"--lr_num_cycles\",\n type=int,\n default=1,\n help=\"Number of hard resets of the lr in cosine_with_restarts scheduler.\",\n )\n parser.add_argument(\"--lr_power\", type=float, default=1.0, help=\"Power factor of the polynomial scheduler.\")\n parser.add_argument(\n \"--use_8bit_adam\", action=\"store_true\", help=\"Whether or not to use 8-bit Adam from bitsandbytes.\"\n )\n parser.add_argument(\"--adam_beta1\", type=float, default=0.9, help=\"The beta1 parameter for the Adam optimizer.\")\n parser.add_argument(\"--adam_beta2\", type=float, default=0.999, help=\"The beta2 parameter for the Adam optimizer.\")\n parser.add_argument(\"--adam_weight_decay\", type=float, default=1e-2, help=\"Weight decay to use.\")\n parser.add_argument(\"--adam_epsilon\", type=float, default=1e-08, help=\"Epsilon value for the Adam optimizer\")\n parser.add_argument(\"--max_grad_norm\", default=1.0, type=float, help=\"Max gradient norm.\")\n parser.add_argument(\"--push_to_hub\", action=\"store_true\", help=\"Whether or not to push the model to the Hub.\")\n parser.add_argument(\"--hub_token\", type=str, default=None, help=\"The token to use to push to the Model Hub.\")\n parser.add_argument(\n \"--hub_model_id\",\n type=str,\n default=None,\n help=\"The name of the repository to keep in sync with the local `output_dir`.\",\n )\n parser.add_argument(\n \"--logging_dir\",\n type=str,\n default=\"logs\",\n help=(\n \"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to\"\n \" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***.\"\n ),\n )\n parser.add_argument(\n \"--allow_tf32\",\n action=\"store_true\",\n help=(\n \"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see\"\n \" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices\"\n ),\n )\n parser.add_argument(\n \"--report_to\",\n type=str,\n default=\"tensorboard\",\n help=(\n 'The integration to report the results and logs to. Supported platforms are `\"tensorboard\"`'\n ' (default), `\"wandb\"` and `\"comet_ml\"`. Use `\"all\"` to report to all integrations.'\n ),\n )\n parser.add_argument(\n \"--validation_steps\",\n type=int,\n default=None,\n help=(\n \"Run validation every X steps. Validation consists of running the prompt(s) `validation_prompt` \"\n \"multiple times (`validation_number_images`) and logging the images.\"\n ),\n )\n parser.add_argument(\n \"--validation_prompt\",\n type=str,\n default=None,\n help=\"A prompt that is used during validation to verify that the model is learning. You can use commas to \"\n \"define multiple negative prompts. This parameter can be defined also within the file given by \"\n \"`concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_number_images\",\n type=int,\n default=4,\n help=\"Number of images that should be generated during validation with the validation parameters given. This \"\n \"can be defined within the file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_negative_prompt\",\n type=str,\n default=None,\n help=\"A negative prompt that is used during validation to verify that the model is learning. You can use commas\"\n \" to define multiple negative prompts, each one corresponding to a validation prompt. This parameter can \"\n \"be defined also within the file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_inference_steps\",\n type=int,\n default=25,\n help=\"Number of inference steps (denoising steps) to run during validation. This can be defined within the \"\n \"file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_guidance_scale\",\n type=float,\n default=7.5,\n help=\"To control how much the image generation process follows the text prompt. This can be defined within the \"\n \"file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--mixed_precision\",\n type=str,\n default=None,\n choices=[\"no\", \"fp16\", \"bf16\"],\n help=(\n \"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=\"\n \" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the\"\n \" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config.\"\n ),\n )\n parser.add_argument(\n \"--prior_generation_precision\",\n type=str,\n default=None,\n choices=[\"no\", \"fp32\", \"fp16\", \"bf16\"],\n help=(\n \"Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=\"\n \" 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32.\"\n ),\n )\n parser.add_argument(\"--local_rank\", type=int, default=-1, help=\"For distributed training: local_rank\")\n parser.add_argument(\n \"--enable_xformers_memory_efficient_attention\", action=\"store_true\", help=\"Whether or not to use xformers.\"\n )\n parser.add_argument(\n \"--set_grads_to_none\",\n action=\"store_true\",\n help=(\n \"Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain\"\n \" behaviors, so disable this argument if it causes any problems. More info:\"\n \" https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html\"\n ),\n )\n parser.add_argument(\n \"--concepts_list\",\n type=str,\n default=None,\n help=\"Path to json file containing a list of multiple concepts, will overwrite parameters like instance_prompt,\"\n \" class_prompt, etc.\",\n )\n\n if input_args:\n args = parser.parse_args(input_args)\n else:\n args = parser.parse_args()\n\n if not args.concepts_list and (not args.instance_data_dir or not args.instance_prompt):\n raise ValueError(\n \"You must specify either instance parameters (data directory, prompt, etc.) or use \"\n \"the `concept_list` parameter and specify them within the file.\"\n )\n\n if args.concepts_list:\n if args.instance_prompt:\n raise ValueError(\"If you are using `concepts_list` parameter, define the instance prompt within the file.\")\n if args.instance_data_dir:\n raise ValueError(\n \"If you are using `concepts_list` parameter, define the instance data directory within the file.\"\n )\n if args.validation_steps and (args.validation_prompt or args.validation_negative_prompt):\n raise ValueError(\n \"If you are using `concepts_list` parameter, define validation parameters for \"\n \"each subject within the file:\\n - `validation_prompt`.\"\n \"\\n - `validation_negative_prompt`.\\n - `validation_guidance_scale`.\"\n \"\\n - `validation_number_images`.\\n - `validation_prompt`.\"\n \"\\n - `validation_inference_steps`.\\nThe `validation_steps` parameter is the only one \"\n \"that needs to be defined outside the file.\"\n )\n\n env_local_rank = int(environ.get(\"LOCAL_RANK\", -1))\n if env_local_rank != -1 and env_local_rank != args.local_rank:\n args.local_rank = env_local_rank\n\n if args.with_prior_preservation:\n if not args.concepts_list:\n if not args.class_data_dir:\n raise ValueError(\"You must specify a data directory for class images.\")\n if not args.class_prompt:\n raise ValueError(\"You must specify prompt for class images.\")\n else:\n if args.class_data_dir:\n raise ValueError(\n \"If you are using `concepts_list` parameter, define the class data directory within the file.\"\n )\n if args.class_prompt:\n raise ValueError(\n \"If you are using `concepts_list` parameter, define the class prompt within the file.\"\n )\n else:\n # logger is not available yet\n if not args.class_data_dir:\n warnings.warn(\n \"Ignoring `class_data_dir` parameter, you need to use it together with `with_prior_preservation`.\"\n )\n if not args.class_prompt:\n warnings.warn(\n \"Ignoring `class_prompt` parameter, you need to use it together with `with_prior_preservation`.\"\n )\n\n return args\n\n\nclass DreamBoothDataset(Dataset):\n \"\"\"\n A dataset to prepare the instance and class images with the prompts for fine-tuning the model.\n It pre-processes the images and then tokenizes prompts.\n \"\"\"\n\n def __init__(\n self,\n instance_data_root,\n instance_prompt,\n tokenizer,\n class_data_root=None,\n class_prompt=None,\n size=512,\n center_crop=False,\n ):\n self.size = size\n self.center_crop = center_crop\n self.tokenizer = tokenizer\n\n self.instance_data_root = []\n self.instance_images_path = []\n self.num_instance_images = []\n self.instance_prompt = []\n self.class_data_root = [] if class_data_root is not None else None\n self.class_images_path = []\n self.num_class_images = []\n self.class_prompt = []\n self._length = 0\n\n for i in range(len(instance_data_root)):\n self.instance_data_root.append(Path(instance_data_root[i]))\n if not self.instance_data_root[i].exists():\n raise ValueError(\"Instance images root doesn't exists.\")\n\n self.instance_images_path.append(list(Path(instance_data_root[i]).iterdir()))\n self.num_instance_images.append(len(self.instance_images_path[i]))\n self.instance_prompt.append(instance_prompt[i])\n self._length += self.num_instance_images[i]\n\n if class_data_root is not None:\n self.class_data_root.append(Path(class_data_root[i]))\n self.class_data_root[i].mkdir(parents=True, exist_ok=True)\n self.class_images_path.append(list(self.class_data_root[i].iterdir()))\n self.num_class_images.append(len(self.class_images_path))\n if self.num_class_images[i] > self.num_instance_images[i]:\n self._length -= self.num_instance_images[i]\n self._length += self.num_class_images[i]\n self.class_prompt.append(class_prompt[i])\n\n self.image_transforms = transforms.Compose(\n [\n transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),\n transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),\n transforms.ToTensor(),\n transforms.Normalize([0.5], [0.5]),\n ]\n )\n\n def __len__(self):\n return self._length\n\n def __getitem__(self, index):\n example = {}\n for i in range(len(self.instance_images_path)):\n instance_image = Image.open(self.instance_images_path[i][index % self.num_instance_images[i]])\n if not instance_image.mode == \"RGB\":\n instance_image = instance_image.convert(\"RGB\")\n example[f\"instance_images_{i}\"] = self.image_transforms(instance_image)\n example[f\"instance_prompt_ids_{i}\"] = self.tokenizer(\n self.instance_prompt[i],\n truncation=True,\n padding=\"max_length\",\n max_length=self.tokenizer.model_max_length,\n return_tensors=\"pt\",\n ).input_ids\n\n if self.class_data_root:\n for i in range(len(self.class_data_root)):\n class_image = Image.open(self.class_images_path[i][index % self.num_class_images[i]])\n if not class_image.mode == \"RGB\":\n class_image = class_image.convert(\"RGB\")\n example[f\"class_images_{i}\"] = self.image_transforms(class_image)\n example[f\"class_prompt_ids_{i}\"] = self.tokenizer(\n self.class_prompt[i],\n truncation=True,\n padding=\"max_length\",\n max_length=self.tokenizer.model_max_length,\n return_tensors=\"pt\",\n ).input_ids\n\n return example\n\n\ndef collate_fn(num_instances, examples, with_prior_preservation=False):\n input_ids = []\n pixel_values = []\n\n for i in range(num_instances):\n input_ids += [example[f\"instance_prompt_ids_{i}\"] for example in examples]\n pixel_values += [example[f\"instance_images_{i}\"] for example in examples]\n\n # Concat class and instance examples for prior preservation.\n # We do this to avoid doing two forward passes.\n if with_prior_preservation:\n for i in range(num_instances):\n input_ids += [example[f\"class_prompt_ids_{i}\"] for example in examples]\n pixel_values += [example[f\"class_images_{i}\"] for example in examples]\n\n pixel_values = torch.stack(pixel_values)\n pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()\n\n input_ids = torch.cat(input_ids, dim=0)\n\n batch = {\n \"input_ids\": input_ids,\n \"pixel_values\": pixel_values,\n }\n return batch\n\n\nclass PromptDataset(Dataset):\n \"\"\"A simple dataset to prepare the prompts to generate class images on multiple GPUs.\"\"\"\n\n def __init__(self, prompt, num_samples):\n self.prompt = prompt\n self.num_samples = num_samples\n\n def __len__(self):\n return self.num_samples\n\n def __getitem__(self, index):\n example = {}\n example[\"prompt\"] = self.prompt\n example[\"index\"] = index\n return example\n\n\ndef main(args):\n logging_dir = Path(args.output_dir, args.logging_dir)\n accelerator_project_config = ProjectConfiguration(\n total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir\n )\n accelerator = Accelerator(\n gradient_accumulation_steps=args.gradient_accumulation_steps,\n mixed_precision=args.mixed_precision,\n log_with=args.report_to,\n project_config=accelerator_project_config,\n )\n\n if args.report_to == \"wandb\":\n if not is_wandb_available():\n raise ImportError(\"Make sure to install wandb if you want to use it for logging during training.\")\n\n # Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate\n # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.\n # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.\n if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:\n raise ValueError(\n \"Gradient accumulation is not supported when training the text encoder in distributed training. \"\n \"Please set gradient_accumulation_steps to 1. This feature will be supported in the future.\"\n )\n\n instance_data_dir = []\n instance_prompt = []\n class_data_dir = [] if args.with_prior_preservation else None\n class_prompt = [] if args.with_prior_preservation else None\n if args.concepts_list:\n with open(args.concepts_list, \"r\") as f:\n concepts_list = json.load(f)\n\n if args.validation_steps:\n args.validation_prompt = []\n args.validation_number_images = []\n args.validation_negative_prompt = []\n args.validation_inference_steps = []\n args.validation_guidance_scale = []\n\n for concept in concepts_list:\n instance_data_dir.append(concept[\"instance_data_dir\"])\n instance_prompt.append(concept[\"instance_prompt\"])\n\n if args.with_prior_preservation:\n try:\n class_data_dir.append(concept[\"class_data_dir\"])\n class_prompt.append(concept[\"class_prompt\"])\n except KeyError:\n raise KeyError(\n \"`class_data_dir` or `class_prompt` not found in concepts_list while using \"\n \"`with_prior_preservation`.\"\n )\n else:\n if \"class_data_dir\" in concept:\n warnings.warn(\n \"Ignoring `class_data_dir` key, to use it you need to enable `with_prior_preservation`.\"\n )\n if \"class_prompt\" in concept:\n warnings.warn(\n \"Ignoring `class_prompt` key, to use it you need to enable `with_prior_preservation`.\"\n )\n\n if args.validation_steps:\n args.validation_prompt.append(concept.get(\"validation_prompt\", None))\n args.validation_number_images.append(concept.get(\"validation_number_images\", 4))\n args.validation_negative_prompt.append(concept.get(\"validation_negative_prompt\", None))\n args.validation_inference_steps.append(concept.get(\"validation_inference_steps\", 25))\n args.validation_guidance_scale.append(concept.get(\"validation_guidance_scale\", 7.5))\n else:\n # Parse instance and class inputs, and double check that lengths match\n instance_data_dir = args.instance_data_dir.split(\",\")\n instance_prompt = args.instance_prompt.split(\",\")\n assert all(\n x == len(instance_data_dir) for x in [len(instance_data_dir), len(instance_prompt)]\n ), \"Instance data dir and prompt inputs are not of the same length.\"\n\n if args.with_prior_preservation:\n class_data_dir = args.class_data_dir.split(\",\")\n class_prompt = args.class_prompt.split(\",\")\n assert all(\n x == len(instance_data_dir)\n for x in [len(instance_data_dir), len(instance_prompt), len(class_data_dir), len(class_prompt)]\n ), \"Instance & class data dir or prompt inputs are not of the same length.\"\n\n if args.validation_steps:\n validation_prompts = args.validation_prompt.split(\",\")\n num_of_validation_prompts = len(validation_prompts)\n args.validation_prompt = validation_prompts\n args.validation_number_images = [args.validation_number_images] * num_of_validation_prompts\n\n negative_validation_prompts = [None] * num_of_validation_prompts\n if args.validation_negative_prompt:\n negative_validation_prompts = args.validation_negative_prompt.split(\",\")\n while len(negative_validation_prompts) < num_of_validation_prompts:\n negative_validation_prompts.append(None)\n args.validation_negative_prompt = negative_validation_prompts\n\n assert num_of_validation_prompts == len(\n negative_validation_prompts\n ), \"The length of negative prompts for validation is greater than the number of validation prompts.\"\n args.validation_inference_steps = [args.validation_inference_steps] * num_of_validation_prompts\n args.validation_guidance_scale = [args.validation_guidance_scale] * num_of_validation_prompts\n\n # Make one log on every process with the configuration for debugging.\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO,\n )\n logger.info(accelerator.state, main_process_only=False)\n if accelerator.is_local_main_process:\n datasets.utils.logging.set_verbosity_warning()\n transformers.utils.logging.set_verbosity_warning()\n diffusers.utils.logging.set_verbosity_info()\n else:\n datasets.utils.logging.set_verbosity_error()\n transformers.utils.logging.set_verbosity_error()\n diffusers.utils.logging.set_verbosity_error()\n\n # If passed along, set the training seed now.\n if args.seed is not None:\n set_seed(args.seed)\n\n # Generate class images if prior preservation is enabled.\n if args.with_prior_preservation:\n for i in range(len(class_data_dir)):\n class_images_dir = Path(class_data_dir[i])\n if not class_images_dir.exists():\n class_images_dir.mkdir(parents=True)\n cur_class_images = len(list(class_images_dir.iterdir()))\n\n if cur_class_images < args.num_class_images:\n torch_dtype = torch.float16 if accelerator.device.type == \"cuda\" else torch.float32\n if args.prior_generation_precision == \"fp32\":\n torch_dtype = torch.float32\n elif args.prior_generation_precision == \"fp16\":\n torch_dtype = torch.float16\n elif args.prior_generation_precision == \"bf16\":\n torch_dtype = torch.bfloat16\n pipeline = DiffusionPipeline.from_pretrained(\n args.pretrained_model_name_or_path,\n torch_dtype=torch_dtype,\n safety_checker=None,\n revision=args.revision,\n )\n pipeline.set_progress_bar_config(disable=True)\n\n num_new_images = args.num_class_images - cur_class_images\n logger.info(f\"Number of class images to sample: {num_new_images}.\")\n\n sample_dataset = PromptDataset(class_prompt[i], num_new_images)\n sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)\n\n sample_dataloader = accelerator.prepare(sample_dataloader)\n pipeline.to(accelerator.device)\n\n for example in tqdm(\n sample_dataloader, desc=\"Generating class images\", disable=not accelerator.is_local_main_process\n ):\n images = pipeline(example[\"prompt\"]).images\n\n for ii, image in enumerate(images):\n hash_image = hashlib.sha1(image.tobytes()).hexdigest()\n image_filename = (\n class_images_dir / f\"{example['index'][ii] + cur_class_images}-{hash_image}.jpg\"\n )\n image.save(image_filename)\n\n # Clean up the memory deleting one-time-use variables.\n del pipeline\n del sample_dataloader\n del sample_dataset\n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n\n # Handle the repository creation\n if accelerator.is_main_process:\n if args.output_dir is not None:\n makedirs(args.output_dir, exist_ok=True)\n\n if args.push_to_hub:\n repo_id = create_repo(\n repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token\n ).repo_id\n\n # Load the tokenizer\n tokenizer = None\n if args.tokenizer_name:\n tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)\n elif args.pretrained_model_name_or_path:\n tokenizer = AutoTokenizer.from_pretrained(\n args.pretrained_model_name_or_path,\n subfolder=\"tokenizer\",\n revision=args.revision,\n use_fast=False,\n )\n\n # import correct text encoder class\n text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)\n\n # Load scheduler and models\n noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder=\"scheduler\")\n text_encoder = text_encoder_cls.from_pretrained(\n args.pretrained_model_name_or_path, subfolder=\"text_encoder\", revision=args.revision\n )\n vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder=\"vae\", revision=args.revision)\n unet = UNet2DConditionModel.from_pretrained(\n args.pretrained_model_name_or_path, subfolder=\"unet\", revision=args.revision\n )\n\n vae.requires_grad_(False)\n if not args.train_text_encoder:\n text_encoder.requires_grad_(False)\n\n if args.enable_xformers_memory_efficient_attention:\n if is_xformers_available():\n unet.enable_xformers_memory_efficient_attention()\n else:\n raise ValueError(\"xformers is not available. Make sure it is installed correctly\")\n\n if args.gradient_checkpointing:\n unet.enable_gradient_checkpointing()\n if args.train_text_encoder:\n text_encoder.gradient_checkpointing_enable()\n\n # Enable TF32 for faster training on Ampere GPUs,\n # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices\n if args.allow_tf32:\n torch.backends.cuda.matmul.allow_tf32 = True\n\n if args.scale_lr:\n args.learning_rate = (\n args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes\n )\n\n # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs\n if args.use_8bit_adam:\n try:\n import bitsandbytes as bnb\n except ImportError:\n raise ImportError(\n \"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`.\"\n )\n\n optimizer_class = bnb.optim.AdamW8bit\n else:\n optimizer_class = torch.optim.AdamW\n\n # Optimizer creation\n params_to_optimize = (\n itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()\n )\n optimizer = optimizer_class(\n params_to_optimize,\n lr=args.learning_rate,\n betas=(args.adam_beta1, args.adam_beta2),\n weight_decay=args.adam_weight_decay,\n eps=args.adam_epsilon,\n )\n\n # Dataset and DataLoaders creation:\n train_dataset = DreamBoothDataset(\n instance_data_root=instance_data_dir,\n instance_prompt=instance_prompt,\n class_data_root=class_data_dir,\n class_prompt=class_prompt,\n tokenizer=tokenizer,\n size=args.resolution,\n center_crop=args.center_crop,\n )\n\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.train_batch_size,\n shuffle=True,\n collate_fn=lambda examples: collate_fn(len(instance_data_dir), examples, args.with_prior_preservation),\n num_workers=1,\n )\n\n # Scheduler and math around the number of training steps.\n overrode_max_train_steps = False\n num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)\n if args.max_train_steps is None:\n args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch\n overrode_max_train_steps = True\n\n lr_scheduler = get_scheduler(\n args.lr_scheduler,\n optimizer=optimizer,\n num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,\n num_training_steps=args.max_train_steps * accelerator.num_processes,\n num_cycles=args.lr_num_cycles,\n power=args.lr_power,\n )\n\n # Prepare everything with our `accelerator`.\n if args.train_text_encoder:\n unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(\n unet, text_encoder, optimizer, train_dataloader, lr_scheduler\n )\n else:\n unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(\n unet, optimizer, train_dataloader, lr_scheduler\n )\n\n # For mixed precision training we cast the text_encoder and vae weights to half-precision\n # as these models are only used for inference, keeping weights in full precision is not required.\n weight_dtype = torch.float32\n if accelerator.mixed_precision == \"fp16\":\n weight_dtype = torch.float16\n elif accelerator.mixed_precision == \"bf16\":\n weight_dtype = torch.bfloat16\n\n # Move vae and text_encoder to device and cast to weight_dtype\n vae.to(accelerator.device, dtype=weight_dtype)\n if not args.train_text_encoder:\n text_encoder.to(accelerator.device, dtype=weight_dtype)\n\n # We need to recalculate our total training steps as the size of the training dataloader may have changed.\n num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)\n if overrode_max_train_steps:\n args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch\n # Afterwards we recalculate our number of training epochs\n args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)\n\n # We need to initialize the trackers we use, and also store our configuration.\n # The trackers initialize automatically on the main process.\n if accelerator.is_main_process:\n accelerator.init_trackers(\"dreambooth\", config=vars(args))\n\n # Train!\n total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps\n\n logger.info(\"***** Running training *****\")\n logger.info(f\" Num examples = {len(train_dataset)}\")\n logger.info(f\" Num batches each epoch = {len(train_dataloader)}\")\n logger.info(f\" Num Epochs = {args.num_train_epochs}\")\n logger.info(f\" Instantaneous batch size per device = {args.train_batch_size}\")\n logger.info(f\" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}\")\n logger.info(f\" Gradient Accumulation steps = {args.gradient_accumulation_steps}\")\n logger.info(f\" Total optimization steps = {args.max_train_steps}\")\n global_step = 0\n first_epoch = 0\n\n # Potentially load in the weights and states from a previous save\n if args.resume_from_checkpoint:\n if args.resume_from_checkpoint != \"latest\":\n path = basename(args.resume_from_checkpoint)\n else:\n # Get the mos recent checkpoint\n dirs = listdir(args.output_dir)\n dirs = [d for d in dirs if d.startswith(\"checkpoint\")]\n dirs = sorted(dirs, key=lambda x: int(x.split(\"-\")[1]))\n path = dirs[-1] if len(dirs) > 0 else None\n\n if path is None:\n accelerator.print(\n f\"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run.\"\n )\n args.resume_from_checkpoint = None\n else:\n accelerator.print(f\"Resuming from checkpoint {path}\")\n accelerator.load_state(join(args.output_dir, path))\n global_step = int(path.split(\"-\")[1])\n\n resume_global_step = global_step * args.gradient_accumulation_steps\n first_epoch = global_step // num_update_steps_per_epoch\n resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)\n\n # Only show the progress bar once on each machine.\n progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)\n progress_bar.set_description(\"Steps\")\n\n for epoch in range(first_epoch, args.num_train_epochs):\n unet.train()\n if args.train_text_encoder:\n text_encoder.train()\n for step, batch in enumerate(train_dataloader):\n # Skip steps until we reach the resumed step\n if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:\n if step % args.gradient_accumulation_steps == 0:\n progress_bar.update(1)\n continue\n\n with accelerator.accumulate(unet):\n # Convert images to latent space\n latents = vae.encode(batch[\"pixel_values\"].to(dtype=weight_dtype)).latent_dist.sample()\n latents = latents * vae.config.scaling_factor\n\n # Sample noise that we'll add to the latents\n noise = torch.randn_like(latents)\n bsz = latents.shape[0]\n # Sample a random timestep for each image\n time_steps = torch.randint(\n 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device\n )\n time_steps = time_steps.long()\n\n # Add noise to the latents according to the noise magnitude at each timestep\n # (this is the forward diffusion process)\n noisy_latents = noise_scheduler.add_noise(latents, noise, time_steps)\n\n # Get the text embedding for conditioning\n encoder_hidden_states = text_encoder(batch[\"input_ids\"])[0]\n\n # Predict the noise residual\n model_pred = unet(noisy_latents, time_steps, encoder_hidden_states).sample\n\n # Get the target for loss depending on the prediction type\n if noise_scheduler.config.prediction_type == \"epsilon\":\n target = noise\n elif noise_scheduler.config.prediction_type == \"v_prediction\":\n target = noise_scheduler.get_velocity(latents, noise, time_steps)\n else:\n raise ValueError(f\"Unknown prediction type {noise_scheduler.config.prediction_type}\")\n\n if args.with_prior_preservation:\n # Chunk the noise and model_pred into two parts and compute the loss on each part separately.\n model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)\n target, target_prior = torch.chunk(target, 2, dim=0)\n\n # Compute instance loss\n loss = F.mse_loss(model_pred.float(), target.float(), reduction=\"mean\")\n\n # Compute prior loss\n prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction=\"mean\")\n\n # Add the prior loss to the instance loss.\n loss = loss + args.prior_loss_weight * prior_loss\n else:\n loss = F.mse_loss(model_pred.float(), target.float(), reduction=\"mean\")\n\n accelerator.backward(loss)\n if accelerator.sync_gradients:\n params_to_clip = (\n itertools.chain(unet.parameters(), text_encoder.parameters())\n if args.train_text_encoder\n else unet.parameters()\n )\n accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)\n optimizer.step()\n lr_scheduler.step()\n optimizer.zero_grad(set_to_none=args.set_grads_to_none)\n\n # Checks if the accelerator has performed an optimization step behind the scenes\n if accelerator.sync_gradients:\n progress_bar.update(1)\n global_step += 1\n\n if accelerator.is_main_process:\n if global_step % args.checkpointing_steps == 0:\n save_path = join(args.output_dir, f\"checkpoint-{global_step}\")\n accelerator.save_state(save_path)\n logger.info(f\"Saved state to {save_path}\")\n\n if (\n args.validation_steps\n and any(args.validation_prompt)\n and global_step % args.validation_steps == 0\n ):\n images_set = generate_validation_images(\n text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype\n )\n for images, validation_prompt in zip(images_set, args.validation_prompt):\n if len(images) > 0:\n label = str(uuid.uuid1())[:8] # generate an id for different set of images\n log_validation_images_to_tracker(\n images, label, validation_prompt, accelerator, global_step\n )\n\n logs = {\"loss\": loss.detach().item(), \"lr\": lr_scheduler.get_last_lr()[0]}\n progress_bar.set_postfix(**logs)\n accelerator.log(logs, step=global_step)\n\n if global_step >= args.max_train_steps:\n break\n\n # Create the pipeline using the trained modules and save it.\n accelerator.wait_for_everyone()\n if accelerator.is_main_process:\n pipeline = DiffusionPipeline.from_pretrained(\n args.pretrained_model_name_or_path,\n unet=accelerator.unwrap_model(unet),\n text_encoder=accelerator.unwrap_model(text_encoder),\n revision=args.revision,\n )\n pipeline.save_pretrained(args.output_dir)\n\n if args.push_to_hub:\n upload_folder(\n repo_id=repo_id,\n folder_path=args.output_dir,\n commit_message=\"End of training\",\n ignore_patterns=[\"step_*\", \"epoch_*\"],\n )\n\n accelerator.end_training()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n","repo_name":"huggingface/diffusers","sub_path":"examples/research_projects/multi_subject_dreambooth/train_multi_subject_dreambooth.py","file_name":"train_multi_subject_dreambooth.py","file_ext":"py","file_size_in_byte":49694,"program_lang":"python","lang":"en","doc_type":"code","stars":19077,"dataset":"github-code","pt":"85"} +{"seq_id":"13589481410","text":"import mmh3\nimport struct\n\nlocal_file_name='doc'\nkey_size=96\nhash_size=2147483640\ndim=64\nwith open(local_file_name, 'rb') as bin_file:\n while True:\n key = bin_file.read(key_size)\n if len(key) < key_size:\n break\n key = key.strip(b'\\x00').decode('utf-8')\n #decode('utf-8')\n vector = bin_file.read(dim*4)\n vector = struct.unpack(\"{}f\".format(dim), vector) # vector type is tuple\n ## mmh3.hash(key) return a signed 32 int, may < 0. need & 0xffffffff\n hash_value = (mmh3.hash(key) & 0xffffffff) % hash_size\n print (key + \"\\t\" + str(hash_value))\n","repo_name":"Serene-Guo/python_utils","sub_path":"murmurhash_test.py","file_name":"murmurhash_test.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4379497064","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404, render,redirect,get_list_or_404,HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login\nfrom .forms import LoginForm, RegisterForm\n\ndef register_user(request):\n form = RegisterForm()\n if request.method=='POST':\n # print(request.POST)\n form= RegisterForm(request.POST)\n if form.is_valid():\n form.save_user()\n return redirect(\"index\")\n return render(\n request=request,\n template_name='user/register.html',\n context={\n 'form':form\n }\n )\n\ndef login_user(request):\n form = LoginForm()\n message = \"\"\n if request.method =='POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n # Hàm authenticate nhận username và password\n # Nếu thông tin đúng thì return User Object\n # Không đúng thì return None\n user = authenticate(\n username=form.cleaned_data['username'],\n password= form.cleaned_data['password'],\n )\n if user: # Kiem tra not None la True\n # print('Thông tin đúng')\n # Thông tin đúng giữ trạng thái đăng nhập user\n login(request,user)\n # Thay vì kiểm tra redirect về index, phải kiểm tra cái tham số getnext trên web\n if request.GET.get('next'):\n return HttpResponseRedirect(request.GET.get('next'))\n return redirect ('index')\n else:\n # print('Thông tin sai')\n message = \" Thông tin nhập không đúng.Vui lòng nhập lại\"\n\n return render(\n request=request,\n template_name='user/login.html',\n context={\n 'form':form,\n 'message' : message\n }\n )\n\n\n\n","repo_name":"ThaoHn18/mini2","sub_path":"myapp/user_views.py","file_name":"user_views.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2058223531","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n Created by Ênio Viana at 10/10/2021 at 16:20:46\n Project: processos-estocasticos [out, 2021]\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Plot:\n\n @staticmethod\n def plot_histogram(vector: np.ndarray, sigma: [int, float], mu: [int, float], title: str):\n count, bins, ignored = plt.hist(vector, 30, density=True)\n plt.plot(bins, 1 / (sigma * np.sqrt(2 * np.pi)) *\n np.exp(- (bins - mu) ** 2 / (2 * sigma ** 2)),\n linewidth=2, color='r')\n plt.title(title)\n plt.show()\n\n @staticmethod\n def plot_scatter(vector_x: np.ndarray, vector_y: np.ndarray, title: str):\n plt.scatter(vector_x, vector_y, s=50, alpha=0.5)\n plt.title(title)\n plt.show()\n","repo_name":"eniocc/processos-estocasticos","sub_path":"atividade_01/Plot.py","file_name":"Plot.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38791599228","text":"\"\"\"\nAR_OpenRenderFolder\n\nAuthor: Arttu Rautio (aturtur)\nWebsite: http://aturtur.com/\nName-US: AR_OpenRenderFolder\nVersion: 1.0\nDescription-US: Opens folder where project is rendered\nNOTE: Does not support all of the tokens!\n\nWritten for Maxon Cinema 4D R21.207\nPython version 2.7.14\n\"\"\"\n# Libraries\nimport c4d\nimport os\nimport subprocess\nimport re\n\n\n# Functions\ndef CheckFolders(path):\n folders = path.split(\"..\\\\\")\n if len(folders)>1:\n p = doc.GetDocumentPath()\n for x in range(0, len(folders)-1):\n p = os.path.dirname(p)\n path = p + \"\\\\\" + folders[-1]\n current = path.split(\".\\\\\")\n if len(current)>1:\n path = doc.GetDocumentPath() + \"\\\\\" + current[1]\n return path\n\ndef main():\n doc = c4d.documents.GetActiveDocument() # Get active document\n bd = doc.GetActiveBaseDraw() # Get active base draw\n renderData = doc.GetActiveRenderData() # Get document active render data\n \n renderPath = renderData[c4d.RDATA_PATH]\n width = renderData[c4d.RDATA_XRES_VIRTUAL]\n height = renderData[c4d.RDATA_YRES_VIRTUAL]\n fps = renderData[c4d.RDATA_FRAMERATE]\n\n take = doc.GetTakeData().GetCurrentTake().GetName()\n camera = bd.GetSceneCamera(doc).GetName()\n \n tokenPrj = os.path.splitext(doc.GetDocumentName())[0]\n tokenPrj = str(tokenPrj.replace(\" \", \"_\"))\n tokenRes = str(int(width))+\"x\"+str(int(height))\n tokenFps = str(int(fps))\n tokenTake = str(take.replace(\" \", \"_\"))\n tokenCamera = str(camera.replace(\" \", \"_\"))\n\n renderPath = renderPath.replace(\"/\",\"\\\\\")\n\n path = renderPath.replace(\"$prj\", tokenPrj) # Solve project name ($prj) token\n path = path.replace(\"$res\", tokenRes) # Solve esolution ($res) token\n path = path.replace(\"$fps\", tokenFps) # Solve frame rate ($fps) token\n path = path.replace(\"$take\", tokenTake) # Solve take ($take) token\n path = path.replace(\"$camera\", tokenCamera) # Solve camera ($camera) token\n\n path = CheckFolders(path) \n path = os.path.dirname(path)\n \n subprocess.Popen(r'explorer \"'+path+'\"') # Open project folder\n\n# Execute main()\nif __name__=='__main__':\n main()","repo_name":"aturtur/cinema4d-scripts","sub_path":"AR_Scripts_1.0.16_R21_Deprecated/AR_OpenRenderFolder.py","file_name":"AR_OpenRenderFolder.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":328,"dataset":"github-code","pt":"85"} +{"seq_id":"22186336734","text":"from graphene_django.utils.testing import GraphQLTestCase\n\nfrom app_utils.testdata_factories import UserMainFactory\n\n\nclass TestAll(GraphQLTestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.user = UserMainFactory()\n\n def test_user_tokens(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q {\n esiUserTokens {\n id\n character {\n id\n }\n }\n }\n '''\n )\n\n self.assertEqual(self.user.token_set.count(), 1)\n\n token = self.user.token_set.first()\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'esiUserTokens': [\n {\n 'id': str(token.pk),\n 'character': {\n 'id': str(self.user.profile.main_character.pk)\n }\n }\n ]\n }\n }\n )\n","repo_name":"Maestro-Zacht/allianceauth-graphql","sub_path":"allianceauth_graphql/tests/test_esi.py","file_name":"test_esi.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"39195992311","text":"import pandas as pd\nimport numpy as np\n\nimport torch\nfrom sklearn.metrics import log_loss, roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nfrom deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names\n\nclass DeepFMDataLoader:\n def __init__(self, *, sparse_features, dense_features):\n self._sparse_feats = sparse_features\n self._dense_feats = dense_features\n \n def load(self, dataset):\n nn_input = pd.DataFrame()\n nn_input[self._sparse_feats] = dataset[self._sparse_feats]\n nn_input[self._dense_feats] = dataset[self._dense_feats]\n \n for feat in self._sparse_feats:\n encoder = LabelEncoder()\n nn_input[feat] = encoder.fit_transform(nn_input[feat])\n \n mms = MinMaxScaler(feature_range=(0,1))\n nn_input[self._dense_feats] = mms.fit_transform(nn_input[self._dense_feats])\n \n # problems may be here\n sparse_feature_columns = [\n SparseFeat(feat, vocabulary_size=nn_input[feat].nunique(), embedding_dim=4) \n for i, feat in enumerate(self._sparse_feats)\n ]\n\n dense_feature_columns = [DenseFeat(feat, 1,) for feat in self._dense_feats]\n \n dnn_feat_cols = sparse_feature_columns + dense_feature_columns\n linear_feat_cols = sparse_feature_columns + dense_feature_columns\n \n feat_names = get_feature_names(linear_feat_cols + dnn_feat_cols)\n return nn_input, dnn_feat_cols, linear_feat_cols, feat_names\n \n \ndef merge_feats(feats_a, feats_b):\n assert len(feats_a) == len(feats_b)\n merged = []\n for feat_a, feat_b in zip(feats_a, feats_b):\n if isinstance(feat_a, DenseFeat):\n continue\n if feat_a.vocabulary_size >= feat_b.vocabulary_size:\n merged.append(feat_a)\n else:\n merged.append(feat_b)\n return merged\n \n\nclass NNModelWrapper:\n def __init__(self, trained_nn):\n self._nn = trained_nn\n\n def predict_rating_matrix(self, nn_input, merged_df):\n y = self._nn.predict(nn_input)\n result = pd.DataFrame()\n result[\"rating\"] = y.reshape((len(y),))\n result[\"user_id\"] = merged_df[\"user_id\"]\n result[\"item_id\"] = merged_df[\"item_id\"]\n output_matrix = result.pivot(index=\"user_id\", columns=\"item_id\", values=\"rating\")\n return output_matrix","repo_name":"vldpro/SynEvaRec","sub_path":"modules/modules/deepfm.py","file_name":"deepfm.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"3410090927","text":"\r\ndef crime_standardization(crime_group, city_name, crime_assoc_list):\r\n city_crime_group = {\r\n new_key: new_val\r\n for keys, new_val in crime_assoc_list\r\n for new_key in keys\r\n }\r\n crime_group[city_name] = city_crime_group\r\n\r\n\r\nassoc_list1 = [ ([\"01A\"], \"murder\"), ([\"02\"], \"sexual assault\"), ([\"04A\", \"04B\"], \"aggravated assault\"),\r\n ([\"03\"], \"robbery\"), ([\"05\"], \"burglary\"), ([\"06\"], \"theft\"), ([\"07\"], \"motor vehicle theft\") ]\r\n\r\nassoc_list2 = [ ([\"11A\", \"11B\", \"11C\"], \"sexual assault\"), ([\"09A\"], \"murder\"), ([\"13A\"], \"aggravated assault\"), ([\"220\"], \"burglary\"),\r\n ([\"120\"], \"robbery\"), ([\"23A\", \"23B\", \"23C\", \"23D\", \"23E\", \"23F\", \"23G\", \"23H\"], \"theft\"), ([\"240\"], \"motor vehicle theft\") ]\r\n\r\nassoc_list3 = [ ([\"SEXUAL ABUSE 3,2\", \"SEXUAL ABUSE\", \"SODOMY 1\", \"RAPE 1\", \"RAPE 3\", \"RAPE 2\"], \"sexual assault\"), ([\"MURDER,UNCLASSIFIED\"], \"murder\"),\r\n ([\"ASSAULT 2,1,UNCLASSIFIED\", \"ASSAULT 3\"], \"aggravated assault\"), ([\"BURGLARY,UNCLASSIFIED,UNKNOWN\", \"BURGLARY,RESIDENCE,NIGHT\"], \"burglary\"),\r\n ([\"ROBBERY,OPEN AREA UNCLASSIFIED\"], \"robbery\"), ([\"LARCENY,GRAND FROM PERSON,UNCL\", \"LARCENY,GRAND FROM OPEN AREAS, UNATTENDED\", \"LARCENY,PETIT FROM OPEN AREAS,\"], \"theft\"),\r\n ([\"LARCENY,GRAND OF AUTO\"], \"motor vehicle theft\") ]\r\n\r\ncrime_type_fields = {\"Chicago\" : \"fbi_code\",\r\n \"Austin\" : \"ucr_category\",\r\n \"New York\" : \"pd_desc\"\r\n }\r\n\r\n\r\n","repo_name":"jackboller1/Tourist_Watch","sub_path":"crime_grouping.py","file_name":"crime_grouping.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32258993407","text":"#!/usr/bin/python3\n\nimport sys;\nimport cgi;\nimport cgitb;\nimport os;\nimport cgicommon;\nimport urllib.request, urllib.parse, urllib.error;\nimport re;\n\ndef show_now_showing_frame(tourney):\n cgicommon.writeln(\"\" % (urllib.parse.quote_plus(tourney.get_name())))\n\ndef show_view_preview(tourney, form, selected_view):\n cgicommon.writeln(\"\" % (urllib.parse.quote_plus(tourney.get_name()), selected_view))\n\ncheckbox_to_assoc_field = {\n \"standings_videprinter_spell_big_scores\" : \"standings_videprinter_big_score_min\"\n}\n\nassoc_field_to_checkbox = {\n \"standings_videprinter_big_score_min\" : \"standings_videprinter_spell_big_scores\"\n}\n\ndef show_view_option_controls(tourney, form, options):\n if not options:\n return\n cgicommon.writeln(\"
Options for this screen mode
\")\n for o in options:\n cgicommon.writeln(\"
\")\n name_escaped = \"teleost_option_\" + cgicommon.escape(o.name, True)\n if o.value is None:\n value_escaped = \"\"\n else:\n value_escaped = cgicommon.escape(str(o.value), True)\n\n desc_escaped = cgicommon.escape(o.desc)\n\n # If $INDENT exists, replace it with a checkbox-width of empty space\n desc_escaped = re.sub(\"\\\\$INDENT\\\\b\", \"\" % (name_escaped), desc_escaped, 0)\n\n m = re.search(\"\\\\$CONTROL\\\\b\", desc_escaped)\n if m:\n before_control = desc_escaped[0:m.start()]\n after_control = desc_escaped[m.end():]\n else:\n before_control = desc_escaped\n after_control = \"\"\n\n cgicommon.writeln(\"\" % (name_escaped, before_control))\n\n if o.name in checkbox_to_assoc_field:\n onclick_value = \"var numberField = document.getElementById('%s'); var checkboxField = document.getElementById('%s'); numberField.disabled = !checkboxField.checked;\" % (\"teleost_option_\" + checkbox_to_assoc_field[o.name], name_escaped)\n else:\n onclick_value = None\n\n disabled_attr = \"\"\n if o.name in assoc_field_to_checkbox:\n for oo in options:\n if oo.name == assoc_field_to_checkbox[o.name]:\n try:\n value = int(oo.value)\n except ValueError:\n value = 0\n\n if value:\n disabled_attr = \"\"\n else:\n disabled_attr = \"disabled\"\n break\n\n if o.control_type == countdowntourney.CONTROL_NUMBER:\n cgicommon.writeln(\"\" % (name_escaped, name_escaped, value_escaped, disabled_attr))\n elif o.control_type == countdowntourney.CONTROL_CHECKBOX:\n if o.value is not None and int(o.value):\n checked_str = \"checked\"\n else:\n checked_str = \"\"\n cgicommon.writeln(\"\" % (\n name_escaped,\n name_escaped,\n checked_str,\n \"\" if not onclick_value\n else \"onclick=\\\"\" + re.sub(\"\\\"\", \"\\\\\\\"\", onclick_value, 0) + \"\\\"\"))\n cgicommon.writeln(\"\" % (\"exists_checkbox_\" + name_escaped))\n\n cgicommon.writeln(\"\" % (name_escaped, after_control))\n\n cgicommon.writeln(\"
\")\n\n\ncgitb.enable();\n\ncgicommon.writeln(\"Content-Type: text/html; charset=utf-8\");\ncgicommon.writeln(\"\");\n\nbaseurl = \"/cgi-bin/displayoptions.py\";\nform = cgi.FieldStorage();\ntourney_name = form.getfirst(\"tourney\");\n\ntourney = None;\nrequest_method = os.environ.get(\"REQUEST_METHOD\", \"\");\n\ncgicommon.set_module_path();\n\nimport countdowntourney;\n\ncgicommon.print_html_head(\"Display setup: \" + str(tourney_name), \"style.css\");\n\ncgicommon.writeln(\"\");\n\ncgicommon.writeln(\"\")\n\ncgicommon.assert_client_from_localhost()\n\nif tourney_name is None:\n cgicommon.writeln(\"

No tourney specified

\");\n cgicommon.writeln(\"

Home

\");\n cgicommon.writeln(\"\")\n cgicommon.writeln(\"\")\n sys.exit(0)\n\ntry:\n tourney = countdowntourney.tourney_open(tourney_name, cgicommon.dbdir);\n\n teleost_modes = tourney.get_teleost_modes();\n\n selected_view = form.getfirst(\"selectedview\")\n if selected_view is not None:\n try:\n selected_view = int(selected_view)\n except ValueError:\n selected_view = None\n\n if selected_view is not None and (selected_view < 0 or selected_view >= len(teleost_modes)):\n selected_view = None\n\n if selected_view is None or selected_view == \"\":\n selected_view = tourney.get_current_teleost_mode()\n\n mode_info = teleost_modes[selected_view]\n\n if request_method == \"POST\":\n if \"setoptions\" in form:\n # Set per-view options\n for name in list(form.keys()):\n if name.startswith(\"teleost_option_\"):\n option_name = name[15:]\n option_value = form.getfirst(name)\n tourney.set_attribute(option_name, option_value)\n elif name.startswith(\"exists_checkbox_teleost_option_\"):\n cgi_option_name = name[16:]\n if cgi_option_name not in form:\n tourney.set_attribute(cgi_option_name[15:], 0)\n if \"setbanner\" in form:\n text = form.getfirst(\"bannertext\")\n if not text:\n tourney.clear_banner_text()\n else:\n tourney.set_banner_text(text)\n elif \"clearbanner\" in form:\n tourney.clear_banner_text()\n if \"setfontprofile\" in form:\n font_profile_id = form.getfirst(\"fontprofileselect\")\n if font_profile_id is not None:\n try:\n font_profile_id = int(font_profile_id)\n tourney.set_display_font_profile_id(font_profile_id)\n except ValueError:\n pass\n if \"switchview\" in form:\n tourney.set_teleost_mode(selected_view)\n teleost_modes = tourney.get_teleost_modes();\n mode_info = teleost_modes[selected_view]\n\n banner_text = tourney.get_banner_text()\n if banner_text is None:\n banner_text = \"\"\n\n cgicommon.show_sidebar(tourney);\n\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"

Display Setup

\");\n\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"\"\"\n \n Open Display Window\n \\\"Opens\n \"\"\" % (urllib.parse.quote_plus(tourney.name)));\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\" % (urllib.parse.quote_plus(tourney_name), selected_view))\n cgicommon.writeln(\"Banner text: \" % (cgicommon.escape(banner_text, True)))\n cgicommon.writeln(\"\")\n cgicommon.writeln(\"\")\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\")\n\n display_font_profile = tourney.get_display_font_profile_id()\n font_profile_descs = countdowntourney.DISPLAY_FONT_PROFILES\n cgicommon.writeln(\"\"\"
\n
\n\n\")\n cgicommon.writeln(\"\")\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\")\n show_now_showing_frame(tourney)\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"Now showing\")\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\")\n show_view_preview(tourney, form, selected_view)\n\n cgicommon.writeln(\"
\")\n if teleost_modes[selected_view].get(\"selected\", False):\n if selected_view == 0:\n cgicommon.writeln(\"Automatic view\")\n else:\n cgicommon.writeln(\"Selected view\");\n else:\n cgicommon.writeln(\"
\" % (urllib.parse.quote_plus(tourney_name), selected_view))\n cgicommon.writeln(\"\" % (\"this screen mode\" if selected_view != 0 else \"automatic control\"))\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\") # viewpreviewswitch\n\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\") # viewpreviewandoptions\n\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\") # viewselection\n\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\")\n #cgicommon.writeln(\"
Select screen mode
\")\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"\")\n cgicommon.write(cgicommon.escape(mode_info[\"name\"]))\n cgicommon.writeln(\": \");\n cgicommon.writeln(cgicommon.escape(mode_info[\"desc\"]))\n cgicommon.writeln(\"
\") # viewdetailstext\n\n cgicommon.writeln(\"
\") # viewdetails\n\n\n menu_row_size = 5\n teleost_modes_sorted = sorted(teleost_modes, key=lambda x : (x.get(\"menuorder\", 100000), x[\"num\"], x[\"name\"]))\n\n for idx in range(len(teleost_modes_sorted)):\n mode = teleost_modes_sorted[idx]\n if idx % menu_row_size == 0:\n if idx > 0:\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\")\n classes = [\"viewmenucell\"]\n if mode.get(\"selected\", False):\n # This is the view currently showing on the public display\n classes.append(\"viewmenucellshowing\")\n elif mode[\"num\"] == selected_view:\n # This is the view the user has clicked in the display options page\n classes.append(\"viewmenucellselected\")\n else:\n # This is neither showing nor selected\n classes.append(\"viewmenucellbystander\")\n cgicommon.writeln(\"\")\n\n if len(teleost_modes) > 0:\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\") #viewmenu\n\n options = tourney.get_teleost_options(mode=selected_view)\n if options:\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\" % (urllib.parse.quote_plus(tourney_name), selected_view))\n cgicommon.writeln(\"
\")\n show_view_option_controls(tourney, form, options)\n cgicommon.writeln(\"
\")\n\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"\")\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\") # viewsubmitbuttons\n\n cgicommon.writeln(\"
\")\n cgicommon.writeln(\"
\") # viewcontrols\n\n cgicommon.writeln(\"\") # mainpane\n\nexcept countdowntourney.TourneyException as e:\n cgicommon.show_tourney_exception(e);\n\ncgicommon.writeln(\"\");\n\nsys.exit(0);\n\n","repo_name":"aibolem/atropine","sub_path":"webroot/cgi-bin/displayoptions.py","file_name":"displayoptions.py","file_ext":"py","file_size_in_byte":13800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"85"} +{"seq_id":"72827261079","text":"import os\nimport re\n\nimport hdf_utils\n\n\nclass ConfigItem(object):\n def __init__(self, index, line):\n self.index = index\n self.line = line\n\n\nclass HdfDotConfigFile(object):\n def __init__(self, dot_config_path):\n self.file_path = dot_config_path\n if os.path.exists(dot_config_path):\n self.lines = hdf_utils.read_file_lines(dot_config_path)\n self.dot_config_exist = True\n else:\n self.lines = []\n self.dot_config_exist = False\n self.cache = {}\n self.hdf_item = 'LOSCFG_DRIVERS_HDF'\n self.prefix = 'LOSCFG_'\n\n def save(self):\n if not self.dot_config_exist:\n return\n with open(self.file_path, 'r+', newline='\\n') as file:\n file.truncate()\n file.write(''.join(self.lines))\n\n def _update_cache(self, item, index, line):\n self.cache[item] = ConfigItem(index, line)\n\n def _find(self, item):\n if item in self.cache:\n index = self.cache[item].index\n line = self.cache[item].line\n return index, line\n for index, line in enumerate(self.lines):\n item_pattern = r'%s\\s*(=|is)' % item\n if re.search(item_pattern, line):\n line_ = line.strip()\n self._update_cache(item, index, line_)\n return index, line_\n return 0, ''\n\n @staticmethod\n def _is_line_enabled(line):\n if line.strip().startswith('#'):\n return False\n return True\n\n def _enable(self, item):\n if not item:\n return\n new_line = '%s=y\\n' % item\n index, line = self._find(item)\n if line:\n if self._is_line_enabled(line):\n return\n self.lines[index] = new_line\n self._update_cache(item, index, new_line)\n return\n else:\n count = len(self.lines)\n self.lines.append(new_line)\n self._update_cache(item, count, new_line)\n\n def _disable(self, item):\n if not item:\n return\n new_line = '# %s is not set\\n' % item\n index, line = self._find(item)\n if not line:\n return\n if not self._is_line_enabled(line):\n return\n self.lines[index] = new_line\n self._update_cache(item, index, new_line)\n\n def _is_enabled(self, item):\n if not item:\n return False\n index, line = self._find(item)\n if not line:\n return False\n return self._is_line_enabled(line)\n\n def _add_prefix(self, item):\n if not item.startswith(self.prefix):\n item = '%s%s' % (self.prefix, item)\n return item\n\n def is_enabled(self, item, depends_on_item):\n if item:\n item = self._add_prefix(item)\n if depends_on_item:\n depends_on_item = self._add_prefix(depends_on_item)\n if depends_on_item:\n if not self._is_enabled(depends_on_item):\n return False\n return self._is_enabled(item)\n\n def enable(self, item, depends_on_item):\n if item:\n item = self._add_prefix(item)\n if depends_on_item:\n depends_on_item = self._add_prefix(depends_on_item)\n self._enable(self.hdf_item)\n self._enable(depends_on_item)\n self._enable(item)\n\n def disable(self, item):\n if item:\n item = self._add_prefix(item)\n self._disable(item)\n","repo_name":"fenwii/OpenHarmony","sub_path":"Openharmony v1.0/drivers/hdf/lite/tools/hdf_dev_eco_tool/command_line/hdf_dot_config_file.py","file_name":"hdf_dot_config_file.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","stars":596,"dataset":"github-code","pt":"85"} +{"seq_id":"35809508097","text":"import pygame\nfrom pygame.locals import *\n\nSYS_CONFIGS = {\n 'default_fps': 60,\n 'fullscreen_mode': False,\n 'window_x_size': 1280,\n 'window_y_size': 1024,\n 'window_name': '0g',\n 'tileset_path': 'assets/tilesets/',\n 'fps_draw_x': 10,\n 'fps_draw_y': 10,\n 'tool_tileviewer_max_col_size': 16,\n 'tool_tileviewer_font_colour': (0, 0, 0)\n}\n\nGAME_CONFIGS = {\n 'map_configs': {\n 'sample_map_x_size': 10,\n 'sample_map_y_size': 10,\n 'map_x': 0,\n 'map_y': 0,\n },\n 'tile_configs': {\n 'zoom_levels': (1, 2, 4),\n 'tile_size': 32,\n 'tilesets': {\n 1: {\n 'name': '',\n 'filename': 'RoboStatic.png',\n 'colorkey': (0, 0, 0),\n 'tile_width': 38,\n 'tile_height': 57,\n },\n 2: {\n 'name': '',\n 'filename': 'RoboSpin.png',\n 'colorkey': (0, 0, 0),\n 'tile_width': 56,\n 'tile_height': 88,\n },\n 3: {\n 'name': '',\n 'filename': 'RoboJump.png',\n 'colorkey': (0, 0, 0),\n 'tile_width': 42,\n 'tile_height': 63,\n },\n }\n },\n\n 'font_configs': {\n 'font_path': 'assets/fonts/',\n 'system_fonts': {\n 2: ('eight2empire.ttf', 64),\n },\n 'system_font_default': 2,\n 'system_font_size': 20,\n 'system_font_colour': (255, 255, 255),\n },\n 'default_background_colour': (16, 16, 16)\n}\n\nGAME_CONFIGS['tile_configs']['min_zoom'] = 0\nGAME_CONFIGS['tile_configs']['max_zoom'] = len(GAME_CONFIGS['tile_configs']['zoom_levels'])-1\n\nGAME_CONFIGS['map_configs']['map_window_size_x'] = SYS_CONFIGS['window_x_size'] // GAME_CONFIGS['tile_configs']['tile_size']\nGAME_CONFIGS['map_configs']['map_window_size_y'] = SYS_CONFIGS['window_y_size'] // GAME_CONFIGS['tile_configs']['tile_size']\n\nWIDGET_CONFIGS = {\n 'widget_list_line_spacing': 20,\n 'widget_default_menu_line_spacing': 80,\n 'widget_default_menu_bg_colour': (40, 40, 40),\n 'widget_default_menu_font': 2,\n 'widget_default_menu_font_colour': (255, 255, 255)\n}\n\nEVENT_CUSTOM_SWITCH_STATE = USEREVENT + 2\nEVENT_CUSTOM_CREATE_STATE = USEREVENT + 3\n","repo_name":"renton/0g","sub_path":"src/rlengine/config/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73025220759","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os\nimport time\n\nfrom absl import logging\n\n\nimport gin\nimport gym\nimport numpy as np\nimport tensorflow as tf0\nimport tensorflow.compat.v1 as tf\n\nfrom behavior_regularized_offline_rl.brac import dataset\nfrom behavior_regularized_offline_rl.brac import train_eval_utils\nfrom behavior_regularized_offline_rl.brac import utils\n\nfrom gym.wrappers import time_limit\n\nfrom tf_agents.environments import tf_py_environment\nfrom tf_agents.environments import gym_wrapper\n\n\ndef get_offline_data(tf_env):\n gym_env = tf_env.pyenv.envs[0]\n #offline_dataset = gym_env.unwrapped.get_dataset()\n offline_dataset = gym_env.get_dataset()\n dataset_size = len(offline_dataset['observations'])\n tf_dataset = dataset.Dataset(\n tf_env.observation_spec(),\n tf_env.action_spec(),\n size=dataset_size)\n observation_dtype = tf_env.observation_spec().dtype\n action_dtype = tf_env.action_spec().dtype\n\n offline_dataset['terminals'] = np.squeeze(offline_dataset['terminals'])\n offline_dataset['rewards'] = np.squeeze(offline_dataset['rewards'])\n nonterminal_steps, = np.where(\n np.logical_and(\n np.logical_not(offline_dataset['terminals']),\n np.arange(dataset_size) < dataset_size - 1))\n logging.info('Found %d non-terminal steps out of a total of %d steps.' % (\n len(nonterminal_steps), dataset_size))\n\n s1 = tf.convert_to_tensor(offline_dataset['observations'][nonterminal_steps],\n dtype=observation_dtype)\n s2 = tf.convert_to_tensor(offline_dataset['observations'][nonterminal_steps + 1],\n dtype=observation_dtype)\n a1 = tf.convert_to_tensor(offline_dataset['actions'][nonterminal_steps],\n dtype=action_dtype)\n a2 = tf.convert_to_tensor(offline_dataset['actions'][nonterminal_steps + 1],\n dtype=action_dtype)\n discount = tf.convert_to_tensor(\n 1. - offline_dataset['terminals'][nonterminal_steps + 1],\n dtype=tf.float32)\n reward = tf.convert_to_tensor(offline_dataset['rewards'][nonterminal_steps],\n dtype=tf.float32)\n\n transitions = dataset.Transition(\n s1, s2, a1, a2, discount, reward)\n\n tf_dataset.add_transitions(transitions)\n return tf_dataset\n\n\ndef env_factory(env_name):\n gym_env = gym.make(env_name)\n gym_spec = gym.spec(env_name)\n if gym_spec.max_episode_steps in [0, None]: # Add TimeLimit wrapper.\n gym_env = time_limit.TimeLimit(gym_env, max_episode_steps=1000)\n\n tf_env = tf_py_environment.TFPyEnvironment(\n gym_wrapper.GymWrapper(gym_env))\n return tf_env\n\n\n@gin.configurable\ndef train_eval_offline(\n # Basic args.\n log_dir,\n data_file,\n agent_module,\n env_name='HalfCheetah-v2',\n n_train=int(1e6),\n shuffle_steps=0,\n seed=0,\n use_seed_for_data=False,\n # Train and eval args.\n total_train_steps=int(1e6),\n summary_freq=100,\n print_freq=1000,\n save_freq=int(2e4),\n eval_freq=5000,\n n_eval_episodes=20,\n # Agent args.\n model_params=(((200, 200),), 2),\n behavior_ckpt_file=None,\n value_penalty=True,\n alpha=1.0,\n #model_params=((200, 200),),\n optimizers=(('adam', 0.001),),\n batch_size=256,\n weight_decays=(0.0,),\n update_freq=1,\n update_rate=0.005,\n discount=0.99,\n ):\n \"\"\"Training a policy with a fixed dataset.\"\"\"\n # Create tf_env to get specs.\n print('[train_eval_offline.py] env_name=', env_name)\n print('[train_eval_offline.py] data_file=', data_file)\n print('[train_eval_offline.py] agent_module=', agent_module)\n print('[train_eval_offline.py] model_params=', model_params)\n print('[train_eval_offline.py] optimizers=', optimizers)\n print('[train_eval_offline.py] bckpt_file=', behavior_ckpt_file)\n print('[train_eval_offline.py] value_penalty=', value_penalty)\n\n tf_env = env_factory(env_name)\n observation_spec = tf_env.observation_spec()\n action_spec = tf_env.action_spec()\n\n # Prepare data.\n full_data = get_offline_data(tf_env)\n\n # Split data.\n n_train = min(n_train, full_data.size)\n logging.info('n_train %s.', n_train)\n if use_seed_for_data:\n rand = np.random.RandomState(seed)\n else:\n rand = np.random.RandomState(0)\n shuffled_indices = utils.shuffle_indices_with_steps(\n n=full_data.size, steps=shuffle_steps, rand=rand)\n train_indices = shuffled_indices[:n_train]\n train_data = full_data.create_view(train_indices)\n\n # Create agent.\n agent_flags = utils.Flags(\n observation_spec=observation_spec,\n action_spec=action_spec,\n model_params=model_params,\n optimizers=optimizers,\n batch_size=batch_size,\n weight_decays=weight_decays,\n update_freq=update_freq,\n update_rate=update_rate,\n discount=discount,\n train_data=train_data)\n agent_args = agent_module.Config(agent_flags).agent_args\n my_agent_arg_dict = {}\n for k in vars(agent_args):\n my_agent_arg_dict[k] = vars(agent_args)[k]\n if 'brac_primal' in agent_module.__name__: \n my_agent_arg_dict['behavior_ckpt_file'] = behavior_ckpt_file\n my_agent_arg_dict['value_penalty'] = value_penalty\n my_agent_arg_dict['alpha'] = alpha\n print('agent:', agent_module.__name__)\n print('agent_args:', my_agent_arg_dict)\n #agent = agent_module.Agent(**vars(agent_args))\n agent = agent_module.Agent(**my_agent_arg_dict)\n agent_ckpt_name = os.path.join(log_dir, 'agent')\n\n # Restore agent from checkpoint if there exists one.\n if tf.io.gfile.exists('{}.index'.format(agent_ckpt_name)):\n logging.info('Checkpoint found at %s.', agent_ckpt_name)\n agent.restore(agent_ckpt_name)\n\n # Train agent.\n train_summary_dir = os.path.join(log_dir, 'train')\n eval_summary_dir = os.path.join(log_dir, 'eval')\n train_summary_writer = tf0.compat.v2.summary.create_file_writer(\n train_summary_dir)\n eval_summary_writers = collections.OrderedDict()\n for policy_key in agent.test_policies.keys():\n eval_summary_writer = tf0.compat.v2.summary.create_file_writer(\n os.path.join(eval_summary_dir, policy_key))\n eval_summary_writers[policy_key] = eval_summary_writer\n eval_results = []\n\n time_st_total = time.time()\n time_st = time.time()\n step = agent.global_step\n timed_at_step = step\n while step < total_train_steps:\n agent.train_step()\n step = agent.global_step\n if step % summary_freq == 0 or step == total_train_steps:\n agent.write_train_summary(train_summary_writer)\n if step % print_freq == 0 or step == total_train_steps:\n agent.print_train_info()\n if step % eval_freq == 0 or step == total_train_steps:\n time_ed = time.time()\n time_cost = time_ed - time_st\n logging.info(\n 'Training at %.4g steps/s.', (step - timed_at_step) / time_cost)\n eval_result, eval_infos = train_eval_utils.eval_policies(\n tf_env, agent.test_policies, n_eval_episodes)\n eval_results.append([step] + eval_result)\n with open(os.path.join(log_dir, 'results.txt'), 'a') as logfile:\n logfile.write(str(eval_result)+'\\n')\n logging.info('Testing at step %d:', step)\n for policy_key, policy_info in eval_infos.items():\n logging.info(utils.get_summary_str(\n step=None, info=policy_info, prefix=policy_key+': '))\n utils.write_summary(eval_summary_writers[policy_key], step, policy_info)\n time_st = time.time()\n timed_at_step = step\n if step % save_freq == 0:\n agent.save(agent_ckpt_name)\n logging.info('Agent saved at %s.', agent_ckpt_name)\n\n agent.save(agent_ckpt_name)\n time_cost = time.time() - time_st_total\n logging.info('Training finished, time cost %.4gs.', time_cost)\n return np.array(eval_results)\n","repo_name":"Farama-Foundation/D4RL-Evaluations","sub_path":"brac/behavior_regularized_offline_rl/brac/train_eval_offline.py","file_name":"train_eval_offline.py","file_ext":"py","file_size_in_byte":7741,"program_lang":"python","lang":"en","doc_type":"code","stars":177,"dataset":"github-code","pt":"85"} +{"seq_id":"20130079220","text":"# ch = \"hello welcome\"\r\n# for j in ch :\r\n# print(j)\r\n# for i in range(1,122):\r\n# print(i,j)\r\n\r\n #for loop excersise\r\n# x = int (input(\"how many times have to tell this : \"))\r\n# for i in range(x):\r\n# print(f\"time {i} :clean your room!!\")\r\n\r\n# for i in range(1,21):\r\n# if (i/2==6.5):\r\n# print(f\"{i}: is unlucky!!\")\r\n# elif(i/2==2):\r\n# print(f\"{i}: is unlucky!!\")\r\n# elif (i%2!=0):\r\n# print(f\"{i} is odd\")\r\n \r\n# elif(i%2 ==0):\r\n# print(f\"{i}: is Even \")\r\n \r\n\r\n#verson 2.O \r\n# for i in range(1,21):\r\n# if (i/2==6.5):\r\n# state = \"unlucky!!\"\r\n# elif(i/2==2):\r\n# state =\"unlucky!!\"\r\n# elif (i%2!=0):\r\n# state = \"odd\"\r\n# # print(f\"{i} is odd\")\r\n \r\n# elif(i%2 ==0):\r\n# # print(f\"{i}: is Even \")\r\n# state = \"Even\"\r\n# print(f\"{i} is {state}\")\r\n\r\n# # h wr u (\r\n# p r gu u \r\n\r\n# for i in range(1,4):\r\n# brother = input(\"brother : how are you >>>\")\r\n# sister = input(\"sister:\")\r\n# brother1 = input(\"brother : \")\r\n# sister1 = input(\"sister1: \")\r\n# if sister == brother and sister1 == brother1:\r\n# print(\"stop copying me !\")\r\n# elif sister!=brother:\r\n# print(input(\"tell some thing !>>\")) \r\n# else:\r\n# print(\"\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#while loop\r\n# i = 1\r\n# while (i<11):\r\n# print(i)\r\n# print(\"\\U0001f601\")\r\ni = 1\r\n# for i in range(1,2):\r\n# print(\"\\U0001f600\")\r\n# i+=1 \r\n# while i < 11 :\r\n# print(\" \")\r\n \r\n# print(\"\\U0001f600 \" * i)\r\n# i+=1\r\n \r\n\r\n#while loop ugraded version 2.O \r\n# for x in range(1,11):\r\n# count = 1\r\n# simle = \"\"\r\n# while count <= x : #1 ==1 \r\n# simle = \"\\U0001f600 \" * count\r\n# count+= 1\r\n# print(simle)\r\n\r\n\r\n# break \r\nwhile i < 11:\r\n x = input(\"type 'exit' to exit : >>>\")\r\n if x == \"exit\":\r\n break\r\n else:\r\n print(\"ggg\")\r\n\r\n\r\n","repo_name":"jeykarlokes/complete-reference-to-python3-programs","sub_path":"python/loops.py","file_name":"loops.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"14802389053","text":"import unittest\nimport sys\nimport os\n\nsys.path.append(os.path.realpath(os.path.dirname(__file__) + \"/..\"))\nfrom lib.database.db import Database\nfrom lib.database.user import User\n\n\nclass TestDatabase(unittest.TestCase):\n def test_create_user(self):\n database = Database()\n user = database.create_user(\"Test User\", 50)\n self.assertIsNotNone(user)\n self.assertEqual(user.name, \"Test User\")\n self.assertEqual(user.speed, 50)\n\n def test_create_duplicate_user(self):\n database = Database()\n user1 = database.create_user(\"Test User1\", 50)\n user2 = database.create_user(\"Test User1\", 60)\n self.assertEqual(user1.name, \"Test User1\")\n self.assertIsNone(user2)\n\n def test_get_user(self):\n database = Database()\n temp = database.create_user(\"Test User3\", 50)\n user = database.get_user(\"Test User3\")\n self.assertIsNotNone(user)\n self.assertEqual(user.name, \"Test User3\")\n self.assertEqual(user.speed, 50)\n\n def test_get_users(self):\n database = Database()\n users = database.get_users()\n self.assertGreater(len(users), 0)\n\n def test_user_history(self):\n database = Database()\n user = database.get_user(\"Test User\")\n history = user.history()\n self.assertGreater(len(history), 0)\n\n def test_user_update(self):\n database = Database()\n user = database.get_user(\"Test User\")\n self.assertIsNotNone(user)\n self.assertEqual(user.speed, 50)\n user.update(60)\n user = database.get_user(\"Test User\")\n self.assertEqual(user.speed, 55)\n","repo_name":"Moultree/keyboard-trainer","sub_path":"tests/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"35796273297","text":"from airflow import DAG\nfrom airflow.operators.bash import BashOperator\nfrom airflow.operators.python import PythonOperator\n# from airflow.operators.dummy import DummyOperator\n\nfrom airflow.utils.helpers import cross_downstream\n\n\nfrom datetime import datetime\n\n\ndef func(execution_date):\n print('python callable.')\n if execution_date.day == 6:\n raise ValueError('python callable produce error')\n\n\ndag = DAG(dag_id=\"poolexperiment\", start_date=datetime(\n 2022, 7, 1), schedule_interval='@daily', catchup=False, tags=['mark'])\n\nwith dag as d:\n\n extract_a = BashOperator(\n task_id=\"extract_a\",\n bash_command=\"echo '{{ti.try_number}}'\"\n )\n\n extract_b = BashOperator(\n task_id=\"extract_b\",\n bash_command=\"echo '{{ti.try_number}}' && echo 'new operator'\"\n )\n\n process_a = BashOperator(\n task_id='process_a',\n bash_command=\"echo 'process a' && sleep 20\",\n pool=\"Experiment_pool\"\n\n )\n\n process_b = BashOperator(\n task_id='process_b',\n bash_command=\"echo 'process a' && sleep 20\",\n pool=\"Experiment_pool\"\n )\n\n process_c = BashOperator(\n task_id='process_c',\n bash_command=\"echo 'process a' && sleep 20\",\n pool=\"Experiment_pool\"\n )\n\n store = PythonOperator(\n task_id=\"store\",\n python_callable=func,\n depends_on_past=True\n )\n\n # dummy = DummyOperator(\n # task_id=\"dummy\"\n # )\n\n cross_downstream([extract_a, extract_b], [process_a, process_b, process_c])\n [process_a, process_b, process_c] >> store\n # extract_a >> process_a\n","repo_name":"anil-chhetri/airflow-practise","sub_path":"dags/experiment_pool.py","file_name":"experiment_pool.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26972946871","text":"import pandas as pd\nimport os\nfrom tqdm import tqdm\n\ndef load_data_train(path_location, path_folder):\n \"\"\"\n Load data train input (In example: data of 11 station)\n Args:\n path_location: dir path location file --> read satation order\n path_folder: dir path of folder contain data train input or data train output\n Return:\n file csv data combine train input or output\n \"\"\"\n df_total_train = pd.DataFrame()\n for i in tqdm(pd.read_csv(path_location)['station'].map(lambda x: str(x)+ '.csv').to_list()):\n try:\n df = pd.read_csv(os.path.join(path_folder, i))\n df.drop(['Unnamed: 0'], axis= 1, inplace = True)\n name_location_i = i.split('.')[0]\n dict_col_change = {\n 'PM2.5': 'PM2.5_' + name_location_i,\n 'humidity': 'humidity_'+ name_location_i,\n 'temperature': 'temperature_'+ name_location_i\n }\n df.rename(columns= dict_col_change, inplace= True)\n if len(df_total_train.columns) < 2:\n df_total_train['timestamp'] = df['timestamp']\n df_total_train = df_total_train.merge(df, on = 'timestamp')\n except:\n print(f'No found file: {i} !')\n df_total_train['timestamp'] = pd.to_datetime(df_total_train['timestamp'], dayfirst= True)\n df_total_train = df_total_train.set_index('timestamp')\n\n return df_total_train\n\ndef check_feature(df, p):\n \"\"\"\n Keep column of data df has missing data percent < p%\n Args:\n df: DataFrame\n p: percent\n Return:\n List columns have data minsing/ total < p%\n \"\"\"\n k = 0\n list_feature = []\n for i in df.columns:\n n_miss = df[[i]].isnull().sum()\n perc = n_miss / df.shape[0] * 100\n if perc.values[0]< p:\n # print('> %s, Missing: %d (%.1f%%)' % (i, n_miss, perc))\n k += 1\n list_feature.append(i)\n print(f'feature < {p}%: {k} / total: {len(df.columns)}')\n return list_feature\n\ndef normalize(data, train_split):\n # Normalize Min-Max data\n data_min = data[:train_split].min(axis=0)\n data_max = data[:train_split].max(axis=0)\n return (data - data_min) / (data_max - data_min) , data_min, data_max\n\ndef load_data_test(path_folder, col_name):\n \"\"\"\n Load data test to predict and submit\n Args:\n path_folder: dir path of data test\n col_name(list): list columns order by data train\n Return:\n dict data of each folder in path_folder test.\n \"\"\"\n dict_data_submit = {}\n for k in tqdm(os.listdir(path_folder)):\n PUBLIC_TEST_INPUT_PATH_FOLDER = os.path.join(path_folder, k)\n df_concat = pd.DataFrame()\n for i in os.listdir(PUBLIC_TEST_INPUT_PATH_FOLDER):\n df = pd.read_csv(os.path.join(PUBLIC_TEST_INPUT_PATH_FOLDER, i))\n df.drop(['Unnamed: 0'], axis= 1, inplace = True)\n name_location_i = i.split('.')[0]\n dict_col_change = {\n 'PM2.5': 'PM2.5_' + name_location_i,\n 'humidity': 'humidity_'+ name_location_i,\n 'temperature': 'temperature_'+ name_location_i\n }\n df.rename(columns= dict_col_change, inplace= True)\n if len(df_concat.columns) < 2:\n df_concat['timestamp'] = df['timestamp']\n df_concat = df_concat.merge(df, on = 'timestamp')\n value_k = df_concat[col_name].values\n dict_data_submit[k] = value_k\n return dict_data_submit\n\n\ndef load_data_public_test(path_folder, col_name):\n # Return a DataFrame public test\n df_total_public_test = pd.DataFrame()\n for k in tqdm(os.listdir(path_folder)):\n PUBLIC_TEST_INPUT_PATH_FOLDER = os.path.join(path_folder, k)\n df_concat = pd.DataFrame()\n for i in os.listdir(PUBLIC_TEST_INPUT_PATH_FOLDER):\n df = pd.read_csv(os.path.join(PUBLIC_TEST_INPUT_PATH_FOLDER, i))\n df.drop(['Unnamed: 0'], axis= 1, inplace = True)\n name_location_i = i.split('.')[0]\n dict_col_change = {\n 'PM2.5': 'PM2.5_' + name_location_i,\n 'humidity': 'humidity_'+ name_location_i,\n 'temperature': 'temperature_'+ name_location_i\n }\n df.rename(columns= dict_col_change, inplace= True)\n if len(df_concat.columns) < 2:\n df_concat['timestamp'] = df['timestamp']\n df_concat = df_concat.merge(df, on = 'timestamp')\n # df_concat = df_concat[['timestamp'] + COL_NAME]\n df_concat = df_concat[['timestamp'] + col_name]\n # df_concat['folder public test'] = k\n if len(df_total_public_test.columns) < 2:\n df_total_public_test = pd.DataFrame(columns= df_concat.columns)\n df_total_public_test = pd.concat((df_total_public_test, df_concat))\n\n df_total_public_test['timestamp'] = pd.to_datetime(df_total_public_test['timestamp'], dayfirst = True)\n df_total_public_test = df_total_public_test.drop_duplicates(subset=['timestamp'])\n df_total_public_test = df_total_public_test.set_index('timestamp')\n\n return df_total_public_test","repo_name":"thien1892/AI4VN_2022-Air_Quality_Forecasting_Challenge_Public","sub_path":"data/load_data_train.py","file_name":"load_data_train.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42918492152","text":"'''\nN x N 배열에서 한 칸을 선택했을 때 그 칸을 포함하는 가로 행과 세로 열에 포함된 값들의 총합이 최대가 되는 경우를 찾고 싶다.\n한지점에서 본인을 포함한 십자의 합 구하는 문제\n'''\n\ntest_case = int(input())\n\nfor tc in range(1, test_case+1):\n N = int(input())\n board = [list(map(int, input().split())) for _ in range(N)]\n di = [-1,1,0,0] #상하좌우\n dj = [0,0,-1,1]\n max_sum = 0\n for i in range(N):\n for j in range(N):\n sum = board[i][j]\n #십자 행과 열 덧셈\n for k in range(1,N):\n for l in range(4):\n ni = i + di[l]*k\n nj = j + dj[l]*k\n if 0<= ni < N and 0<= nj < N:\n sum += board[ni][nj]\n if sum > max_sum:\n max_sum = sum\n \n print(f'#{tc} {max_sum}')","repo_name":"song7351/TIL-algorithm","sub_path":"추가문제/11094_가로세로의최대합.py","file_name":"11094_가로세로의최대합.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"8941801548","text":"import torch\nimport torch.nn as nn\n\n\nclass LinearEval(nn.Module):\n def __init__(self, opt):\n super().__init__()\n input_dim = opt[\"input_dim\"]\n output_dim = opt[\"output_dim\"]\n self.fc = nn.Linear(input_dim, output_dim)\n self.apply(self._init_weights)\n\n def _init_weights(self, module):\n if isinstance(module, nn.Linear):\n module.weight.data.zero_()\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n def forward(self, x):\n return self.fc(x)\n","repo_name":"cyysc1998/MABe2022-Ants","sub_path":"mabe/archs/linear_eval_arch.py","file_name":"linear_eval_arch.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"25800787607","text":"\nimport os,sys\n# import time, datetime\nsys.path.insert(0, '/home/madhu/work/codes')\nfrom main import check_endWith, check_create_dir, check_env, read_file, write_file, count_lines, save_file, load_file\n\n# check_env('torch')\n\n# import TS_finetune_pred_MP\nfrom datetime import datetime\nimport glob\n\nimport warnings\n# warnings.filterwarnings(\"ignore\", category=FutureWarning)\nwarnings.filterwarnings(\"ignore\")\n\nfrom sklearn.metrics import roc_auc_score, roc_curve\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport pickle\n\nfrom natsort import natsorted\n\n'''\nThis script draws the ROC curves for the other existing tools. \nIt reads the output from those tools. Tools are: \n\n1. Epinano\n2. m6Anet\n3. Tombo \n4. DRUMMER\n5. xPore\n\n'''\n\ndef read_outputs(csv_files):\n if len(csv_files) != 1:\n print('******** There are multiple csv files. INVESTIGATE ... *********')\n else:\n csv_file = csv_files[0]\n \n # print('The final output file is: ', csv_file)\n df = pd.read_csv(csv_file)\n return df\n\ndef read_Tombo_outs(data_type, out_file, y_true, y_score):\n for a_line in read_file(out_file).split('\\n'):\n if len(a_line) >=1:\n if a_line[0].isdigit():\n # print(a_line.split(' ')[-1])\n if data_type == 'wt': \n y_true.append(0)\n elif data_type == 'ko': \n y_true.append(1)\n y_score.append( float(a_line.split(' ')[-1]) )\n return y_true, y_score\n\n\n# def draw_ROC(y_true, y_score, save_ROC_results, saveFig_title):\n# values is a list containing: [y_true, y_score, tool]\ndef calc_AUC__draw_ROC(values, saveFig_title): \n\n fig, ax = plt.subplots(figsize=(20, 20))\n\n list_c = ['r', 'b', 'm', 'y', 'g', 'c']\n list_m = ['*', 'x', 'o', '.', '*', 'x']\n list_s = ['-', '--', '-.', ':', ' ', '']\n # list_s = ['-', '--', '-.', ':', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted']\n\n if len(values) != len(list_c) or len(values) != len(list_c):\n print('***** SOMETHING is WRONG, INVESTIGATE ... ******')\n sys.exit(0)\n \n # for a_value in values:\n for i in range(len(values)): \n [y_true, y_score, tool] = values[i]\n fpr, tpr, thresholds = roc_curve(y_true, y_score)\n AUC_score = roc_auc_score(y_true, y_score)\n print('\\n\\nThe AUC is :', round(AUC_score, 4), ' for the TOOL: ', tool)\n plt.plot(fpr, tpr, list_c[i], marker=list_m[i], linestyle=list_s[i], linewidth=2, label='{}: (AUC = {:.4f})'.format(tool, AUC_score))\n\n plt.legend(loc='lower right', fontsize=28)\n plt.plot([0, 1], [0, 1], color='navy', linestyle='--')\n plt.xlim([-0.02, 1.02])\n plt.ylim([-0.02, 1.02])\n plt.xlabel('Specificity', fontsize=25)\n plt.ylabel('Sensitivity', fontsize=25)\n # plt.xlabel('False Positive Rate', fontsize=20)\n # plt.ylabel('True Positive Rate', fontsize=20)\n \n n_split = 11\n xTick_list = []\n for n in np.linspace(0, 1, n_split):\n xTick_list.append(str(int(n*100))+'%')\n # reversing the list\n new_xTick_list = []\n for i in xTick_list:\n new_xTick_list.insert(0, i)\n plt.xticks(np.linspace(0, 1, n_split), new_xTick_list, fontsize=22)\n yTick_list = []\n for n in np.linspace(0, 1, n_split):\n yTick_list.append(str(int(n*100))+'%')\n plt.yticks(np.linspace(0, 1, n_split), yTick_list, fontsize=22)\n plt.grid(color='y', linewidth=0.5)\n \n # plt.title('Mean ROC curve for TB Index Score', fontsize=35)\n plt.show()\n plt.savefig(saveFig_title)\n print('The ROC figure has been saved at: ', saveFig_title)\n plt.close('all')\n \n # save_file(save_ROC_results, (fpr, tpr, thresholds, AUC_score))\n\n # return AUC_score\n\n\n\nif __name__=='__main__' and '__file__' in globals():\n\n startTime = datetime.now()\n current_time = startTime.strftime(\"%Y/%m/%d at %H:%M:%S\")\n print('\\n\\nThe script starting at: ' + str(current_time), ' \\n\\n' )\n\n ## This data token is consistent for one data type and all existing tools \n base_dir = '/home/madhu/work/comp_tools/paper_6/download_tools'\n data_token = 'IVT_m6A'\n\n\n\n\n\n\n\n # ### Epinano\n # ## The output file to be read \n # epinano_dir = base_dir+'/EpiNano/RESULTS'\n # # out_files = glob.glob( epinano_dir+'/'+data_token+'/pred_DELTA*.csv' )\n # ko_out_files = glob.glob( epinano_dir+'/'+data_token+'/KO_'+data_token+'.q3.mis3.del3.MODEL.rrach.q3.mis3.del3.linear.dump.csv' )\n # wt_out_files = glob.glob( epinano_dir+'/'+data_token+'/WT_'+data_token+'.q3.mis3.del3.MODEL.rrach.q3.mis3.del3.linear.dump.csv' )\n \n # # epinano_df = read_outputs(out_files)\n # ko_epinano_df = read_outputs(ko_out_files)\n # wt_epinano_df = read_outputs(wt_out_files)\n\n # ## 'ProbM': modified probability; 'ProbU': unmodified probability\n # # print(epinano_df)\n # # print(epinano_df['ProbM'].values)\n # # print(epinano_df['ProbU'].values)\n\n # print(ko_epinano_df.head())\n \n # y_true_epinano = []\n # y_score_epinano = []\n\n # y_true_epinano.extend( len(ko_epinano_df)*[1] )\n # y_score_epinano.extend( ko_epinano_df['ProbM'].values )\n\n # y_true_epinano.extend( len(wt_epinano_df)*[0] )\n # y_score_epinano.extend( wt_epinano_df['ProbM'].values )\n\n \n # print('y_true_epinano: ', len(y_true_epinano))\n # print('y_score_epinano: ', len(y_score_epinano))\n\n\n\n\n\n # ### m6Anet\n # m6Anet_dir = base_dir+'/m6anet/RESULTS'\n\n # wt_out_files = glob.glob( m6Anet_dir+'/'+data_token+'/results/WT/data.site_proba.csv' )\n # ko_out_files = glob.glob( m6Anet_dir+'/'+data_token+'/results/KO/data.site_proba.csv' )\n\n # # out_files = glob.glob( m6Anet_dir+'/'+data_token+'/results/WT/data.indiv_proba.csv' )\n\n # # m6Anet_df = read_outputs(out_files)\n # # print(m6Anet_df)\n # # print(m6Anet_df['probability_modified'].values)\n # ko_m6Anet_df = read_outputs(ko_out_files)\n # wt_m6Anet_df = read_outputs(wt_out_files)\n\n # y_true_m6Anet = []\n # y_score_m6Anet = []\n\n # y_true_m6Anet.extend( len(ko_m6Anet_df)*[1] )\n # y_score_m6Anet.extend( ko_m6Anet_df['probability_modified'].values )\n\n # y_true_m6Anet.extend( len(wt_m6Anet_df)*[0] )\n # y_score_m6Anet.extend( wt_m6Anet_df['probability_modified'].values )\n\n\n\n\n\n\n\n\n\n\n \n # ### Tombo\n\n # tombo_dir = base_dir+'/Tombo_Output/RESULTS'\n # # wt_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.fraction_modified_reads.m6A.minus.wig' )\n # # ko_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.fraction_modified_reads.m6A.plus.wig' )\n\n # ## wt_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.fraction_modified_reads.m6A.plus.wig' )\n # ## ko_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.fraction_modified_reads.m6A.minus.wig' )\n\n # wt_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.fraction_modified_reads.m6A.plus.wig' )\n # ko_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.fraction_modified_reads.m6A.minus.wig' )\n\n # ## wt_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.dampened_fraction_modified_reads.m6A.minus.wig' )\n # ## ko_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.dampened_fraction_modified_reads.m6A.plus.wig' )\n\n # # wt_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.dampened_fraction_modified_reads.m6A.plus.wig' )\n # # ko_out_files = glob.glob( tombo_dir+'/'+data_token+'/IVT_m6Afinal_text__.dampened_fraction_modified_reads.m6A.minus.wig' )\n \n\n # y_true_Tombo = []\n # y_score_Tombo = []\n # y_true_Tombo, y_score_Tombo = read_Tombo_outs('wt', wt_out_files[0], y_true_Tombo, y_score_Tombo)\n # y_true_Tombo, y_score_Tombo = read_Tombo_outs('ko', ko_out_files[0], y_true_Tombo, y_score_Tombo)\n\n # # print('y_true: ', len(y_true))\n # # print('y_score: ', len(y_score))\n\n\n\n\n\n\n\n\n ## DRUMMER\n \n \n\n drummer_dir = base_dir+'/DRUMMER/RESULTS'\n y_true_DRUMMER = []\n y_score_DRUMMER = []\n\n data_token_tmp = 'IVT_m6A_0'\n ## I need to sort this out later .... \n # out_files = glob.glob( drummer_dir+'/'+data_token+'/'+ data_token+'__isoform/*/summary.txt' ) \n # out_files = ['/home/madhu/work/comp_tools/paper_6/download_tools/DRUMMER/RESULTS/IVT_m6A_0/IVT_m6A_0__isoform/IVT_normalA_fast5_1-IVT_m6A_fast5_1/summary.txt']\n\n out_files = ['/home/madhu/work/comp_tools/paper_6/download_tools/DRUMMER/RESULTS/IVT_m6A_0/IVT_m6A_0__isoform/IVT_normalA_fast5_0-IVT_normalA_fast5_1/complete_analysis/A1.complete.txt']\n\n ref_file='/home/madhu/work/ref_transcriptome/IVT_seq/IVT_seq.fa'\n ref_content = read_file(ref_file)\n\n # print('The file is: ', out_files)\n\n file_content = []\n for a_line in read_file(out_files[0]).split('\\n'):\n if not len(a_line.split('\\t')) == 1:\n file_content.append(a_line.split('\\t'))\n\n # print(np.array(file_content))\n drummer_df = pd.DataFrame(data=np.array(file_content))\n drummer_df.columns = drummer_df.iloc[0]\n drummer_df = drummer_df.reset_index(drop=True)\n drummer_df = drummer_df[1:]\n\n # print(drummer_df)\n # print(len(list(drummer_df.columns)))\n\n '''\n ['chr_ctrl', 'pos_ctrl', 'ref_ctrl', 'depth_ctrl', 'A_ctrl', 'C_ctrl', 'G_ctrl', 'T_ctrl', 'N_ctrl', 'ref_fraction_ctrl', 'chr_treat', 'ref_treat', 'depth_treat', 'A_treat', 'C_treat', 'G_treat', 'T_treat', 'N_treat', 'ref_fraction_treat', 'ratio_treat', 'frac_diff', 'ratio_ctrl', 'log2_(OR)', 'odds_ratio', 'p_values_OR', 'nearest_ac', 'nearest_ac_motif', 'five_bp_motif', 'eleven_bp_motif', 'G_test', 'p_val', 'padj', 'p_values_OR_adj', 'is_SNP', 'accumulation', 'depletion', 'homopolymer']\n '''\n\n # for a_c in list(drummer_df.columns):\n # print('\\n\\n*** ', a_c, ' : ')\n # print(drummer_df[a_c].values)\n\n ## The following columns are necessary for filtering ... \n\n # print(drummer_df['chr_ctrl'].values)\n # print(drummer_df['pos_ctrl'].values)\n # print(drummer_df['ref_ctrl'].values)\n\n selected_chr = drummer_df['chr_ctrl'].unique()\n # print(selected_chr)\n \n if len(selected_chr) > 1:\n print('*\\n\\nThere is something wrong with the selected chr. INVESTIGATE....')\n \n selected_chr_FINAL = selected_chr[0]\n\n selected_chr_seq = ref_content.split('>'+selected_chr[0])[1].split('>')[0]\n print('The number of ALL nucleotides in the reference sequence: ', len(selected_chr_seq), ' for chromosome:', selected_chr[0])\n\n\n # p_vals_list = []\n # for i in range(len(drummer_df)):\n # # print(drummer_df['pos_ctrl'].values[i])\n # # drummer_df['pos_ctrl'].values[i]\n # if selected_chr_seq[int(drummer_df['pos_ctrl'].values[i])] != drummer_df['ref_ctrl'].values[i]:\n # print('There is something wrong in finding the correct nucleotide.')\n # else:\n # # print('Fine.')\n # # if drummer_df['ref_ctrl'].values[i] == 'A' or drummer_df['ref_ctrl'].values[i] == 'T':\n # if drummer_df['ref_ctrl'].values[i] == 'A':\n # p_vals_list.append(np.float_(drummer_df['p_val'].values[i]))\n # # else:\n # # print(drummer_df['ref_ctrl'].values[i])\n\n # print('A appears ', len(p_vals_list), ' times in the DRUMMER output')\n\n \n col_names = ['chr', 'ref_seq_Nucl', 'position', 'DRUMMER_labels', 'DRUMMER_pVals']\n df_ROC = pd.DataFrame(columns=col_names)\n\n list_chr = []\n list_seq_pos = []\n list_pVals = []\n chr_list = ['A', 'C', 'G', 'T']\n pVal_dict_N_mthyl = {}\n for a_chr in chr_list:\n # if a_chr == 'C' or a_chr == 'G' or a_chr == 'T':\n if a_chr == 'C' or a_chr == 'G':\n continue\n\n pVal_list_N_mthyl = []\n\n seq_pos_list = natsorted([i for i, j in enumerate(selected_chr_seq) if j == a_chr])\n print('Chr: ', a_chr, ' appears ', len(seq_pos_list), ' times in the reference sequence.')\n\n drummer_df__chr = drummer_df[drummer_df['ref_ctrl'] == a_chr]\n print('Chr: ', a_chr, ' appears ', len(drummer_df__chr), ' times in the DRUMMER output.')\n # print( 'pos_list: ', seq_pos_list )\n # print( 'drummer_df__chr: ', pd.to_numeric(drummer_df__chr['pos_ctrl'].values) )\n pos_DIFF = [x for x in seq_pos_list if x not in pd.to_numeric(drummer_df__chr['pos_ctrl'].values) ]\n if len(pos_DIFF) > 0:\n print('The positions where ', a_chr, ' appears in the reference sequence, but not in the DRUMMER output: ', [(x-1) for x in pos_DIFF] )\n \n [pVal_list_N_mthyl.insert(x-1, 1) for x in pos_DIFF]\n \n # pVal_list_N_mthyl.extend( [1]*len(pos_DIFF) )\n \n for a_pos in seq_pos_list:\n for i in range(len(drummer_df__chr)):\n \n if a_pos == int(drummer_df__chr['pos_ctrl'].values[i]) :\n # pVal_list_N_mthyl.append( np.float_(drummer_df__chr['padj'].values[i]) )\n\n pVal_list_N_mthyl.append(-np.log( np.float_(drummer_df__chr['padj'].values[i]) if np.float_(drummer_df__chr['padj'].values[i])>10**(-300) else 10**(-300)) )\n\n # print( np.float_(drummer_df__chr['padj'].values[i]) )\n list_chr.extend( [a_chr]*len(pVal_list_N_mthyl) )\n list_seq_pos.extend( seq_pos_list )\n list_pVals.extend( pVal_list_N_mthyl )\n\n\n\n print(np.vstack(( np.array(['A1']*len(list_chr)), np.array(list_chr), np.array(list_seq_pos), np.array(['Neg']*len(list_chr)), np.array(list_pVals) )))\n\n y_true_DRUMMER.extend( len(pVal_list_N_mthyl)*[0] )\n y_score_DRUMMER.extend( pVal_list_N_mthyl )\n\n\n\n\n\n out_files = ['/home/madhu/work/comp_tools/paper_6/download_tools/DRUMMER/RESULTS/IVT_m6A_1/IVT_m6A_1__isoform/IVT_normalA_fast5_1-IVT_m6A_fast5/complete_analysis/A1.complete.txt']\n\n file_content = []\n for a_line in read_file(out_files[0]).split('\\n'):\n if not len(a_line.split('\\t')) == 1:\n file_content.append(a_line.split('\\t'))\n\n # print(np.array(file_content))\n drummer_df = pd.DataFrame(data=np.array(file_content))\n drummer_df.columns = drummer_df.iloc[0]\n drummer_df = drummer_df.reset_index(drop=True)\n drummer_df = drummer_df[1:]\n\n selected_chr = drummer_df['chr_ctrl'].unique()\n # print(selected_chr)\n \n if len(selected_chr) > 1:\n print('*\\n\\nThere is something wrong with the selected chr. INVESTIGATE....')\n\n selected_chr_seq = ref_content.split('>'+selected_chr[0])[1].split('>')[0]\n print('The number of ALL nucleotides: ', len(selected_chr_seq), ' for chromosome:', selected_chr[0])\n\n\n chr_list = ['A', 'C', 'G', 'T']\n pVal_dict_N_mthyl = {}\n for a_chr in chr_list:\n if a_chr == 'C' or a_chr == 'G' or a_chr == 'T':\n continue\n\n pVal_list_mthyl = []\n \n seq_pos_list = [i for i, j in enumerate(selected_chr_seq) if j == a_chr]\n print('Chr: ', a_chr, ' appears ', len(seq_pos_list), ' times in the reference sequence.')\n\n drummer_df__chr = drummer_df[drummer_df['ref_ctrl'] == a_chr]\n print('Chr: ', a_chr, ' appears ', len(drummer_df__chr), ' times in the DRUMMER output.')\n # print( 'pos_list: ', seq_pos_list )\n # print( 'drummer_df__chr: ', pd.to_numeric(drummer_df__chr['pos_ctrl'].values) )\n pos_DIFF = [x for x in seq_pos_list if x not in pd.to_numeric(drummer_df__chr['pos_ctrl'].values) ]\n if len(pos_DIFF) > 0:\n print('The difference of those two lists: ', pos_DIFF)\n pVal_list_mthyl.extend( [1]*len(pos_DIFF) )\n \n for a_pos in natsorted(seq_pos_list):\n for i in range(len(drummer_df__chr)):\n \n if a_pos == int(drummer_df__chr['pos_ctrl'].values[i]) :\n # pVal_list_mthyl.append( np.float_(drummer_df__chr['padj'].values[i]) )\n\n pVal_list_mthyl.append(-np.log( np.float_(drummer_df__chr['padj'].values[i]) if np.float_(drummer_df__chr['padj'].values[i])>10**(-300) else 10**(-300)) )\n\n # print( np.float_(drummer_df__chr['padj'].values[i]) )\n \n print('pVal_list_mthyl: ', len(pVal_list_mthyl) )\n # for p in pVal_list_mthyl:\n # if p > 0.05:\n # print(p)\n\n y_true_DRUMMER.extend( len(pVal_list_mthyl)*[1] )\n y_score_DRUMMER.extend( pVal_list_mthyl )\n\n # # y_true_DRUMMER.extend( len(drummer_df)*[0] )\n # # y_score_DRUMMER.extend( list( np.float_(drummer_df['frac_diff'].values)) )\n\n\n # # print(drummer_df['p_val'].values)\n # # print(y_true_DRUMMER)\n # # print( y_score_DRUMMER )\n # # AUC_score = roc_auc_score(y_true_DRUMMER, list(np.float_(y_score_DRUMMER)))\n # AUC_score = roc_auc_score(y_true_DRUMMER, y_score_DRUMMER)\n # print('\\n\\n**** AUC: ', AUC_score, '****\\n\\n')\n\n\n\n\n\n\n\n\n\n\n # ### xPore \n # xPore_dir = base_dir+'/xPore/RESULTS'\n # y_true_xPore = []\n # y_score_xPore = []\n\n\n # data_token_tmp = 'IVT_m6A_0'\n # wt_out_files = glob.glob( xPore_dir+'/'+data_token_tmp+'out_diffmod/diffmod.table' )\n # wt_xPore_df = read_outputs(wt_out_files)\n # # print(wt_xPore_df['z_score_ko_vs_wt'].values)\n # y_true_xPore.extend( len(wt_xPore_df)*[0] )\n # y_score_xPore.extend( wt_xPore_df['pval_ko_vs_wt'].values)\n # # y_score_xPore.extend( list(np.float_(wt_xPore_df['z_score_ko_vs_wt'].values) ))\n\n\n # data_token_tmp = 'IVT_m6A_1'\n # ko_out_files = glob.glob( xPore_dir+'/'+data_token_tmp+'out_diffmod/diffmod.table' )\n # ko_xPore_df = read_outputs(ko_out_files)\n # # print(ko_xPore_df['z_score_ko_vs_wt'].values)\n # y_true_xPore.extend( len(ko_xPore_df)*[1] )\n # y_score_xPore.extend( ko_xPore_df['pval_ko_vs_wt'].values)\n\n # print(y_true_xPore)\n # print( y_score_xPore )\n # # AUC_score = roc_auc_score(y_true_DRUMMER, list(np.float_(y_score_DRUMMER)))\n # AUC_score = roc_auc_score(y_true_xPore, y_score_xPore)\n # print('\\n\\n**** AUC: ', AUC_score, '****\\n\\n')\n\n\n\n\n\n\n\n\n\n\n\n\n # ### OUR DNN TOOL\n\n # y_true_ours = []\n # y_score_ours = []\n\n # ## This is using the log file ..................................\n # log_file_name = '/home/madhu/Logs/predict__train_p3_ALL_A_BilstmMean.layers3.hs512.F.lr1000.b256.p1000.GPU.ep1.190363.pt__A.log'\n # # log_file_name = '/home/madhu/Logs/predict__train_p3_ALL_A_BilstmMean.layers3.hs512.F.lr1000.b256.p1000.GPU.ep1.270011.pt__A.log'\n # # log_file_name = '/home/madhu/Logs/predict__train_p3_BOTH_pred_p6_m6A_A_BilstmMean.layers3.hs1024.F.lr1500.b512.p1000.GPU.ep1.160151.pt__A_NEW.log'\n # REF_GENOME = '/mnt/labshare/share/reference_genome/EpiNano_Reference_sequences/cc.fasta'\n\n\n # # log_file_name = '/home/madhu/Logs/predict__pred_p6_train_p5_m6A_ALL_A_BilstmMean.layers3.hs512.F.lr1000.b256.p1000.GPU.ep1.330287.pt__A_NEW.log'\n # # REF_GENOME = '/home/madhu/work/ref_transcriptome/mouse/mrna.fa'\n \n # log_file_content = read_file(log_file_name)\n # ref_gene_content = read_file(REF_GENOME)\n\n # gene_list = []\n # for a_part in tqdm(ref_gene_content.split('\\n')):\n # if a_part.startswith('>'):\n # gene_list.append( a_part.split('>')[1] )\n # for a_part in tqdm(log_file_content.split('\\n')):\n # for a_gene in gene_list:\n # if a_part.startswith('Pred: '+a_gene):\n # info_part = a_part.split(' ')\n # if len(info_part) == 6:\n # conf_mat = info_part[2:len(info_part)]\n \n # if (int(conf_mat[0])+int(conf_mat[1])) != 0 and (int(conf_mat[2])+int(conf_mat[3])) != 0:\n # y_true_ours.append(0)\n # y_score_ours.append(int(conf_mat[1])/(int(conf_mat[0])+int(conf_mat[1])))\n # y_true_ours.append(1)\n # y_score_ours.append(int(conf_mat[3])/(int(conf_mat[2])+int(conf_mat[3])))\n\n # AUC_score = roc_auc_score(y_true_ours, y_score_ours)\n # print('\\n\\n**** AUC: ', AUC_score, '****\\n\\n')\n\n\n\n # ## This is using the saved pickle file .................................. (for real data: mouse)\n # y_score_ours_KO = []\n # y_score_ours_WT = []\n # pred_results = load_file('/home/madhu/work/class_outputs/p5_decoding_epitranscriptional_native_RNA_seq/model_PRED_output__pred_p6_train_p5_m6A_ALL_A_BilstmMean.layers3.hs512.F.lr1000.b256.p1000.GPU.ep1.330287.pt__A/pred_results.pkl')\n\n # for mapc in pred_results:\n # # print(\"Total sites for <{}>: +{} -{}\\n\".format( mapc, (len(pred_results[mapc]['+']) if '+' in pred_results[mapc] else 0), (len(pred_results[mapc]['-']) if '-' in pred_results[mapc] else 0) ) );\n # for mapstn in pred_results[mapc]:\n # for ref_pos in pred_results[mapc][mapstn]:\n \n # t_pred = pred_results[mapc][mapstn][ ref_pos ]\n # # if ref_pos == 2161:\n # # print('t_pred: ', t_pred)\n \n # # print(\"Pred: {}:{}:{} {} {} {} {}\".format( mapc, mapstn, ref_pos, t_pred[0][0], t_pred[0][1], t_pred[1][0], t_pred[1][1] ) )\n # conf_mat = [t_pred[0][0], t_pred[0][1], t_pred[1][0], t_pred[1][1]]\n # if (int(conf_mat[0])+int(conf_mat[1])) != 0 and (int(conf_mat[2])+int(conf_mat[3])) != 0:\n # # y_true_ours.append(0)\n # y_score_ours_KO.append(int(conf_mat[1])/(int(conf_mat[0])+int(conf_mat[1])))\n # # y_true_ours.append(1)\n # y_score_ours_WT.append(int(conf_mat[3])/(int(conf_mat[2])+int(conf_mat[3])))\n\n # # print('The length of sites: ', len(y_score_ours))\n # N_BIN = 20\n # hist_KO,bins_KO=np.histogram(np.array(y_score_ours_KO),bins=np.linspace(0,1,N_BIN))\n # hist_WT,bins_WT=np.histogram(np.array(y_score_ours_WT),bins=np.linspace(0,1,N_BIN))\n # print('hist_KO: ', hist_KO)\n # print('hist_WT: ', hist_WT)\n # # print('sum(hist): ', sum(hist))\n # print('bins_KO: ', bins_KO)\n # print('bins_WT: ', bins_WT)\n\n # fig, ax = plt.subplots(figsize=(20, 20))\n # plt.clf()\n # # plt.hist(np.array(y_score_ours), bins=np.linspace(0,1,N_BIN), histtype='bar', label='y_score distribution')\n # plt.hist([ np.array(y_score_ours_KO) , np.array(y_score_ours_WT) ], bins=np.linspace(0,1,N_BIN), histtype='bar', label=['KO', 'WT'])\n # plt.legend(loc='best', fontsize=25)\n # plt.xticks([x for x in np.linspace(0,1,N_BIN)], [round(x, 2) for x in np.linspace(0,1,N_BIN)], fontsize=20)\n # plt.yticks(fontsize=20)\n # plt.grid(color='y', linestyle='-', linewidth=1)\n # plt.xlabel('Probablity Thresholds', fontsize=22)\n # plt.ylabel('Number of sites', fontsize=22)\n # plt.show()\n \n # output_PNG_filename = '/home/madhu/work/class_outputs/p5_decoding_epitranscriptional_native_RNA_seq/model_PRED_output__pred_p6_train_p5_m6A_ALL_A_BilstmMean.layers3.hs512.F.lr1000.b256.p1000.GPU.ep1.330287.pt__A/yscore_dist.png'\n # plt.savefig(output_PNG_filename)\n # plt.close()\n # print('\\nThe figure has been successfully generated as: ', output_PNG_filename, '\\n')\n \n\n\n\n\n\n\n\n # saveFig_title = base_dir + '/ROC_'+data_token+'.png'\n # # values is a list containing: [y_true, y_score, tool]\n # values = [y_true_ours, y_score_ours, 'Our_DNN_tool'], [y_true_epinano, y_score_epinano, 'Epinano'], [y_true_m6Anet, y_score_m6Anet, 'm6Anet'], [y_true_Tombo, y_score_Tombo, 'Tombo'], [y_true_DRUMMER, y_score_DRUMMER, 'DRUMMER'], [y_true_xPore, y_score_xPore, 'xPore']\n # calc_AUC__draw_ROC(values, saveFig_title)\n\n\n \n executionTime = (datetime.now() - startTime)\n current_time = datetime.now().strftime(\"%Y/%m/%d at %H:%M:%S\")\n print('\\n\\nThe script completed at: ' + str(current_time))\n print('Execution time: ' + str(executionTime), ' \\n\\n')\n\n","repo_name":"Madhurananda/my_current_work_draft","sub_path":"codes/ML_codes/madhu_codes/OLD_codes/plot_ROC_otherTools_OLD4.py","file_name":"plot_ROC_otherTools_OLD4.py","file_ext":"py","file_size_in_byte":23696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7290867925","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom sound import Sound\nfrom random import randint\n\nclass Test(object):\n\tdef __init__(self):\n\t\tself.newWorldSound = Sound('NWS',1)\n\n\tdef addRando(self, maximum=5):\n\t\tfor i in range(0,maximum):\n\t\t\tself.randomMesswert = randint(0, 20)\n\t\t\tself.newWorldSound.addMesswert(self.randomMesswert)\n\n\tdef showAll(self):\n\t\tprint('Current results: '+str(self.newWorldSound.getResult()))\n\t\tprint('Lastäöü results: '+str(self.newWorldSound.getLastResult()))\n\nnewTest = Test()\nnewTest.addRando(10)\nnewTest.showAll()\n","repo_name":"gruener-campus-malchow/raumsteuerung","sub_path":"files/testSound.py","file_name":"testSound.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"3701261988","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom einops import rearrange, repeat\n\nfrom group_unet.groups.base import InterpolativeLiftingKernel, GroupKernelBase\n\n\nclass Residual(nn.Module):\n def __init__(self, fn):\n super().__init__()\n self.fn = fn\n\n def forward(self, x):\n return self.fn(x) + x\n\n\nclass LiftingConvolution(nn.Module):\n def __init__(self, group, in_channels, out_channels, kernel_size):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel = InterpolativeLiftingKernel(\n group=group,\n kernel_size=kernel_size,\n in_channels=in_channels,\n out_channels=out_channels,\n )\n\n def forward(self, x):\n conv_kernels = self.kernel.sample()\n conv_kernels = rearrange(conv_kernels, \"o g i h w -> (o g) i h w\")\n x = F.conv2d(\n input=x,\n weight=conv_kernels,\n padding=\"same\",\n )\n\n x = rearrange(x, \"b (c g) h w -> b c g h w\", c=self.out_channels)\n return x\n\n\nclass InterpolativeGroupKernel(GroupKernelBase):\n def __init__(self, group, kernel_size, in_channels, out_channels):\n super().__init__(group, kernel_size, in_channels, out_channels)\n\n self.weight = nn.Parameter(torch.zeros((\n self.out_channels,\n self.in_channels,\n self.group.elements().numel(),\n self.kernel_size,\n self.kernel_size,\n ), device=self.group.identity.device))\n\n nn.init.kaiming_uniform_(self.weight.data, a=math.sqrt(5))\n\n def sample(self):\n group_size = self.group.elements().numel()\n weight = self.weight.view(\n 1,\n self.out_channels * self.in_channels,\n group_size,\n self.kernel_size,\n self.kernel_size,\n )\n\n weight = repeat(\n self.weight,\n \"o i g h w -> g2 (o i) g h w\",\n g2=group_size,\n )\n transformed_weight = F.grid_sample(\n weight,\n self.transformed_grid_R2xH,\n mode=\"bilinear\",\n padding_mode=\"zeros\",\n align_corners=True,\n )\n\n transformed_weight = repeat(\n transformed_weight,\n \"g2 (o i) g h w -> o g2 i g h w\",\n g2=group_size,\n o=self.out_channels,\n i=self.in_channels,\n )\n\n return transformed_weight\n\n\nclass GroupConvolution(nn.Module):\n def __init__(self, group, in_channels, out_channels, kernel_size):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel = InterpolativeGroupKernel(\n group=group,\n kernel_size=kernel_size,\n in_channels=in_channels,\n out_channels=out_channels,\n )\n\n def forward(self, x):\n x = rearrange(x, \"b c g h w -> b (c g) h w\")\n conv_kernels = self.kernel.sample()\n conv_kernels = rearrange(\n conv_kernels, \"o g i g2 h w -> (o g) (i g2) h w\")\n x = F.conv2d(\n input=x,\n weight=conv_kernels,\n padding=\"same\",\n )\n x = rearrange(x, \"b (c g) h w -> b c g h w\", c=self.out_channels)\n return x\n","repo_name":"dogeplusplus/group-unet","sub_path":"group_unet/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"13197290090","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport skimage\nfrom skimage.transform import warp, SimilarityTransform\nfrom skimage.feature import register_translation\nfrom skimage.feature.register_translation import _upsampled_dft\n\nref_image_fn = 'RgsASPc_A.jpg'\ndef_image_fn = 'RgsASPc_C.jpg'\noutput_image_fn = 'alianed.png'\npixel_precision = 100\n\nref_image = skimage.io.imread(ref_image_fn)\ndef_image = skimage.io.imread(def_image_fn)\n\nref_image_gray = skimage.color.rgb2gray(ref_image)\ndef_image_gray = skimage.color.rgb2gray(def_image)\n\nimage_product = np.fft.fft2(ref_image_gray) * np.fft.fft2(def_image_gray).conj()\n\n# subpixel precision\nshift, error, diffphase = register_translation(ref_image_gray, def_image_gray, pixel_precision)\n\ntform1 = SimilarityTransform(translation=(-shift[1], -shift[0]))\nalianed = warp(def_image, tform1, mode='symmetric')\n\nfig = plt.figure(figsize=(20, 10))\nax1 = plt.subplot(1, 4, 1)\nax2 = plt.subplot(1, 4, 2)\nax3 = plt.subplot(1, 4, 3)\nax4 = plt.subplot(1, 4, 4)\n\nax1.imshow(ref_image)\nax1.set_axis_off()\nax1.set_title('Reference image')\n\nax2.imshow(def_image)\nax2.set_axis_off()\nax2.set_title('Defect image')\n\nax3.imshow(alianed)\nax3.set_axis_off()\nax3.set_title('Alianment')\n\ncc_image = _upsampled_dft(image_product, 150, 100, (shift*100)+75).conj()\nax4.imshow(cc_image.real)\nax4.set_axis_off()\nax4.set_title(\"Supersampled XC sub-area\")\n\nplt.show()\n\nskimage.io.imsave(output_image_fn, alianed)\n\nprint(\"Detected subpixel offset (y, x): {}\".format(shift))\n","repo_name":"g21589/MyNote","sub_path":"Kaggle2018/img_translation.py","file_name":"img_translation.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"74364905559","text":"import os\nfrom contextlib import contextmanager\n\nclass PySPEC:\n \"\"\"\n This class gives access to SPEC features.\n \"\"\"\n\n #: SPEC DDR size\n DDR_SIZE = 256 * 1024 * 1024\n #: SPEC DDR access alignment\n DDR_ALIGN = 4\n\n def __init__(self, pci_id):\n self.pci_id = pci_id\n self.debugfs = \"/sys/kernel/debug/0000:{:s}\".format(self.pci_id)\n self.debugfs_fpga = os.path.join(self.debugfs, \"spec-0000:{:s}\".format(self.pci_id))\n\n def program_fpga(self, bitstream):\n \"\"\"\n Program the FPGA with the given bitstream\n\n :var path: path to bitstream\n :raise OSError: on failure\n \"\"\"\n with open(\"/sys/module/firmware_class/parameters/path\", \"r\") as f:\n prev = f.read()\n with open(\"/sys/module/firmware_class/parameters/path\", \"w\") as f:\n f.write(os.path.dirname(bitstream))\n with open(os.path.join(self.debugfs, \"fpga_firmware\"), \"w\") as f:\n f.write(os.path.basename(bitstream))\n with open(\"/sys/module/firmware_class/parameters/path\", \"w\") as f:\n f.write(os.path.dirname(prev))\n\n @contextmanager\n def dma(self, dma_coherent_size=None):\n \"\"\"\n Create a DMA context from which users can do DMA\n transfers. Within this context the user can use\n PySPECDMA.read() and PySPECDMA.write(). Here an example.\n\n >>> from PySPEC import PySPEC\n >>> spec = PySPEC(\"06:00.0\")\n >>> with spec.dma() as dma:\n >>> cnt = dma.write(0, b\"\\x00\" * 16)\n >>> buffer = dma.read(0, 16)\n\n Which is equivalent to:\n\n >>> from PySPEC import PySPEC\n >>> spec = PySPEC(\"06:00.0\")\n >>> spec_dma = PySPEC.PySPECDMA(spec)\n >>> spec_dma.open()\n >>> cnt = spec_dma.write(0, b\"\\x00\" * 16)\n >>> buffer = spec_dma.read(0, 16)\n >>> spec_dma.close()\n \"\"\"\n spec_dma = self.PySPECDMA(self)\n spec_dma.request(dma_coherent_size)\n try:\n yield spec_dma\n finally:\n spec_dma.release()\n\n class PySPECDMA:\n \"\"\"\n This class wraps DMA features in a single object.\n\n The SPEC has\n only one DMA channel. On request() the user will get exclusive\n access. The user must release() the DMA channel as soon as\n possible to let other users or drivers to access it. For this reason,\n avoid to use this class directly. Instead, use the DMA context\n from the PySPEC class which is less error prone.\n\n >>> from PySPEC import PySPEC\n >>> spec = PySPEC(\"06:00.0\")\n >>> with spec.dma() as dma:\n >>> cnt = dma.write(0, b\"\\x00\" * 16)\n >>> buffer = dma.read(0, 16)\n >>> print(buffer)\n \"\"\"\n\n def __init__(self, spec):\n \"\"\"\n Create a new instance\n\n :var spec: a valid PySPEC instance\n \"\"\"\n self.spec = spec\n\n\n def request(self, dma_coherent_size=None):\n \"\"\"\n Open a DMA file descriptor\n\n :var dma_coherent_size: DMA coherent allocation size (in-kernel).\n :raise OSError: if the open(2) or the driver fails\n \"\"\"\n if dma_coherent_size is not None:\n with open(\"/sys/module/spec_fmc_carrier/parameters/user_dma_coherent_size\", \"w\") as f:\n f.write(str(dma_coherent_size))\n\n self.dma_file = open(os.path.join(self.spec.debugfs_fpga, \"dma\"),\n \"rb+\", buffering=0)\n def release(self):\n \"\"\"\n Close the DMA file descriptor\n\n :raise OSError: if the close(2) or the driver fails\n \"\"\"\n if hasattr(self, \"dma_file\"):\n self.dma_file.close()\n\n def read(self, offset, size, max_segment=0):\n \"\"\"\n Trigger a *device to memory* DMA transfer\n\n :var offset: offset within the DDR\n :var size: number of bytes to be transferred\n :var max_segment: maximum size of a single transfer in a\n scatterlist. Default is 0, it means to use\n the DMA engine's default.\n :return: the data transfered as bytes() array\n :raise OSError: if the read(2) or the driver fails\n \"\"\"\n with open(\"/sys/module/spec_fmc_carrier/parameters/user_dma_max_segment\", \"w\") as f:\n f.write(str(max_segment))\n self.__seek(offset)\n data = []\n while size - len(data) > 0:\n data += self.dma_file.read(size - len(data))\n return bytes(data)\n\n def write(self, offset, data, max_segment=0):\n \"\"\"\n Trigger a *memory to device* DMA transfer\n\n :var offset: offset within the DDR\n :var size: number of bytes to be transferred\n :var max_segment: maximum size of a single transfer in a\n scatterlist. Default is 0, it means to use\n the DMA engine's default.\n :return: the number of transfered bytes\n :raise OSError: if the write(2) or the driver fails\n \"\"\"\n with open(\"/sys/module/spec_fmc_carrier/parameters/user_dma_max_segment\", \"w\") as f:\n f.write(str(max_segment))\n self.__seek(offset)\n start = 0\n while len(data) - start > 0:\n start += self.dma_file.write(bytes(data[start:]))\n return start\n\n def __seek(self, offset):\n \"\"\"\n Change DDR offset\n\n :var offset: offset within the DDR\n :raise OSError: if lseek(2) fails or the driver\n \"\"\"\n self.dma_file.seek(offset)\n","repo_name":"vascoguita/spec","sub_path":"software/PySPEC/PySPEC/PySPEC.py","file_name":"PySPEC.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8710655401","text":"def rotate(l, n):\r\n return l[n:] + l[:n]\r\n\r\n\r\ndef turn(c, d):\r\n if c[0] == max(c):\r\n return c, d\r\n else:\r\n return rotate(c, c.index(max(c))), rotate(d, c.index(max(c)))\r\n\r\n\r\nn = int(input())\r\nc = []\r\nfor i in range(n):\r\n a, b = map(int, input().split())\r\n c = list(map(int, input().split()))\r\n f = c[b] # 보류\r\n d = [0 for j in range(len(c))]\r\n d[b] = 1\r\n print_cnt = 0\r\n q=True\r\n while q:\r\n if c[0] == f and d[0] == 1 and c[0] >= max(c):\r\n print_cnt += 1\r\n print(print_cnt)\r\n q=False\r\n\r\n elif c[0] == max(c):\r\n del c[0], d[0]\r\n print_cnt += 1\r\n\r\n else:\r\n c, d = turn(c, d)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"2022-rescue-macbook/rescue-macbook-py","sub_path":"code/20032656.py3","file_name":"20032656.py3","file_ext":"py3","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32229960144","text":"# kartikay26\n\nfrom math import *\nfrom collections import *\nfrom itertools import *\nfrom functools import *\nfrom random import *\ndef getl(t=int): return [t(x) for x in input().split()]\ndef get(t=int): return t(input())\nalphabet = [chr(x) for x in range(ord('a'), ord('z')+1)]\nalnum = lambda x: ord(x) - ord('a')\n\ndef main():\n\tfor i in range(int(input())):\n\t\tif test():\n\t\t\tprint(\"YES\")\n\t\telse:\n\t\t\tprint(\"NO\")\n\ndef isSubSequence(str1,str2):\n j = 0 # Index of str1 \n i = 0 # Index of str2 \n while j= c2[x] for x in c2.keys())\n\treturn False\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"krkartikay/CodeForces-solutions","sub_path":"codeforces/1194/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73383187797","text":"import ast\nfrom ckanapi import errors as CkanError\nfrom ckanapi import RemoteCKAN\nfrom datetime import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.db import IntegrityError\nfrom functools import wraps\nfrom idgo_admin.exceptions import CkanBaseError\nfrom idgo_admin import logger\nfrom idgo_admin.utils import Singleton\nimport inspect\nimport os\nimport timeout_decorator\nimport unicodedata\nfrom urllib.parse import urljoin\n\n\nCKAN_URL = settings.CKAN_URL\nCKAN_API_KEY = settings.CKAN_API_KEY\ntry:\n CKAN_TIMEOUT = settings.GEONET_TIMEOUT\nexcept AttributeError:\n CKAN_TIMEOUT = 36000\n\n\ndef timeout(fun):\n t = CKAN_TIMEOUT # in seconds\n\n @timeout_decorator.timeout(t, use_signals=False)\n def return_with_timeout(fun, args=tuple(), kwargs=dict()):\n return fun(*args, **kwargs)\n\n @wraps(fun)\n def wrapper(*args, **kwargs):\n return return_with_timeout(fun, args=args, kwargs=kwargs)\n\n return wrapper\n\n\nclass CkanReadError(CkanBaseError):\n message = \"L'url ne semble pas indiquer un site CKAN.\"\n\n\nclass CkanApiError(CkanBaseError):\n message = \"L'API CKAN n'est pas accessible.\"\n\n\nclass CkanTimeoutError(CkanBaseError):\n message = 'Le site CKAN met du temps à répondre, celui-ci est peut-être temporairement inaccessible.'\n\n\nclass CkanNotFoundError(CkanBaseError):\n message = 'La ressource CKAN ne semble pas exister.'\n\n\nclass CkanConflictError(CkanBaseError):\n message = 'La ressource CKAN existe déjà.'\n\n\nclass CkanSyncingError(CkanBaseError):\n message = \"Une erreur de synchronisation avec l'instance de CKAN est survenue.\"\n\n def __init__(self, *args, **kwargs):\n for item in self.args:\n try:\n m = ast.literal_eval(item)\n except Exception:\n continue\n if isinstance(m, dict):\n kwargs.update(**m)\n super().__init__(*args, **kwargs)\n\n def __str__(self):\n try:\n return '{} {}'.format(self.message, ' '.join(self.name))\n except AttributeError:\n return super().__str__()\n\n\nclass CkanExceptionsHandler(object):\n\n def __init__(self, ignore=None):\n self.ignore = ignore or []\n\n def __call__(self, f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n\n root_dir = os.path.dirname(os.path.abspath(__file__))\n info = inspect.getframeinfo(inspect.stack()[1][0])\n logger.debug(\n 'Run {} (called by file \"{}\", line {}, in {})'.format(\n f.__qualname__,\n info.filename.replace(root_dir, '.'),\n info.lineno,\n info.function))\n\n try:\n return f(*args, **kwargs)\n except Exception as e:\n logger.exception(e)\n if isinstance(e, timeout_decorator.TimeoutError):\n raise CkanTimeoutError\n if self.is_ignored(e):\n return f(*args, **kwargs)\n if e.__class__.__qualname__ == 'ValidationError':\n try:\n err = e.error_dict\n del err['__type']\n msg = ', '.join([\n '\"{0}\" {1}'.format(k, isinstance(v, list) and ', '.join(v) or v)\n for k, v in err.items()])\n except Exception as e:\n msg = e.__str__()\n raise ValidationError(msg)\n if e.__str__() in ('Indisponible', 'Not Found'):\n raise CkanNotFoundError\n raise CkanSyncingError(e.__str__())\n return wrapper\n\n def is_ignored(self, exception):\n return type(exception) in self.ignore\n\n\nclass CkanBaseHandler(object):\n\n def __init__(self, url, apikey=None):\n\n self.apikey = apikey\n self.remote = RemoteCKAN(url, apikey=self.apikey)\n try:\n res = self.call_action('site_read')\n except Exception:\n raise CkanReadError()\n # else:\n logger.info('Open CKAN connection with api key: {}'.format(apikey))\n if not res:\n self.close()\n raise CkanApiError()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n\n def close(self):\n self.remote.close()\n logger.info('Close CKAN connection')\n\n # @timeout\n def call_action(self, action, **kwargs):\n return self.remote.call_action(action, kwargs)\n\n @CkanExceptionsHandler()\n def get_all_categories(self, *args, **kwargs):\n kwargs.setdefault('order_by', 'name')\n return [\n category for category\n in self.call_action('group_list', **kwargs)]\n\n @CkanExceptionsHandler()\n def get_all_licenses(self, *args, **kwargs):\n try:\n action_result = self.call_action('license_list', **kwargs)\n except CkanError.CKANAPIError:\n action_result = self.call_action('licence_list', **kwargs)\n return [license for license in action_result]\n\n @CkanExceptionsHandler()\n def get_all_organisations(self, *args, **kwargs):\n return [\n organisation for organisation\n in self.call_action('organization_list', **kwargs)]\n\n @CkanExceptionsHandler(ignore=[CkanError.NotFound])\n def get_organisation(self, id, **kwargs):\n try:\n return self.call_action('organization_show', id=id, **kwargs)\n except CkanError.NotFound:\n return None\n\n @CkanExceptionsHandler(ignore=[CkanError.NotFound])\n def get_package(self, id, **kwargs):\n kwargs.setdefault('include_tracking', True)\n try:\n return self.call_action(\n 'package_show', id=id, **kwargs)\n except CkanError.NotFound:\n return False\n\n def is_package_exists(self, id):\n return self.get_package(id) and True or False\n\n def is_package_name_already_used(self, name):\n return self.get_package(name) and True or False\n\n @CkanExceptionsHandler()\n # @timeout\n def push_resource(self, package, **kwargs):\n kwargs['package_id'] = package['id']\n kwargs['created'] = datetime.now().isoformat()\n for resource in package['resources']:\n if resource['id'] == kwargs['id']:\n kwargs['last_modified'] = kwargs['created']\n del kwargs['created']\n if 'url' in kwargs and not kwargs['url']:\n del kwargs['url']\n resource.update(kwargs)\n del resource['tracking_summary']\n # Moche pour tester\n # if resource['datastore_active']:\n # self.remote.action.resource_update(**resource)\n # if 'upload' in resource:\n # del resource['upload']\n # Fin de 'Moche pour tester'\n datastore_active = resource.get('datastore_active')\n if datastore_active and type(datastore_active) == str:\n resource['datastore_active'] = ast.literal_eval(datastore_active)\n return self.remote.action.resource_update(**resource)\n return self.remote.action.resource_create(**kwargs)\n\n @CkanExceptionsHandler()\n def push_resource_view(self, **kwargs):\n kwargs['title'] = kwargs['title'] if 'title' in kwargs else 'Aperçu'\n kwargs['description'] = kwargs['description'] \\\n if 'description' in kwargs else 'Aperçu du jeu de données'\n\n views = self.call_action(\n 'resource_view_list', id=kwargs['resource_id'])\n for view in views:\n if view['view_type'] == kwargs['view_type']:\n return self.call_action(\n 'resource_view_update', id=view['id'], **kwargs)\n return self.call_action('resource_view_create', **kwargs)\n\n @CkanExceptionsHandler()\n def update_resource(self, id, **kwargs):\n resource = self.call_action('resource_show', id=id)\n resource.update(kwargs)\n return self.call_action('resource_update', **resource)\n\n def check_dataset_integrity(self, name):\n if self.is_package_name_already_used(name):\n raise CkanConflictError('Dataset already exists')\n\n @CkanExceptionsHandler()\n def publish_dataset(self, id=None, resources=None, **kwargs):\n if id and self.is_package_exists(id):\n package = self.call_action(\n 'package_update', **{**self.get_package(id), **kwargs})\n else:\n package = self.call_action('package_create', **kwargs)\n return package\n\n @CkanExceptionsHandler()\n def publish_resource(self, package, **kwargs):\n resource_view_type = kwargs.pop('view_type')\n resource = self.push_resource(package, **kwargs)\n\n view = None\n if resource_view_type:\n view = self.push_resource_view(\n resource_id=resource['id'], view_type=resource_view_type)\n\n return resource, view\n\n @CkanExceptionsHandler(ignore=[CkanError.NotFound])\n def delete_resource(self, id):\n try:\n return self.call_action('resource_delete', id=id, force=True)\n except CkanError.NotFound:\n return None\n\n @CkanExceptionsHandler(ignore=[CkanError.NotFound])\n def delete_dataset(self, id):\n try:\n return self.call_action('package_delete', id=id)\n except CkanError.NotFound:\n return None\n\n\nclass CkanUserHandler(CkanBaseHandler):\n\n def __init__(self, apikey):\n super().__init__(CKAN_URL, apikey=apikey)\n\n\nclass CkanManagerHandler(CkanBaseHandler, metaclass=Singleton):\n\n def __init__(self):\n super().__init__(CKAN_URL, apikey=CKAN_API_KEY)\n\n def get_all_users(self):\n return [(user['name'], user['display_name'])\n for user in self.call_action('user_list')\n if user['state'] == 'active']\n\n @CkanExceptionsHandler(ignore=[CkanError.NotFound])\n def get_user(self, username):\n try:\n return self.call_action('user_show', id=username)\n except CkanError.NotFound:\n return None\n\n def is_user_exists(self, username):\n return self.get_user(username) and True or False\n\n @CkanExceptionsHandler()\n def add_user(self, user, password, state='deleted'):\n\n # CKAN retourne une erreur 500\n fullname = unicodedata.normalize(\n 'NFKD', user.get_full_name()).encode(\n 'ascii', 'ignore').decode('ascii')\n\n params = {'email': user.email,\n 'fullname': fullname,\n 'name': user.username,\n 'password': password,\n 'activity_streams_email_notifications': True,\n 'state': state}\n user = self.call_action('user_create', **params)\n\n @CkanExceptionsHandler()\n def del_user(self, username):\n # self.del_user_from_groups(username)\n self.del_user_from_organisations(username)\n self.call_action('user_delete', id=username)\n\n @CkanExceptionsHandler()\n def update_user(self, user):\n if not self.is_user_exists:\n raise IntegrityError(\n 'User {0} does not exists'.format(user.username))\n\n ckan_user = self.get_user(user.username)\n ckan_user.update({'email': user.email,\n 'fullname': user.get_full_name()})\n self.call_action('user_update', **ckan_user)\n\n @CkanExceptionsHandler()\n def activate_user(self, username):\n ckan_user = self.get_user(username)\n ckan_user.update({'state': 'active'})\n self.call_action('user_update', **ckan_user)\n\n def is_organisation_exists(self, id):\n return self.get_organisation(id) and True or False\n\n @CkanExceptionsHandler(ignore=[ValueError])\n def add_organisation(self, organisation):\n params = {\n 'id': str(organisation.ckan_id),\n 'name': organisation.slug,\n 'title': organisation.legal_name,\n 'description': organisation.description,\n 'extras': [\n {'key': 'email', 'value': organisation.email or ''},\n {'key': 'phone', 'value': organisation.phone or ''},\n {'key': 'website', 'value': organisation.website or ''},\n {'key': 'address', 'value': organisation.address or ''},\n {'key': 'postcode', 'value': organisation.postcode or ''},\n {'key': 'city', 'value': organisation.city or ''}],\n 'state': 'active'}\n try:\n params['image_url'] = \\\n urljoin(settings.DOMAIN_NAME, organisation.logo.url)\n except ValueError:\n pass\n self.call_action('organization_create', **params)\n\n @CkanExceptionsHandler()\n def update_organisation(self, organisation):\n ckan_organisation = self.get_organisation(\n str(organisation.ckan_id), include_datasets=True)\n\n ckan_organisation.update({\n 'title': organisation.legal_name,\n 'name': organisation.slug,\n 'description': organisation.description,\n 'extras': [\n {'key': 'email', 'value': organisation.email or ''},\n {'key': 'phone', 'value': organisation.phone or ''},\n {'key': 'website', 'value': organisation.website or ''},\n {'key': 'address', 'value': organisation.address or ''},\n {'key': 'postcode', 'value': organisation.postcode or ''},\n {'key': 'city', 'value': organisation.city or ''}]})\n\n try:\n if organisation.logo:\n ckan_organisation['image_url'] = \\\n urljoin(settings.DOMAIN_NAME, organisation.logo.url)\n except ValueError:\n pass\n\n self.call_action('organization_update', **ckan_organisation)\n\n for package in ckan_organisation['packages']:\n self.call_action('package_owner_org_update', id=package['id'],\n organization_id=ckan_organisation['id'])\n\n @CkanExceptionsHandler()\n def purge_organisation(self, id):\n return self.call_action('organization_purge', id=id)\n\n @CkanExceptionsHandler()\n def activate_organisation(self, id):\n self.call_action('organization_update', id=id, state='active')\n\n @CkanExceptionsHandler()\n def deactivate_organisation(self, id):\n # self.call_action('organization_delete', id=id)\n pass\n\n def deactivate_ckan_organisation_if_empty(self, id):\n organisation = self.get_organisation(id)\n if organisation and int(organisation.get('package_count')) < 1:\n self.deactivate_organisation(id)\n\n @CkanExceptionsHandler()\n def get_organisations_which_user_belongs(\n self, username, permission='manage_group'):\n # permission=read|create_dataset|manage_group\n res = self.call_action(\n 'organization_list_for_user', id=username, permission=permission)\n return [d['name'] for d in res if d['is_organization']]\n\n @CkanExceptionsHandler()\n def add_user_to_organisation(\n self, username, organisation_id, role='editor'):\n # role=member|editor|admin\n self.call_action(\n 'organization_member_create',\n id=str(organisation_id), username=username, role=role)\n\n @CkanExceptionsHandler()\n def del_user_from_organisation(self, username, organisation_id):\n self.call_action(\n 'organization_member_delete',\n id=str(organisation_id), username=username)\n\n @CkanExceptionsHandler()\n def del_user_from_organisations(self, username):\n organisations = self.get_organisations_which_user_belongs(username)\n if not organisations:\n return\n for organisation_name in organisations:\n self.del_user_from_organisation(username, organisation_name)\n\n @CkanExceptionsHandler(ignore=[CkanError.NotFound])\n def get_group(self, id, **kwargs):\n try:\n return self.call_action('group_show', id=str(id), **kwargs)\n except CkanError.NotFound:\n return None\n\n def is_group_exists(self, id):\n b = self.get_group(str(id)) and True or False\n if not b:\n logger.warning(\"CKAN group '{id}' does not exists.\".format(id=str(id)))\n return b\n\n @CkanExceptionsHandler()\n def create_partner_group(self, name):\n return self.call_action('group_create', type='partner', name=name)\n\n @CkanExceptionsHandler()\n def add_user_to_partner_group(self, username, name):\n ckan_group = self.get_group(name) or self.create_partner_group(name)\n\n users = ckan_group.pop('users', [])\n ckan_group['users'] = [\n {'id': user['id'], 'name': user['name']} for user in users]\n\n if username not in [user['name'] for user in ckan_group['users']]:\n ckan_group['users'].append({'name': username})\n\n self.call_action('group_update', **ckan_group)\n\n @CkanExceptionsHandler()\n def del_user_from_partner_group(self, username, id):\n if self.is_group_exists(id):\n self.call_action('group_member_delete', id=id, username=username)\n\n @CkanExceptionsHandler()\n def add_group(self, group, type=None):\n ckan_group = {\n 'id': str(group.ckan_id),\n 'type': type,\n 'title': group.name,\n 'name': group.slug,\n 'description': group.description}\n try:\n ckan_group['image_url'] = \\\n urljoin(settings.DOMAIN_NAME, group.picto.url)\n except ValueError:\n pass\n return self.call_action('group_create', **ckan_group)\n\n @CkanExceptionsHandler()\n def update_group(self, group):\n ckan_group = self.get_group(str(group.ckan_id), include_datasets=True)\n ckan_group.update({\n 'title': group.name,\n 'name': group.slug,\n 'description': group.description})\n\n for val in ('packages', 'tags', 'groups'):\n lst = ckan_group.get(val, [])\n if lst:\n del ckan_group[val]\n ckan_group[val] = [{'id': e['id'], 'name': e['name']} for e in lst]\n\n try:\n ckan_group['image_url'] = \\\n urljoin(settings.DOMAIN_NAME, group.picto.url)\n except ValueError:\n pass\n try:\n return self.call_action('group_update', **ckan_group)\n except CkanError.NotFound:\n return None\n\n @CkanExceptionsHandler()\n def del_group(self, id):\n self.call_action('group_purge', id=str(id))\n\n @CkanExceptionsHandler()\n def add_user_to_group(self, username, group_id):\n ckan_group = self.get_group(str(group_id), include_datasets=True)\n if not ckan_group:\n raise Exception(\"The group '{0}' does not exists\".format(str(group_id)))\n\n packages = ckan_group.get('packages', [])\n if packages:\n del ckan_group['packages']\n ckan_group['packages'] = \\\n [{'id': package['id'], 'name': package['name']} for package in packages]\n\n users = ckan_group.get('users', [])\n if users:\n del ckan_group['users']\n ckan_group['users'] = \\\n [{'id': user['id'], 'name': user['name'], 'capacity': 'admin'} for user in users]\n\n if username not in [user['name'] for user in ckan_group['users']]:\n ckan_group['users'].append({'name': username, 'capacity': 'admin'})\n\n self.call_action('group_update', **ckan_group)\n\n @CkanExceptionsHandler()\n def purge_dataset(self, id):\n try:\n return self.call_action('dataset_purge', id=id)\n except CkanError.NotFound:\n return None\n\n @CkanExceptionsHandler()\n def get_tags(self, query=None, all_fields=False, vocabulary_id=None):\n return self.call_action('tag_list', vocabulary_id=vocabulary_id,\n all_fields=all_fields, query=query)\n\n def is_tag_exists(self, name, vocabulary_id=None):\n try:\n return name in self.get_tags(vocabulary_id=vocabulary_id)\n except Exception:\n return False\n\n @CkanExceptionsHandler()\n def add_tag(self, name, vocabulary_id=None):\n return self.call_action(\n 'tag_create', name=name, vocabulary_id=vocabulary_id)\n\n @CkanExceptionsHandler()\n def add_vocabulary(self, name, tags):\n return self.call_action('vocabulary_create', name=name,\n tags=[{'name': tag} for tag in tags])\n\n @CkanExceptionsHandler()\n def get_vocabulary(self, id):\n try:\n return self.call_action('vocabulary_show', id=id)\n except CkanError.NotFound:\n return None\n\n @CkanExceptionsHandler()\n def get_licenses(self):\n return self.call_action('license_list')\n\n @CkanExceptionsHandler()\n def get_resource(self, id):\n return self.call_action('resource_show', id=id)\n\n\nCkanHandler = CkanManagerHandler()\n","repo_name":"DataSud/DataSud-2017-2019","sub_path":"idgo_admin/ckan_module.py","file_name":"ckan_module.py","file_ext":"py","file_size_in_byte":21138,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"42214586478","text":"#!/usr/bin/python3\nimport inspect\nimport defopt\nimport socket\nimport os\n\nfrom enum import Enum\nfrom rich import inspect\nfrom mininet.cli import CLI\nfrom datetime import datetime\nfrom rich.console import Console\nfrom ipaddress import IPv4Network\nfrom mininet.node import Controller\nfrom mininet.net import Containernet\n\nconsole = Console()\n\nclass Host(Enum):\n HOST_NORMAL = 0\n HOST_VULNERABLE = 1\n HOST_INFECTIONMONKEY = 2\n HOST_COLLECTOR = 3\n\nclass BASSDN():\n def __init__(self, network_range='10.0.0.0/24'):\n self.net = Containernet(controller=Controller)\n self.net.addController('c0')\n self.hosts = []\n self.switches = []\n self.links = []\n\n # network range used to keep track of assigned IP addresses.\n self.netrange = IPv4Network(network_range)\n self.netrange_iterator = (host for host in self.netrange.hosts())\n\n # create a list for each host type\n for type in (Host):\n self.hosts.append([])\n\n def addHost(self, host_type: Host):\n \"\"\"\n Adds a Docker host to the running network. Hosts are given a name of \n either `normX` (for normal), `vulnX` (for vulnerable), `monkX` (for \n monkey), and `collX` (for a collector). Hosts start at index `0` \n (i.e., `norm0`) and increase by one for each host of that type created.\n \"\"\"\n ip = next(self.netrange_iterator).__str__()\n hostname = \"\"\n\n if host_type == Host.HOST_NORMAL:\n hostname = f\"norm{self.hosts[host_type.value].__len__()}\"\n self.hosts[host_type.value].append(\n self.net.addDocker(\n name=hostname,\n ip=ip,\n dimage='normal'\n )\n )\n elif host_type == Host.HOST_VULNERABLE:\n hostname = f\"vuln{self.hosts[host_type.value].__len__()}\"\n self.hosts[host_type.value].append(\n self.net.addDocker(\n name=hostname,\n ip=ip,\n dimage='vulnerable',\n dcmd='/usr/sbin/sshd -D'\n )\n )\n elif host_type == Host.HOST_INFECTIONMONKEY:\n hostname = f\"monk{self.hosts[host_type.value].__len__()}\"\n self.hosts[host_type.value].append(\n self.net.addDocker(\n name=hostname,\n ip=ip,\n dimage='infectionmonkey',\n dcmd='/etc/service/InfectionMonkey-v1.13.0.AppImage '\n '--appimage-extract-and-run',\n ports=[5000],\n port_bindings={5000: 443},\n )\n )\n elif host_type == Host.HOST_COLLECTOR:\n hostname = f\"coll{self.hosts[host_type.value].__len__()}\"\n self.hosts[host_type.value].append(\n self.net.addDocker(\n name=hostname,\n ip=ip,\n dimage='collector',\n volumes=[f\"{os.getcwd()}/traffic_dumps/:/mnt/vol:rw\"]\n )\n )\n else:\n console.log(f\"host type {host_type} does not exist\",\n style=\"red\")\n\n console.log(f\"added host [b]{hostname}[/b] with address {ip}\")\n self.addLink(self.hosts[host_type.value][-1], self.switches[-1])\n\n def addSwitch(self):\n \"\"\"\n Adds a generic Mininet switch to the running network. Switches have the\n naming convention of `sX` where `X` is the index of the switch.\n \"\"\"\n i = self.switches.__len__()\n name = f\"s{i}\"\n self.switches.append(\n self.net.addSwitch(name)\n )\n\n console.log(f\"added switch [b]{name}[/b]\")\n\n def addLink(self, host_a, host_b):\n \"\"\"\n Adds a generic Mininet link between `host_a` and `host_b`.\n \"\"\"\n try:\n self.links.append(self.net.addLink(host_a, host_b))\n console.log(f\"added link [b]{host_a} <-> {host_b}[/b]\")\n except:\n console.log(f\"failed to add link [b]{host_a} <-> {host_b}[/b]\", \n style=\"red\")\n\n def start(self):\n \"\"\"\n Starts the Containernet instance.\n \"\"\"\n try:\n self.net.start()\n console.log(\"🚀 BASSDN instance started\")\n except:\n console.log(\"failed to start BASSDN instance!\",\n style=\"red\")\n\n def commandLine(self):\n \"\"\"\n Starts the Containernet command line tool.\n \"\"\"\n try:\n CLI(self.net)\n except:\n console.log(\"containernet CLI raised an error\",\n style=\"red\")\n finally:\n return\n\n def stop(self):\n \"\"\"\n Stops the Containernet instance.\n \"\"\"\n try:\n self.net.stop()\n console.log(\"stopped BASSDN instance\")\n except:\n console.log(\"failed to stop BASSDN instance!\",\n style=\"red\")\n\n\ndef get_host_ip():\n \"\"\"\n Returns the IP Address of the host machine.\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.settimeout(0)\n s.connect(('254.254.254.254', 1))\n ip = s.getsockname()[0]\n s.close()\n return ip\n\n\ndef main(*, n_hosts: int = 4, v_hosts: int = 4, segments: int = 1,\n network_range: str = '10.0.0.0/24'):\n \"\"\"\n Launches a software-defined network with vulnerable and non-vulnerable hosts\n as well as one Infection Monkey instance. \n\n :param int n_hosts: Number of regular (non-vulnerable) hosts to deploy\n :param int v_hosts: Number of vulnerable hosts to deploy\n :param int segments: Number of network segments (i.e. switches) to deploy\n :param str network_range: CIDR IP range that the network will operate in\n \"\"\"\n bassdn = BASSDN(network_range=network_range)\n\n total_hosts = n_hosts + v_hosts # includes collector and monkey\n hosts_per_segment = total_hosts // segments\n\n # add hosts and link them by segment\n for _ in range(segments):\n bassdn.addSwitch()\n for _ in range(hosts_per_segment):\n if (n_hosts > 0):\n bassdn.addHost(Host.HOST_NORMAL)\n n_hosts = n_hosts - 1\n elif (v_hosts > 0):\n bassdn.addHost(Host.HOST_VULNERABLE)\n v_hosts = v_hosts - 1\n \n # add links to each switch\n for i, switch_a in enumerate(bassdn.switches):\n if i < (len(bassdn.switches) - 1):\n switch_b = bassdn.switches[i + 1]\n bassdn.addLink(switch_a, switch_b)\n\n \"\"\" always attaches to the last switch \"\"\"\n # add infection monkey source\n bassdn.addHost(Host.HOST_INFECTIONMONKEY)\n # add a collector to dump traffic info\n bassdn.addHost(Host.HOST_COLLECTOR)\n # start collector\n bassdn.hosts[Host.HOST_COLLECTOR.value][0].cmd(\n f\"tshark -i coll0-eth0 > /mnt/vol/coll0-traffic-\" \\\n f\"{datetime.now().strftime('%d-%m-%Y-%H-%M-%S')}.dmp &\"\n )\n console.log(\"started [b]data collector[/b] on [b]coll0[/b]\\n\" \\\n f\"[b]dump file[/b]: {os.getcwd()}/traffic_dumps/coll0-\" \\\n f\"traffic-{datetime.now().strftime('%d-%m-%Y-%H-%M-%S')}.dmp\")\n\n bassdn.start()\n\n console.print(\"\\nPlease access the Infection Monkey webserver on \"\n f\"https://{get_host_ip()}/\",\n style='bold',\n justify='center')\n console.print(\"Upload the `monkey.conf` file to the configuration \"\n \"settings to initialise the attack.\\n\",\n justify='center')\n \n bassdn.commandLine()\n bassdn.stop()\n\n\nif __name__ == \"__main__\":\n defopt.run(main, short={'n-hosts': 'n', 'v-hosts': 'v', 'segments': 's'})\n","repo_name":"xiaoyujia/basssdn","sub_path":"bassdn.py","file_name":"bassdn.py","file_ext":"py","file_size_in_byte":7793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5796548809","text":"from tqdm import tqdm\nimport argparse\nfrom get_data import HumanAtlasDatasetTest, HumanAtlasDataset\n\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom networks import DenseNet121\nimport os\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\nimport pandas as pd\nfrom options import test_options\n\nopt = test_options()\n\n# get DataLoader:\ntest_dataset = HumanAtlasDataset(data_dir=opt.data_dir, label_file=opt.image_list, n_class=opt.n_class, \n\t\t\t\t\t\t\t\t\t\ttransform = transforms.Compose([\n\t\t\t\t\t\t\t\t\t\ttransforms.ToTensor()\n\t\t\t\t\t\t\t\t\t\t]))\n# get dataloader\ntest_loader = DataLoader(dataset=test_dataset, batch_size=opt.batch_size, shuffle=False, num_workers=0, pin_memory=True)\n\nmodel_0 = DenseNet121(opt.n_class).cuda()\nmodel_1 = DenseNet121(opt.n_class).cuda()\nmodel_2 = DenseNet121(opt.n_class).cuda()\n\ncheckpoint_0 = torch.load(f\"{opt.chckpnt_dir}/{opt.chckpnt_folder}/model_0_{opt.model_type}.pth.tar\")\ncheckpoint_1 = torch.load(f\"{opt.chckpnt_dir}/{opt.chckpnt_folder}/model_1_{opt.model_type}.pth.tar\")\ncheckpoint_2 = torch.load(f\"{opt.chckpnt_dir}/{opt.chckpnt_folder}/model_2_{opt.model_type}.pth.tar\")\n\nmodel_0.load_state_dict(checkpoint_0['model'])\nmodel_1.load_state_dict(checkpoint_1['model'])\nmodel_2.load_state_dict(checkpoint_2['model'])\n\n# switch to evaluate mode\nmodel_0.eval()\t\nmodel_1.eval()\t\nmodel_2.eval()\t\n\ncounter = 0\ntp = np.zeros(opt.n_class) # True Positive array\nfp = np.zeros(opt.n_class) # False Positive array\nfn = np.zeros(opt.n_class) # False Negative array\n\nloader = tqdm(test_loader, total=len(test_loader))\nfor _, (images, labels) in enumerate(loader):\n\n\timages = Variable(images.cuda())\n\toutput_0 = model_0(images) \n\toutput_1 = model_1(images) \n\toutput_2 = model_2(images) \n\n\tpred_arr_0 = output_0.cpu().detach().numpy()\n\tpred_arr_1 = output_1.cpu().detach().numpy()\n\tpred_arr_2 = output_2.cpu().detach().numpy()\n\n\tlabel_arr = labels.cpu().detach().numpy()\n\n\tpred_arr = pred_arr_0 + pred_arr_1 + pred_arr_2\n\tpred_arr = (pred_arr > 1.0).astype(np.int32)\n\n\ttp_batch = label_arr * pred_arr # multiplication of the label and pred arrays\n\ttp += tp_batch.sum(axis=0) # sum for all samples throughout the batch\n\n\tfp_batch = (label_arr * pred_arr + pred_arr) % 2 \n\tfp += fp_batch.sum(axis=0)\n\n\tfn_batch = (label_arr * pred_arr + label_arr) % 2 \n\tfn += fn_batch.sum(axis=0)\n\n\tcounter += 1\n\nprecision = tp / (tp + fp + 1e-8)\nrecall = tp / (tp + fn + 1e-8)\n# calculate f1 score for all classes and average for all classes as unweighted:\nmacro_f = (2 * precision * recall / (precision + recall + 1e-18)).mean()\n\nprint(f'Final Macro-F score is: {macro_f:.4f}')","repo_name":"sers9/protein_pattern_classification","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12532698689","text":"import paho.mqtt.client as paho\nimport os\nimport time\nimport gi\n\n\ngi.require_version(\"Gst\", \"1.0\")\n\nfrom gi.repository import Gst\n\nGst.init(None)\n\n\n\ndef startRecord():\n print(\"starting record\")\n\n recordName = time.strftime(\"%Y-%m-%d-%H:%M\") + \".ogg\"\n\n global pipeline\n pipeline = Gst.parse_launch(\"autoaudiosrc ! audioconvert ! queue ! vorbisenc ! oggmux ! filesink location={}\".format(recordName))\n pipeline.set_state(Gst.State.PLAYING)\n\ndef stopRecord():\n print(\"stop record\")\n\n global pipeline\n pipeline.set_state(Gst.State.NULL)\n\n\n# Define event callbacks\ndef on_connect(mosq, obj, rc):\n print(\"rc: \" + str(rc))\n\ndef on_message(mosq, obj, msg):\n print(msg.topic + \" \" + str(msg.qos) + \" \" + str(msg.payload))\n\n if msg.payload == \"start\":\n startRecord()\n\n if msg.payload == \"stop\":\n stopRecord()\n\ndef on_publish(mosq, obj, mid):\n print(\"mid: \" + str(mid))\n\ndef on_subscribe(mosq, obj, mid, granted_qos):\n print(\"Subscribed: \" + str(mid) + \" \" + str(granted_qos))\n\ndef on_log(mosq, obj, level, string):\n print(string)\n\nmqttc = paho.Client()\n\n# Assign event callbacks\nmqttc.on_message = on_message\nmqttc.on_connect = on_connect\nmqttc.on_publish = on_publish\nmqttc.on_subscribe = on_subscribe\n\n# Uncomment to enable debug messages\n#mqttc.on_log = on_log\n\n# Connect\nmqttc.connect(\"localhost\")\n\n# Start subscribe, with QoS level 0\nmqttc.subscribe(\"neg-record/pipeline\", 0)\n\n# Continue the network loop, exit when an error occurs\nrc = 0\nwhile rc == 0:\n rc = mqttc.loop()\n\nprint(\"rc: \" + str(rc))\n","repo_name":"victor1234/neg-record","sub_path":"mqtt-test.py","file_name":"mqtt-test.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"14804788530","text":"# Samuel Carroll\n# CptS 355\n# Homework 4 Pt 1\n## All functions contain debug/error messages. Seperated by code\n## Comments designating what following section will contain.\n\n######################### OpStack with pop and push #############################\nopstack = []\n\n\ndef opPop():\n if opstack:\n x = opstack[-1]\n del opstack[-1]\n return x\n else:\n print(\"No values in opstack\")\n return None\n\ndef opPush(value):\n opstack.append(value)\n\n\n######################## DictStack with pop, push, define, and lookup #######################\n\n\ndictstack = []\n\n\ndef dictPop():\n if dictstack:\n del dictstack[-1]\n else:\n print(\"Stack is empty\")\n\ndef dictPush(d):\n dictstack.append(d)\n\n\ndef define(name,value):\n if dictstack:\n dictstack[-1][name] = value\n else:\n dictstack.append( {name:value} )\n\n\ndef lookup(name):\n for val in reversed(dictstack):\n if ('/'+name) in val.keys():\n return val['/'+name]\n print(\"Error - Item not found\")\n return None\n\n\n####################### Operators Ints ####################\n\n\ndef add():\n if len(opstack) > 1:\n a = opPop()\n b = opPop()\n if isinstance(a,(int,float)) and isinstance(b,(int,float)):\n opPush(a + b)\n else:\n print(\"Error Add - Non ints returned\")\n else:\n print(\"Error Add - Not enough values in stack or non ints present\")\n\n\ndef sub():\n if len(opstack) > 1:\n a = opPop()\n b = opPop()\n if isinstance(a,(int,float)) and isinstance(b,(int,float)):\n opPush(b - a)\n else:\n print(\"Error Sub - Non ints returned\")\n else:\n print(\"Error Sub - Not enough values in stack or non ints present\")\n\n\ndef mul():\n if len(opstack) > 1:\n a = opPop()\n b = opPop()\n if isinstance(a,(int,float)) and isinstance(b,(int,float)):\n opPush(a * b)\n else:\n print(\"Error Mul - Non ints returned\")\n else:\n print(\"Error Mul - Not enough values in stack or non ints present\")\n\ndef div():\n if len(opstack) > 1:\n a = opPop()\n b = opPop()\n if isinstance(a,(int,float)) and isinstance(b,(int,float)):\n opPush(b / a)\n else:\n print(\"Error Div - Non ints returned\")\n else:\n print(\"Error Div - Not enough values in stack or non ints present\")\n\ndef mod():\n if len(opstack) > 1:\n a = opPop()\n b = opPop()\n if isinstance(a,(int,float)) and isinstance(b,(int,float)):\n opPush(b % a)\n else:\n print(\"Error Mod - Non ints returned\")\n else:\n print(\"Error Mod - Not enough values in stack or non ints present\")\n\n\n####################### Operators Arrays ####################\n\ndef length():\n if opstack and isinstance(opstack[-1],list):\n opstack.append(len(opstack[-1]))\n else:\n print(\"Error Length - Empty stack or non array at start\")\n\n\ndef get():\n if len(opstack) > 1:\n value = opPop()\n arr = opPop()\n if isinstance(arr,list) and isinstance(value,int) and value >= 0 and value <= len(opstack):\n opPush(arr[value])\n elif isinstance(arr,int) and isinstance(value,list) and arr >= 0 and value <= len(opstack):\n opPush(value[arr])\n else:\n print(\"Error Get - Improper return types from operator stack\")\n else:\n print(\"Error Get - Too few items in opstack\")\n\n\n################# Stack manipulation and print operators ###################\n\ndef dup():\n\n if opstack:\n opPush(opstack[-1])\n else:\n print(\"Error Dup - Empty stack\")\n\n\ndef exch():\n if len(opstack) > 1:\n a = opPop()\n b = opPop()\n opPush(a)\n opPush(b)\n else:\n print(\"Error Exch - Stack has insufficient nodes\")\n\n\ndef pop():\n if opstack:\n print(\"Popped Value:\", opstack[-1])\n del opstack[-1]\n else:\n print(\"Error Pop - Stack has insufficient nodes\")\n\n\ndef roll():\n top = opPop()\n Spos = opPop()\n if top <= len(opstack):\n hold = opstack[len(opstack) - Spos:]\n for i in range(Spos):\n opPop()\n if top:\n for val in range(abs(top)):\n temp = hold[0]\n hold.append(temp)\n hold.remove(temp)\n else:\n for val2 in range(top):\n temp = hold.pop()\n hold.insert(0,temp)\n for val3 in hold:\n opPush(val3)\n else:\n print(\"Error Roll - Rolling more than in stack\")\n\n\ndef copy():\n newlist = []\n if opstack:\n val = opPop()\n if val <= len(opstack) + 1:\n for i in range(val):\n newlist.append(opPop())\n newlist.reverse()\n opstack.extend(newlist + newlist)\n else:\n print(\"Error Copy - Input greater than stack length\")\n else:\n print(\"Error Copy - Empty Stack\")\n\n\ndef clear():\n del opstack[:]\n\n\ndef stack():\n print(opstack)\n\n\n################# Dictionary Manipulations ################\n\ndef psDict():\n opPop()\n opPush({})\n\n\ndef begin():\n if opstack:\n a = opPop()\n if (isinstance(a,dict)):\n dictPush(a)\n else:\n print(\"Error Begin - Non Dictionary type\")\n else:\n print(\"Error Begin - Empty Stack\")\n\n\ndef end():\n if dictstack:\n del dictstack[-1]\n else:\n print(\"Error End - Dictstack Empty\")\n\n\ndef psDef():\n if len(opstack) > 1:\n newval = opPop()\n newname = opPop()\n if isinstance(newname, str):\n define(newname,newval)\n else:\n print(\"Error PSDef - Name value not a string\")\n else:\n print(\"Error PSDef - Insufficient nodes in opstack\")\n\n\n#------- Part 1 TEST CASES--------------\ndef testDefine():\n define(\"/n1\", 4)\n define(\"/n2\", 0)\n define(\"/n3\", -15)\n define(\"/n4\", 1000)\n if lookup(\"n1\") != 4 and lookup(\"n2\") != 0 and lookup(\"n3\") != -15 and lookup(\"n4\") != 1000:\n return False\n return True\n\ndef testLookup():\n opPush(\"/n1\")\n opPush(3)\n psDef()\n opPush(\"/n2\")\n opPush(0)\n psDef()\n opPush(\"/n3\")\n opPush(-15)\n psDef()\n opPush(\"/n4\")\n opPush(1000)\n psDef()\n if lookup(\"n1\") != 4 and lookup(\"n2\") != 0 and lookup(\"n3\") != -15 and lookup(\"n4\") != 1000:\n return False\n return True\n\n#Arithmatic operator tests\ndef testAdd():\n opPush(1)\n opPush(2)\n add()\n T1 = opPop()\n opPush(15)\n opPush(-5)\n add()\n T2 = opPop()\n opPush(0)\n opPush(0)\n add()\n T3 = opPop()\n opPush(-5)\n opPush(1000)\n add()\n T4 = opPop()\n if T1 != 3 and T2 != 10 and T3 != None and T4 != -995:\n return False\n return True\n\ndef testSub():\n opPush(10)\n opPush(4.5)\n sub()\n T1 = opPop()\n opPush(15)\n opPush(-5)\n sub()\n T2 = opPop()\n opPush(0)\n opPush(0)\n sub()\n T3 = opPop()\n opPush(-5)\n opPush(1000)\n sub()\n T4 = opPop()\n if T1 != 5.5 and T2 != 20 and T3 != 0 and T4 != -1005:\n return False\n return True\n\ndef testMul():\n opPush(2)\n opPush(4.5)\n mul()\n T1 = opPop()\n opPush(.5)\n opPush(-5)\n mul()\n T2 = opPop()\n opPush(0)\n opPush(0)\n mul()\n T3 = opPop()\n opPush(-5)\n opPush(1000)\n mul()\n T4 = opPop()\n if T1 != 9 and T2 != -2.5 and T3 != None and T4 != -5000:\n return False\n return True\n\ndef testDiv():\n opPush(10)\n opPush(4)\n div()\n T1 = opPop()\n opPush(15)\n opPush(-5)\n sub()\n T2 = opPop()\n opPush(50)\n opPush(0)\n sub()\n T3 = opPop()\n opPush(5)\n opPush(1)\n sub()\n T4 = opPop()\n if T1 != 2.5 and T2 != -3 and T3 != 0 and T4 != .2:\n return False\n return True\n\ndef testMod():\n opPush(10)\n opPush(3)\n mod()\n T1 = opPop()\n opPush(15)\n opPush(-5)\n sub()\n T2 = opPop()\n opPush(3)\n opPush(3)\n sub()\n T3 = opPop()\n opPush(6)\n opPush(1000)\n sub()\n T4 = opPop()\n if T1 != 1 and T2 != 10 and T3 != None and T4 != 4:\n return False\n return True\n\n#Array operator tests\ndef testLength():\n opPush([1,2,3,4,5])\n length()\n T1 = opPop()\n opPush([])\n length()\n T2 = opPop()\n opPush([\"One\", \"Two\", \"Three\"])\n length()\n T3 = opPop()\n opPush([[],[1],[1,2],[1,2,3]])\n length()\n T4 = opPop()\n if T1 != 5 and T2 != None and T3 != 3 and T4 != 4:\n return False\n return True\n\ndef testGet():\n opPush([1,2,3,4,5])\n opPush(4)\n get()\n T1 = opPop()\n opPush([1,2,3,4,5])\n opPush(0)\n get()\n T2 = opPop()\n opPush([\"One\", \"Two\", \"Three\"])\n opPush(2)\n get()\n T3 = opPop()\n opPush([[],[1],[1,2],[1,2,3]])\n opPush(3)\n get()\n T4 = opPop()\n if T1 != 5 and T2 != 1 and T3 != \"Three\" and T4 != [1,2,3]:\n return False\n return True\n\n#stack manipulation functions\ndef testDup():\n vals = [10,'a',-5,\"Hello\"]\n for i in vals:\n opPush(i)\n dup()\n if opPop()!=opPop():\n return False\n return True\n\ndef testExch():\n opPush(10)\n opPush(\"/x\")\n exch()\n if opPop()!=10 and opPop()!=\"/x\":\n return False\n return True\n\ndef testPop():\n l1 = len(opstack)\n opPush(10)\n pop()\n l2 = len(opstack)\n if l1 != l2:\n return False\n l1 = len(opstack)\n opPush(10)\n opPush(10)\n pop()\n pop()\n l2 = len(opstack)\n if l1 != l2:\n return False\n l1 = len(opstack)\n opPush(10)\n opPush(10)\n opPush(10)\n pop()\n pop()\n pop()\n l2 = len(opstack)\n if l1 != l2:\n return False\n l1 = len(opstack)\n opPush(10)\n opPush(10)\n opPush(10)\n opPush(10)\n pop()\n pop()\n pop()\n pop()\n l2 = len(opstack)\n if l1 != l2:\n return False\n return True\n\ndef testRoll():\n opPush(1)\n opPush(2)\n opPush(3)\n opPush(4)\n opPush(5)\n opPush(4)\n opPush(-2)\n roll()\n if opPop()!=3 and opPop()!=2 and opPop()!=5 and opPop()!=4 and opPop()!=1:\n return False\n opPush(7)\n opPush(3)\n opPush(9)\n opPush(6)\n opPush(13)\n opPush(5)\n opPush(-3)\n roll()\n if opPop()!=9 and opPop()!=3 and opPop()!=7 and opPop()!=13 and opPop()!=6:\n return False\n opPush(7)\n opPush(3)\n opPush(9)\n opPush(6)\n opPush(13)\n opPush(5)\n opPush(4)\n roll()\n if opPop()!=6 and opPop()!=9 and opPop()!=3 and opPop()!=7 and opPop()!=13:\n return False\n opPush(0)\n opPush(0)\n opPush(-3)\n opPush(-13)\n opPush(-5)\n opPush(2)\n opPush(1)\n roll()\n if opPop()!=-13 and opPop()!=-5 and opPop()!=-3 and opPop()!=0 and opPop()!=0:\n return False\n return True\n\ndef testCopy():\n opPush(1)\n opPush(2)\n opPush(3)\n opPush(4)\n opPush(5)\n opPush(2)\n copy()\n if opPop()!=5 and opPop()!=4 and opPop()!=5 and opPop()!=4 and opPop()!=3 and opPop()!=2:\n return False\n opPush(\"Hello\")\n opPush(\"Grader\")\n opPush(\"Please\")\n opPush(\"Provide\")\n opPush(\"An\")\n opPush(\"A\")\n opPush(7)\n copy()\n if opPop()!=\"A\" and opPop()!=\"An\" and opPop()!=\"Provide\" and opPop()!=\"Please\" and opPop()!=\"Grader\" and opPop()!=\"Hello\":\n return False\n opPush(1)\n opPush(2)\n opPush(3)\n opPush(4)\n opPush(6)\n opPush(3)\n copy()\n if opPop()!=6 and opPop()!=4 and opPop()!=3:\n return False\n opPush(0)\n opPush(0)\n opPush(0)\n opPush(0)\n copy()\n if opPop()!=0:\n return False\n return True\n\ndef testClear():\n opPush(10)\n opPush(\"/x\")\n clear()\n if len(opstack)!=0:\n return False\n opPush(10)\n opPush(\"/x\")\n opPush({\"/x\":10})\n clear()\n if len(opstack)!=0:\n return False\n opPush(0)\n clear()\n if len(opstack)!=0:\n return False\n opPush(15)\n opPush(\"No\")\n opPush('a')\n clear()\n if len(opstack)!=0:\n return False\n return True\n\n#dictionary stack operators\ndef testDict():\n opPush(1)\n psDict()\n if opPop()!={}:\n return False\n opPush({\"Name\":5})\n opPush(8)\n opPop()\n psDict()\n if opPop()!={}:\n return False\n opPush({\"new\":\"Val\"})\n opPush({\"Old\":\"Newval\"})\n opPush({\"Not\":'3'})\n psDict()\n if opPop()!={}:\n return False\n opPush(10000)\n psDict()\n if opPop()!={}:\n return False\n return True\n\ndef testBeginEnd():\n opPush(\"/x\")\n opPush(3)\n psDef()\n opPush({})\n begin()\n opPush(\"/x\")\n opPush(4)\n psDef()\n end()\n if lookup(\"x\")!=3:\n return False\n opPush(\"/y\")\n opPush(15)\n psDef()\n opPush({})\n begin()\n opPush(\"/y\")\n opPush(15)\n psDef()\n end()\n if lookup(\"y\")!=15:\n return False\n opPush(\"/z\")\n opPush(\"No\")\n psDef()\n opPush({})\n begin()\n opPush(\"/z\")\n opPush(4)\n psDef()\n end()\n if lookup(\"z\")!=\"No\":\n return False\n opPush(\"/a\")\n opPush('a')\n psDef()\n opPush({})\n begin()\n opPush(\"/a\")\n opPush(\"b\")\n psDef()\n end()\n if lookup(\"a\")!='a':\n return False\n return True\n\ndef testpsDef():\n opPush(\"/x\")\n opPush(10)\n psDef()\n if lookup(\"x\")!=10:\n return False\n return True\n\ndef testpsDef2():\n opPush(\"/x\")\n opPush(10)\n psDef()\n opPush(1)\n psDict()\n begin()\n if lookup(\"x\")!=10:\n end()\n return False\n opPush(\"/y\")\n opPush(\"a\")\n psDef()\n opPush(1)\n psDict()\n begin()\n if lookup(\"y\")!=\"a\":\n end()\n return False\n opPush(\"/z\")\n opPush(None)\n psDef()\n opPush(15)\n psDict()\n begin()\n if lookup(\"z\")!=None:\n end()\n return False\n opPush(\"/a\")\n opPush([1,1,2,3,5,8])\n psDef()\n opPush(\"Hello\")\n psDict()\n begin()\n if lookup(\"a\")!=[1,1,2,3,5,8]:\n end()\n return False\n end()\n return True\n\n\ndef main_part1():\n testCases = [('define',testDefine),('lookup',testLookup),('add', testAdd), ('sub', testSub),('mul', testMul),('div', testDiv), ('mod', testMod), \\\n ('length', testLength),('get', testGet), ('dup', testDup), ('exch', testExch), ('pop', testPop), ('roll', testRoll), ('copy', testCopy), \\\n ('clear', testClear), ('dict', testDict), ('begin', testBeginEnd), ('psDef', testpsDef), ('psDef2', testpsDef2)]\n # add you test functions to this list along with suitable names\n failedTests = [testName for (testName, testProc) in testCases if not testProc()]\n if failedTests:\n print(\"Fail\")\n return ('Some tests failed', failedTests)\n else:\n print(\"Pass\")\n return ('All part-1 tests OK')\n\n\nmain_part1()","repo_name":"SamCarroll6/CptS-355","sub_path":"HW4P1.py","file_name":"HW4P1.py","file_ext":"py","file_size_in_byte":14627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19961814339","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 03.01.2019\n\n@author: beckmann\n\nCan be run from a desktop pycharm to execute on a remote (ssh) raspberry Pi, by setting environment variable:\nDISPLAY=:0 lets plots appear on pi\nDISPLAY=localhost:10.0 lets plots appear on Pycharm desktop machine\n\nif plot is on Pi:\n* Pi keyboard is captured\n* plot updates on Pi\n* console output arrives in Pycharm.\n\"\"\"\nimport time\n\nimport matplotlib\nprint(matplotlib.rcsetup.all_backends)\nmatplotlib.use(\"TkAgg\")\n\nimport matplotlib.pyplot as plt\nimport numpy\nimport sys\n\n\nclass InteractivePlot:\n def __init__(self):\n self.fig, self.ax = plt.subplots()\n\n self.fig.canvas.mpl_connect('key_press_event', lambda event: self.press(event))\n\n self.ys = [0.]\n self.plot, = self.ax.plot(self.ys)\n\n self.time_last_draw = time.time()\n\n def press(self, event):\n self.ys.append(numpy.random.randn())\n\n print('press', event.key, len(self.ys))\n sys.stdout.flush()\n\n self.update_plot()\n\n def update_plot(self):\n self.plot.set_ydata(self.ys)\n self.plot.set_xdata(range(len(self.ys)))\n\n now = time.time()\n if now - self.time_last_draw > .2:\n self.time_last_draw = now\n self.ax.relim()\n self.ax.autoscale_view()\n self.fig.canvas.draw()\n else:\n print(\"not updating after\", now - self.time_last_draw)\n #self.fig.canvas.flush_events()\n\n\nif __name__ == '__main__':\n InteractivePlot()\n plt.show()\n","repo_name":"holmos-ipm/holmos-rpi","sub_path":"other/test_remote_ui.py","file_name":"test_remote_ui.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"85"} +{"seq_id":"9644849264","text":"from threading import Thread\nimport time\n\ndef tarea1(id, r):\n global contador\n for i in range(50):\n contador += 1\n time.sleep(1)\n\ndef tarea2(id, r):\n global contador\n for i in range(50,0,-1):\n print(\"contador =\", contador)\n time.sleep(1)\n\ncontador = 0\nhilo1 = Thread(target=tarea1, args=(1,20))\nhilo2 = Thread(target=tarea2, args=(2, 20))\n\nhilo1.start()\nhilo2.start()\n\nhilo1.join()\nhilo2.join()","repo_name":"drcabreramendieta/ejemplosPython","sub_path":"hilos3.py","file_name":"hilos3.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27617613512","text":"#!/usr/bin/env python\n\nfrom helpers import email\nfrom google.appengine.ext import webapp, db\nfrom google.appengine.ext.webapp import util, template\nfrom google.appengine.api import users\nimport datetime, urllib, logging\n\nfrom django.utils import encoding\n\nPER_PAGE = 10\nMAX_PER_PAGE = 100\n\n# def redirect(handler_method):\n# def redirect_if_needed(self, *args, **kwargs):\n# if 'www' not in self.request.referrer and 'admonymous' in self.request.referrer:\n# try:\n# self.redirect(re.sub('admonymous.co', 'www.admonymous.co', self.request.referrer))\n# except:\n# handler_method(self, *args, **kwargs)\n# else:\n# handler_method(self, *args, **kwargs)\n# return redirect_if_needed\n\nclass User(db.Model):\n username = db.StringProperty()\n name = db.StringProperty()\n google_account = db.UserProperty(auto_current_user_add=True)\n create_date = db.DateTimeProperty(auto_now_add=True)\n update_date = db.DateTimeProperty(auto_now=True)\n message = db.TextProperty()\n # image = db.BlobProperty\n \n def message_html(self):\n from helpers.textile import textile\n return textile.textile(self.message)\n\n @classmethod\n def get_current(cls):\n google_account = users.get_current_user()\n if not google_account:\n return\n user = cls.all().filter('google_account', google_account).get()\n return user\n \n def first_name(self):\n import re\n return re.split(self.name, ' ')[0]\n\nclass Response(db.Model):\n user = db.ReferenceProperty(User)\n create_date = db.DateTimeProperty(auto_now_add=True)\n body = db.TextProperty()\n author = db.StringProperty()\n reveal_datetime = db.DateTimeProperty(default=datetime.datetime.now())\n revealed = db.BooleanProperty(default=False)\n\ndef get_bounded_int_value(s, default, lower_bound = None, upper_bound = None):\n if s:\n try:\n value = int(s)\n if lower_bound and value < lower_bound:\n value = lower_bound\n if upper_bound and value > upper_bound:\n value = upper_bound\n except ValueError:\n value = default\n else:\n value = default\n return value\n\nclass HomeHandler(webapp.RequestHandler):\n # @redirect\n def get(self):\n google_account = users.get_current_user()\n if google_account:\n user = User.all().filter('google_account', google_account).get()\n if not user:\n user = User()\n template_values = {\n 'user':user,\n }\n per_page = get_bounded_int_value(self.request.get('per_page'), PER_PAGE, 1, MAX_PER_PAGE)\n offset = get_bounded_int_value(self.request.get('offset'), 0, 0)\n responses = Response.all().filter('user', user).order('-create_date').fetch(limit=per_page+1, offset=offset) if user.is_saved() else []\n if offset > 0:\n template_values['older_offset'] = max(0, offset - per_page)\n if len(responses) == per_page+1:\n responses.pop()\n template_values['newer_offset'] = offset + per_page\n for response in responses:\n response.response_id = response.key().id()\n template_values['responses'] = responses\n else:\n template_values = {}\n path = 'templates/home.html'\n page = template.render(path, template_values, debug=(True if 'local' in self.request.host_url or users.is_current_user_admin() else False))\n self.response.out.write(page)\n\n def post(self):\n \n def namify(inStr, spacechar='_'):\n import re\n aslug = re.sub('[^\\w\\s-]', '', inStr).strip().lower()\n aslug = re.sub('\\s+', spacechar, aslug)\n return aslug\n \n google_account = users.get_current_user()\n if google_account:\n user = User.all().filter('google_account', google_account).get()\n username = namify(self.request.get('username'))\n user_with_username_key = User.all(keys_only=True).filter('username', username).get()\n if user:\n username_taken = True if user_with_username_key != None and user_with_username_key != user.key() else False\n else:\n username_taken = True if user_with_username_key != None else False\n user = User()\n if not username_taken:\n if user.username:\n success = True\n else:\n success = None\n user.username = username\n else:\n success = False\n user.name = self.request.get('name')\n user.message = self.request.get('message')\n user.put()\n template_values = {\n 'user':user,\n 'success':success,\n 'username_taken':username if username_taken else False,\n 'logout_url':users.create_logout_url('/')\n }\n per_page = get_bounded_int_value(self.request.get('per_page'), PER_PAGE, 1, MAX_PER_PAGE)\n offset = get_bounded_int_value(self.request.get('offset'), 0, 0)\n responses = Response.all().filter('user', user).order('-create_date').fetch(limit=per_page+1, offset=offset)\n if offset > 0:\n template_values['older_offset'] = max(0, offset - per_page)\n if len(responses) == per_page+1:\n responses.pop()\n template_values['newer_offset'] = offset + per_page\n template_values['responses'] = responses\n else:\n template_values = {'login_url':users.create_login_url()}\n path = 'templates/home.html'\n page = template.render(path, template_values, debug=(True if 'local' in self.request.host_url or users.is_current_user_admin() else False))\n self.response.out.write(page)\n\nclass UserPageHandler(webapp.RequestHandler):\n def get(self, username):\n target_user = User.all().filter('username', username).get()\n if (username == 'admonymous') and not target_user:\n admonymous_user = User(username = 'admonymous',\n name = 'Admonymous',\n google_account = None)\n admonymous_user.put()\n target_user = admonymous_user\n template_values = {\n 'target_user':target_user,\n 'target_user_first_name':target_user.first_name,\n 'user':User.all().filter('google_account', users.get_current_user()).get(), \n 'logout_url':users.create_logout_url('/'), \n 'login_url':users.create_login_url('/')\n }\n path = 'templates/user.html'\n page = template.render(path, template_values, debug=(True if 'local' in self.request.host_url or users.is_current_user_admin() else False))\n self.response.out.write(page)\n \n def post(self, username):\n from helpers.textile import textile\n target_user = User.all().filter('username', username).get()\n template_values = {\n 'target_user':target_user,\n 'user':User.all().filter('google_account', users.get_current_user()).get(), \n 'logout_url':users.create_logout_url('/'), \n 'login_url':users.create_login_url('/'),\n 'success':True\n }\n author=self.request.get('author')\n body = self.request.get('body')\n if self.request.get('email') != '':\n notification = email.EmailMessage(sender='Admonymous ', to='eloise.rosen@gmail.com', subject='BOT left someone a response on Admonymous')\n notification.render_and_send('notification', {\n 'target_user':target_user,\n 'author':None if author == 'anonymous' else author,\n 'body_html':response.body,\n 'body_txt':body\n })\n else:\n response = Response(body=encoding.force_unicode(textile.textile(encoding.smart_str(body), encoding='utf-8', output='utf-8')), author=author, user=target_user, revealed=True)\n response.put()\n if target_user.google_account:\n target_email = target_user.google_account.email()\n elif target_user.username == 'admonymous':\n target_email = 'eloise.rosen@gmail.com'\n \n if response.body:\n notification = email.EmailMessage(sender='Admonymous ', to=target_email, subject='%s left you a response on Admonymous' % ('Someone' if not author else author))\n notification.render_and_send('notification', {\n 'target_user':target_user,\n 'author':None if author == 'anonymous' else author,\n 'body_html':response.body,\n 'body_txt':body\n })\n path = 'templates/user.html'\n page = template.render(path, template_values, debug=(True if 'local' in self.request.host_url or users.is_current_user_admin() else False))\n self.response.out.write(page)\n\nclass ContactHandler(webapp.RequestHandler):\n def get(self):\n user = User.get_current()\n page = template.render('templates/contact.html', {'user':user})\n self.response.out.write(page)\n\nclass SuggestionsHandler(webapp.RequestHandler):\n def get(self):\n user = User.get_current()\n args = self.request.arguments()\n all_topics = [{'name': 'giving', 'description': 'Giving admonition'},\n {'name': 'receiving', 'description': 'Receiving admonition'},\n {'name': 'anonymity', 'description': 'Maintaining anonymity'},\n {'name': 'faq', 'description': 'Frequently Asked Questions'}]\n page = template.render('templates/suggestions.html', {'user':user, 'topic':args, 'topic_list': all_topics})\n self.response.out.write(page)\n\nclass PrintablePageHandler(webapp.RequestHandler):\n def get(self):\n google_account = users.get_current_user()\n if google_account:\n user = User.all().filter('google_account', google_account).get()\n if not user:\n self.redirect('/')\n encoded_url = urllib.quote(\"https://www.admonymous.co/%s\"%(user.username))\n template_values = {'user':user, 'encoded_url':encoded_url}\n else:\n self.redirect('/')\n path = 'templates/print.html'\n page = template.render(path, template_values, debug=(True if 'local' in self.request.host_url or users.is_current_user_admin() else False))\n self.response.out.write(page)\n \nclass DeleteResponseHandler(webapp.RequestHandler):\n def get(self):\n google_account = users.get_current_user()\n if google_account:\n user = User.all().filter('google_account', google_account).get()\n if not user:\n self.redirect('/')\n #self.response.out.write(\"Must be logged in to delete response.\")\n return\n args = self.request.arguments()\n response_id = self.request.get('id','')\n try:\n response_id = long(response_id)\n except InputError:\n self.redirect('/')\n #self.response.out.write(\"Bad response id.\")\n return\n r = Response.get(db.Key.from_path('Response', response_id))\n if not r:\n self.redirect('/')\n return\n if not r.user.key().id() == user.key().id():\n self.redirect('/')\n #self.response.out.write(\"Not allowed to delete.\")\n return\n r.delete()\n #self.response.out.write(\"Response deleted.\")\n #return\n self.redirect('/')\n else:\n self.redirect('/')\n\nclass LogoutHandler(webapp.RequestHandler):\n def get(self):\n self.redirect(users.create_logout_url('/'))\n\nclass LoginHandler(webapp.RequestHandler):\n def get(self):\n google_account = users.get_current_user()\n if google_account:\n self.redirect('/')\n else:\n self.redirect(users.create_login_url('/'))\n\nclass DeleteUserHandler(webapp.RequestHandler):\n def get(self):\n google_account = users.get_current_user()\n if google_account:\n user = User.all().filter('google_account', google_account).get()\n if not user:\n self.redirect('/')\n for r in user.response_set:\n r.delete() \n user.delete()\n self.redirect('/')\n else:\n self.redirect('/')\n\ndef main():\n application = webapp.WSGIApplication([('/', HomeHandler), \n ('/logout', LogoutHandler),\n ('/login', LoginHandler),\n ('/contact', ContactHandler),\n ('/print', PrintablePageHandler),\n ('/suggestions', SuggestionsHandler),\n ('/delete_username', DeleteUserHandler),\n ('/delete_admonition', DeleteResponseHandler),\n ('/([0-9a-zA-Z_\\-]+)', UserPageHandler)],\n debug=True)\n util.run_wsgi_app(application)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"EloiseRosen/admonymous","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12431,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"20461210240","text":"import sys,os,re,gzip,io,requests\n\nimport torchtext\nimport math\nimport torch\nfrom torch import nn\nimport argparse\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport tempfile\n\ndef get(vocab,word):\n\t\"\"\" return (vector, index) \"\"\"\n\tif not word in vocab.stoi:\n\t\tword=word.strip()\n\tif not word in vocab.stoi:\n\t\tword=word.lower()\n\tidx=-1 # not found\n\tif word in vocab.stoi:\n\t\tidx=vocab.stoi[word]\n\treturn (vocab.get_vecs_by_tokens(word),idx)\n\ndef tokenize(text: str, lcase=True):\n\ttext=\" \".join(text.split(\"_\"))\n\tif(lcase):\n\t\ttext=text.lower()\n\ttext=re.sub(r\"([.,;:\\\"'()<>|!?\\[\\]{}]+)\",r\" \\1 \",text)\n\ttext=text.strip()\n\treturn text.split()\n\t\ndef induce(src_vocab, dict2src_tgt_weight, outfile=None, lcase=True, corpus_files=[], context_size=50):\n\t\"\"\" src_vocab: trained vocab with source language embeddings\n\t\tdict2src_tgt_weight: key is dict URI or file name, val is a tuple of source column, target column and weight column, weight column may be None (= equally weighted)\n\t\tnote that we restrict source words to those found in the vocab, target side remains unconstrained\n\t\tnote that we add weights, this is useful if the dictionary is actually a TSV file with running translations\n\t\tcorpus_files are TXT or XML files that are used to bootstrap embeddings for unknown words\n\t\tif there are corpus_files, context specifies the aggregation window\n\t\toutfile is the external copy of the embedding file, if this is found, it is just read\n\n\t\tnote that it returns the trained vocab\n\t\"\"\"\n\t# sys.stderr.write(f\"induce({src_vocab},{dict2src_tgt_weight},lcase={lcase},corpus_files={corpus_files}, context_size={context_size})\\n\")\n\t# sys.stderr.flush()\n\t\n\tif outfile==None:\n\t\twith tempfile.NamedTemporaryFile() as outfile:\n\t\t\treturn induce(src_vocab, dict2src_tgt_weight, outfile=outfile.name, lcase=lcase, corpus_files=corpus_files, context_size=context_size)\n\n\tresult=None\n\tif os.path.exists(outfile):\n\t\ttry:\n\t\t\tsys.stderr.write(f\"loading embeddings from {outfile} .. \")\n\t\t\tsys.stderr.flush()\n\t\t\tresult=torchtext.vocab.Vectors(outfile)\n\t\t\tsys.stderr.write(f\"ok ({len(result.stoi)} target language embeddings)\\n\")\n\t\texcept Exception:\n\t\t\tsys.stderr.write(\"failed\\n\")\n\n\tif result!=None:\n\t\treturn result\n\n\tif True:\n\t\tsys.stderr.write(f\"lexical induction from {len(src_vocab.stoi)} source language embeddings\\n\")\n\t\tdict2tgt2src2weight={}\n\t\tfor d,(src_col,tgt_col,weight_col) in dict2src_tgt_weight.items():\n\t\t\t\n\t\t\tsys.stderr.write(f\"\\tloading {d}\\n\")\n\t\t\tsys.stderr.flush()\n\n\t\t\tdict2tgt2src2weight[d]={}\n\t\t\tif os.path.exists(d):\n\t\t\t\tmyopen=open\n\t\t\t\tif d.endswith(\"gz\"):\n\t\t\t\t\tmyopen=gzip.open\n\t\t\t\tinput=myopen(d,\"rt\",errors=\"ignore\")\n\t\t\telif d.endswith(\"gz\"): # URL in gz\n\t\t\t\tinput=gzip.GzipFile(fileobj=io.BytesIO(requests.get(d, stream=True).content))\n\t\t\telse: # url, no gzip\n\t\t\t\tinput=StringIO(requests.get(d, stream=True).content)\n\t\t\tfor line in input:\n\t\t\t\tfields=line.strip().decode(\"utf-8\").split(\"\\t\")\n\t\t\t\t# print(fields)\n\t\t\t\ttry:\n\t\t\t\t\tsrc=\"_\".join(fields[src_col].split())\n\t\t\t\t\ttgt=\"_\".join(fields[tgt_col].split())\n\t\t\t\t\tif not src in src_vocab.stoi:\n\t\t\t\t\t\tsrc=src.lower()\n\t\t\t\t\t# print(src,tgt,len(dict2tgt2src2weight[d]))\n\t\t\t\t\tif lcase:\n\t\t\t\t\t\ttgt=tgt.lower()\n\t\t\t\t\tif src in src_vocab.stoi:\n\t\t\t\t\t\tw=1.0\n\t\t\t\t\t\tif weight_col!=None and len(fields)>weight_col and weight_col>=0:\n\t\t\t\t\t\t\tw=float(fields[weight_col])\n\t\t\t\t\t\tif not d in dict2tgt2src2weight: dict2tgt2src2weight[d]={}\n\t\t\t\t\t\tif not tgt in dict2tgt2src2weight[d]: dict2tgt2src2weight[d][tgt]={}\n\t\t\t\t\t\tif not src in dict2tgt2src2weight[d][tgt]: \n\t\t\t\t\t\t\tdict2tgt2src2weight[d][tgt][src]=w\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdict2tgt2src2weight[d][tgt][src]+=w\n\t\t\t\texcept Exception:\n\t\t\t\t\tpass\n\t\t\tinput.close()\n\t\t\t\n\t\t\t# normalize dict entry weights to sum up to 1\n\t\t\tsys.stderr.write(f\"\\tnormalize {d} weights\\n\")\n\t\t\tsys.stderr.flush()\n\t\t\tfor tgt in dict2tgt2src2weight[d]:\n\t\t\t\tsum_w=sum(dict2tgt2src2weight[d][tgt].values())\n\t\t\t\tfor src,w in dict2tgt2src2weight[d][tgt].items():\n\t\t\t\t\tdict2tgt2src2weight[d][tgt][src]=w/sum_w\n\t\t# print(dict2tgt2src2weight)\n\n\t\ttgt2src2weight={}\n\t\t# average over all dictionaries\n\t\tif len(dict2tgt2src2weight)==1:\n\t\t\ttgt2src2weight=list(dict2tgt2src2weight.values())[0]\n\t\telse:\n\t\t\tfor d in dict2tgt2src2weight:\n\t\t\t\tsys.stderr.write(f\"\\taggregate dict {d}\\n\")\n\t\t\t\tsys.stderr.flush()\n\t\t\t\tfor tgt in dict2tgt2src2weight[d]:\n\t\t\t\t\tif not tgt in tgt2src2weight: tgt2src2weight[tgt]={}\n\t\t\t\t\tfor src,w in dict2tgt2src2weight[d][tgt].items():\n\t\t\t\t\t\tw=w/len(dict2tgt2src2weight)\n\t\t\t\t\t\tif not src in tgt2src2weight[tgt]:\n\t\t\t\t\t\t\ttgt2src2weight[tgt][src]=w\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttgt2src2weight[tgt][src]+=w\n\t\t# print(tgt2src2weight)\n\n\t\tsys.stderr.write(f\"\\tinduce embeddings for {len(tgt2src2weight)} target language words\\n\")\n\t\tsys.stderr.flush()\n\t\ttgt2emb={}\n\t\tfor tgt in tgt2src2weight:\n\t\t\tes=[ w*(get(src_vocab,src)[0]) for src,w in tgt2src2weight[tgt].items() ]\n\t\t\ttgt2emb[tgt]=sum(es) # avg\n\t\t\n\t\t# print(tgt2emb[\"übrig\"])\n\t\t# print(tgt2src2weight[\"übrig\"])\n\t\t# print(get(src_vocab,\"left\"))\n\t\t# sys.exit()\n\n\t\t# bootstrap embeddings for OOV words\n\t\tsys.stderr.write(\"corpus induction (OOV embeddings)\\n\")\n\t\tif len(corpus_files)>0:\n\t\t\tword2contexts={}\n\t\t\tfor file in corpus_files:\n\t\t\t\twith open(file, \"rt\", errors=\"ignore\") as input:\n\t\t\t\t\tsys.stderr.write(f\"\\tfile {file}\\n\")\n\t\t\t\t\tsys.stderr.flush()\n\t\t\t\t\tbuffer=[]\n\t\t\t\t\tfor line in input:\n\t\t\t\t\t\t# print(\"RAW\",line.strip())\n\t\t\t\t\t\tline=re.sub(r\"<[^>]*>\",\"\",line)\n\t\t\t\t\t\tline=line.split(\"<\")[0]\n\t\t\t\t\t\tif \">\" in line:\n\t\t\t\t\t\t\tline=line.split(\">\")[1]\n\t\t\t\t\t\tline=line.strip()\n\t\t\t\t\t\t# print(\"LIN\",line)\n\t\t\t\t\t\tfor tok in tokenize(line,lcase=lcase):\n\t\t\t\t\t\t\tif re.match(r\".*[^.,;:\\\"'()<>|!?\\[\\]{}\\s0-9_].*\",tok): # exclude punctuation and numbers\n\t\t\t\t\t\t\t\tbuffer.append(tok)\n\t\t\t\t\t\t\t\tif len(buffer)>context_size:\n\t\t\t\t\t\t\t\t\tbuffer=buffer[1:]\n\t\t\t\t\t\t\t\tif len(buffer)==context_size:\n\t\t\t\t\t\t\t\t\tword=buffer[int(context_size/2)]\n\t\t\t\t\t\t\t\t\tif not word in tgt2emb:\n\t\t\t\t\t\t\t\t\t\tif word in src_vocab.stoi or word.lower() in src_vocab.stoi:\n\t\t\t\t\t\t\t\t\t\t\ttgt2emb[word]=get(src_vocab,word)[0]\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tif not word in word2contexts:\n\t\t\t\t\t\t\t\t\t\t\t\tword2contexts[word]=[]\n\t\t\t\t\t\t\t\t\t\t\tword2contexts[word].append(buffer)\n\t\t\t\n\t\t\tsys.stderr.write(f\"\\tinduce embeddings for up to {len(word2contexts)} OOV words\\n\")\n\t\t\tsys.stderr.flush()\n\t\t\ttgt2emb_addenda={}\n\t\t\tfor word in word2contexts:\n\t\t\t\tif len(word2contexts[word])>2: # no hapaxes\n\t\t\t\t\tes=[]\n\t\t\t\t\tfor context in word2contexts[word]:\n\t\t\t\t\t\tcontext = [ tgt2emb[t] for t in context if t in tgt2emb ]\n\t\t\t\t\t\tif len(context)>=max(context_size/2,1): # only word with interpretable contexts\n\t\t\t\t\t\t\te=sum(context)/len(context)\n\t\t\t\t\t\t\tes.append(e)\n\t\t\t\t\tif len(es)>2: # no hapaxes\n\t\t\t\t\t\ttgt2emb_addenda[word]=sum(es)/len(es)\n\t\t\t\n\t\t\tsys.stderr.write(f\"\\tadd embeddings for {len(tgt2emb_addenda)} OOV words\\n\")\n\t\t\tsys.stderr.flush()\n\t\t\tfor tgt,emb in tgt2emb_addenda.items():\n\t\t\t\tif not tgt in tgt2emb:\n\t\t\t\t\ttgt2emb[tgt]=emb\n\n\t\twith open(outfile,\"wt\") as tmpfile:\t\t\n\t\t\tsys.stderr.write(f\"store vocab in {outfile}: {len(tgt2emb)} target language words\\n\")\n\t\t\tsys.stderr.flush()\n\t\t\tfor nr,(tgt,e) in enumerate(tgt2emb.items()):\n\t\t\t\tsys.stderr.write(f\"\\r{nr+1} embeddings\")\n\t\t\t\tsys.stderr.flush()\n\t\t\t\ttmpfile.write(tgt+\" \"+\" \".join([str(val) for val in e.tolist()])+\"\\n\")\n\t\t\t\ttmpfile.flush()\n\t\t\tsys.stderr.write(\"\\n\")\n\t\t\tsys.stderr.flush()\n\n\treturn torchtext.vocab.Vectors(outfile)\n\n\nargs=argparse.ArgumentParser(description=\"\"\"\n\t\tlexical inducer, using OPUS and FastText embeddings\n\t\t\"\"\")\nargs.add_argument(\"src\", type=str, help=\"source language, use a BCP47 code\")\nargs.add_argument(\"tgt\", type=str, help=\"target language\")\nargs.add_argument(\"dict_file\", type=str, help=\"basename of the dict file (without path), e.g., {src}-{tgt}.dic.gz for OPUS\")\nargs.add_argument(\"dict_path\", type=str, nargs=\"?\", help=\"directory of dictionary file or URI, defaults to https://object.pouta.csc.fi/OPUS-bible-uedin/v1/dic/, use . for local directory\", default=\"https://object.pouta.csc.fi/OPUS-bible-uedin/v1/dic/\")\nargs.add_argument(\"-s\", \"--src_col\", type=int, nargs=\"?\", help=\"source column in dict, defaults to third col (2, OPUS format)\", default=2)\nargs.add_argument(\"-t\",\"--tgt_col\", type=int, nargs=\"?\", help=\"target column in dict, defaults to fourth col (3, OPUS format)\",default=3)\nargs.add_argument(\"-w\",\"--weight_col\", type=int, nargs=\"?\", help=\"weight column in dict, defaults to None (i.e., equally weighted); note: OPUS format first col (0)\",default=None)\nargs.add_argument(\"-o\",\"--outfile\", type=str, nargs=\"?\", help=\"outfile for vocab, defaults to {tgt}_from_{dict_file}.tsv\", default=None)\nargs.add_argument(\"-d\",\"--debug\", action=\"store_true\", help=\"run on limited vocabulary for debugging purposes\")\nargs.add_argument(\"-c\",\"--corpus_files\", type=str, nargs=\"*\", help=\"corpus files, plain text or XML formats\", default=[])\nargs=args.parse_args()\nif args.outfile==None and not args.debug:\n\targs.outfile=args.tgt+\"_from_\"+args.dict_file+\".tsv\"\n\nprint(args)\n\nif args.debug:\n\tsrc_vocab=torchtext.vocab.FastText(language=args.src,max_vectors=1000000)\nelse:\n\tsrc_vocab=torchtext.vocab.FastText(language=args.src)\ntgt_vocab=induce(src_vocab, {os.path.join(args.dict_path,args.dict_file) : (args.src_col, args.tgt_col, args.weight_col)}, args.outfile, corpus_files=args.corpus_files)\n\nsys.stderr.write(\"explore language term (skip with empty line): \")\nsys.stderr.flush()\nfor line in sys.stdin:\n\tline=line.strip()\n\tif line==\"\":\n\t\tsys.stderr.write(\"bye!\\n\")\n\t\tsys.exit()\n\te=get(tgt_vocab,line)[0]\n\t\n\ttopk=5\n\n\tfor lang,vocab in [ (args.src, src_vocab), (args.tgt, tgt_vocab)]:\n\t\tdist = torch.norm(vocab.vectors - e, dim=1, p=None)\n\t\tknn = dist.topk(topk+1,largest=False)\n\t\tfor dist,i in zip(knn.values,knn.indices):\n\t\t\tprint(f\"{vocab.itos[i]}@{lang} ({dist})\")\n\t\tprint()\n\tsys.stderr.write(\"explore language term (skip with empty line): \")\n\tsys.stderr.flush()\n\n\t","repo_name":"acoli-repo/lex_inducer","sub_path":"induce.py","file_name":"induce.py","file_ext":"py","file_size_in_byte":9772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12497451787","text":"import cv2\r\nimport pickle\r\n\r\nclass ImageProcessing: \r\n def __init__(self, filename, W=547, H=447, C=3) -> None:\r\n self.filename = filename\r\n self.W = W\r\n self.H = H \r\n self.C = C\r\n return\r\n \r\n def readImage(self): \r\n return cv2.imread(self.filename)\r\n \r\n def resize(self, img):\r\n return cv2.resize(img, (self.H, self.W))\r\n \r\n def crop(self, img): \r\n return img[50:int(self.H/3), :int(self.W/4)]\r\n \r\n def grayScale(self, img): \r\n return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n \r\n def threshOld(self, gray):\r\n return cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)\r\n \r\n def findContour(self, thresh): \r\n return cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n \r\n def filterContour(self, contours): \r\n rects = [] \r\n for cnt in contours:\r\n area = cv2.contourArea(cnt)\r\n if area < 1000 or area > 5000:\r\n continue\r\n rect = cv2.boundingRect(cnt)\r\n rects.append(rect)\r\n return rects\r\n \r\n def getCoordinates(self, img, rects): \r\n x, y, w, h = rects[0]\r\n w, y = int(w/2.5), int(h/1.5)\r\n return img[y:y+h, x:x+w]\r\n \r\n def process(self): \r\n image = self.readImage()\r\n image = self.resize(image)\r\n image = self.crop(image)\r\n grayImage = self.grayScale(image)\r\n thresh = self.threshOld(grayImage)\r\n contours, hierarchy = self.findContour(thresh)\r\n rects = self.filterContour(contours)\r\n image = self.getCoordinates(image, rects)\r\n cv2.imshow('output', image)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n return image\r\n\r\nclass OCR: \r\n def __init__(self, fileModel, image) -> None:\r\n self.fileModel = fileModel\r\n self.image = image\r\n return\r\n \r\n def readMark(self):\r\n with open(self.fileModel, 'rb') as f: \r\n reader = pickle.load(f)\r\n result = reader.readtext(self.image)\r\n mark = ' '.join(detect[1] for detect in result)\r\n print(mark)\r\n return mark\r\n \r\n \r\ndef main(): \r\n processing = ImageProcessing('tuluan5 - Copy.jpg')\r\n image = processing.process()\r\n model = OCR('OCR.pkl', image)\r\n model.readMark() \r\n\r\nif __name__ == '__main__': \r\n main()","repo_name":"dinhhieuz/NCKH_2022-2023","sub_path":"qr_service/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27241936275","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 20 09:45:49 2023\r\n\r\n@author: Vviik\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# constants\r\npi = np.pi\r\nr_comet = 1e3 # [m]\r\nv_n = 6e2 # m/s, all ions are born with 600 m/s radial velocity\r\nelectrontemperature = 10 # eV\r\nbeta = 147.8215 # electron to ion energy ratio: kT/(Mv^2)\r\nnu = 1e-6 # ionization frequency [number/s], Vigren2013a (Table 5. 9.2e-7 at solar maximum)\r\n\r\n# normalization, tbd. \r\nu_n = 1\r\nx_comet = 1\r\nx_thickness = 1\r\nDel_t = 0.1 # timestep between ionization bursts, unitless. 1 is time for unaccelerated ions to traverse one shell width.\r\n\r\n#-----------------------------------Creation-----------------------------------\r\n\r\n# 1.1 General parameter choices\r\nnumber_of_boundaries = int(1e2)\r\nx_k = np.arange(x_comet, number_of_boundaries+x_comet, dtype=int) # every equally thick shell has an equal number of ionization events per unit time. Unitless\r\nx_k_i = x_k[:-int(len(x_k)/2)] # shells in which we consider ionization\r\n\r\n# 1.2 defining functions\r\ndef ioncreation(n, final_k): # creates n ions, equally many in each shell, up to shell number final_k\r\n n_per_shell = int(n/(final_k+1)) # this is rounded down. n_per_shell * number_of_boundaries <= n\r\n ilist = np.empty((0, 3)) # empty 0-by-3 matrix\r\n for k in range(final_k+1):\r\n ilist = np.concatenate((ilist, ionshellcreation(n_per_shell, k)), axis=0)\r\n return ilist\r\n\r\ndef ionshellcreation(n, k): # creates n ions uniformly distributed in the k-th shell\r\n ilist = np.empty((n, 3)) # creates an empty n-by-3 matrix \r\n ilist[:, 1] = u_n # 1st column stores velocity\r\n ilist[:, 2] = k # 2nd column stores shell number\r\n \r\n xmin = k+x_comet\r\n x_ion = xmin+np.array([np.random.rand(n)])\r\n x_ion.sort()\r\n x_ion.reshape((n,1)) # make the x_ion array a column vector\r\n ilist[:, 0] = x_ion # 0th column stores position\r\n return ilist\r\n \r\n# 1.3 Randomly generating the ions and electrons\r\n# ions\r\nn_ion = 1e3\r\nionmatrix = ioncreation(n_ion, int(x_k_i[-1])) # Position (sorted) and velocity of all ions.\r\nif n_ion > 1000:\r\n plt.figure()\r\n plt.hist(ionmatrix[:, 0], bins = 100, density = True)\r\n plt.hist(ionmatrix[:, 0], bins = 10, density = True, fill = False)\r\n plt.xlabel('Distance from comet nucleus [km]')\r\n plt.ylabel('Number of ions (pdf normalization)') # Normalization: area of all bins = 1\r\n plt.title('Radial distribution of randomly generated ions')\r\n \r\n# electrons \r\n\r\n# 1.4 Creating the first potential\r\n\r\nQ = 1e25 # [s-1], number of neutrals per second leaving the comet surface\r\nN_R = Q/(4*np.pi*r_comet**2*v_n) # [m-3], neutral density at the comet surface\r\n\r\n# phi(r) = k Te/e * ln(nu_R dt N_R (r/R)**2) # \r\nphi_at_comet = 1e-4 # PLACEHOLDER. CALCULATE\r\n# phi0 = FIX THIS\r\nphi_anders = -phi_at_comet*x_k # numpy array\r\n\r\n#----------------------------------Ion motion----------------------------------\r\n\r\n# 2.1 Function definitions\r\ndef ElectricField(philist): # calculates the unitless electric field\r\n return -(philist[1:]-philist[:-1])/(x_k[1:]-x_k[:-1]) # ElectricField list has one less element than phi. (Number of shells between points = Number of points - 1)\r\n\r\ndef arraytimeevaluator(v0, a, s, s_alt): # Calculates the crossing times for an array of initial velocities, accelerations and the two nearest shell boundary distances \r\n t = np.empty(v0.shape)\r\n s_used = np.empty(s.shape)\r\n \r\n # t = v0/a*(-1+(1+2*a*s/v0**2)**(1/2))\r\n # s_used = s \r\n \r\n taylor_ind = (abs(2*a*s)=-v0**2).nonzero() # find all t that are calculated to be real\r\n t[real_ind] = v0[real_ind]/a[real_ind]*(-1+(1+2*a[real_ind]*s[real_ind]/v0[real_ind]**2)**(1/2))\r\n s_used[real_ind] = s[real_ind]\r\n \r\n # without the if block this causes a problem for some reason\r\n complex_ind = (2*a*s<-v0**2).nonzero() # find all t that are calculated to be complex\r\n if complex_ind[0].size>0:\r\n print('Complex_ind is: ', complex_ind)\r\n t[complex_ind], s_used[complex_ind] = arraytimeevaluator(v0[complex_ind], a[complex_ind], s_alt[complex_ind], s[complex_ind])\r\n \r\n negative_ind = (t<=0).nonzero()\r\n t[negative_ind] = -t[negative_ind]-2*v0[negative_ind]/a[negative_ind]\r\n\r\n return t, s_used\r\n\r\ndef ioncount(imatrix): # counts the number of ions inside each shell number k\r\n ks = imatrix[:,2]\r\n counts = np.empty((number_of_boundaries,), dtype=int)\r\n for k in range(number_of_boundaries):\r\n counts[k] = np.count_nonzero(ks==k)\r\n return counts\r\n \r\ndef ionmotion(imatrix, Delta_t, Elist): # calculates motion for every ion in ionmatrix. Each ion is a row in the n-by-3 ionmatrix [x_ion, u_ion, k_ion]\r\n pos = imatrix[:,0] # position of ions\r\n vs = imatrix[:,1] # velocity of ions\r\n ks = imatrix[:,2].astype(int) # shell number of ions, astype may be unnecessary\r\n \r\n # counts = ioncount(imatrix) # count number of ions in each shell\r\n # a = np.repeat(Elist, counts[:len(Elist)]) # calculate the electric field that each ion experiences (repeating the value of the Elist elements as many times as there are ions in each shell)\r\n # a = a*beta # rescaled motion equation has beta factor infront of (unitless) time\r\n a = np.zeros(ks.shape)\r\n a += Elist[0]*beta # only works NOW\r\n \r\n pos_in_shell = pos%1 # calculates position inside each shell from [0, 1)\r\n s_inner = -pos_in_shell # distance (negative) to inner shell for each ion\r\n s_outer = 1-pos_in_shell # distance (positive) to outer shell for each ion\r\n \r\n # s_main: New array where s has the same direction as the velocity\r\n positive_vs_ind = (vs>0).nonzero()\r\n s_main = s_inner # (Read line below first) rest go to inner s\r\n s_main[positive_vs_ind] = s_outer[positive_vs_ind] # those with positive velocity go to outer s \r\n \r\n # s_alt: New array where s has the opposite direction to the velocity\r\n s_alt = s_outer \r\n s_alt[positive_vs_ind] = s_inner[positive_vs_ind]\r\n \r\n # calculate the crossing times and what shell boundary was crossed\r\n crossing_t, s = arraytimeevaluator(vs, a, s_main, s_alt)\r\n \r\n # check for which indices a crossing happens/does not happen\r\n non_crossing_ind = (crossing_t>=Delta_t).nonzero()\r\n crossing_ind = (crossing_t=number_of_boundaries).nonzero()\r\n ks[OBC_ind] = number_of_boundaries-1 # The outermost shell has infinite extent for now. Largest shell number allowed is number_of_boundaries-1\r\n \r\n # create a new matrix of ions\r\n imatrixnew = np.array(list(zip(pos, vs, ks))) # recombine position, velocity and shell number \r\n \r\n # ions which crossed have to be calculated again recursively\r\n if crossing_ind[0].size>0:\r\n print(\"Non crossing ind is: \", non_crossing_ind)\r\n print(\"Crossing ind is: \", crossing_ind)\r\n print(\"Remaining time - Crossing time is\", Delta_t[crossing_ind]-crossing_t[crossing_ind])\r\n print(\"imatrixnew[crossing_ind] = \", imatrixnew[crossing_ind])\r\n imatrixnew[crossing_ind] = ionmotion(imatrixnew[crossing_ind], Delta_t[crossing_ind]-crossing_t[crossing_ind], Elist)\r\n \r\n return imatrixnew \r\n\r\ndef iondensity(i_per_shell):\r\n i_numberdensity = 1/(4*pi*(r_comet*x_k[1:])**2)*(i_per_shell[1:]+i_per_shell[:-1])/(2*x_comet*r_comet)\r\n return i_numberdensity\r\n\r\n# 2.4 Anders Loop. Supplementary, move to last. \r\nnumber_of_loops = int(len(x_k_i)/Del_t)\r\ncounter = 0\r\nandersfield = ElectricField(phi_anders)\r\nfor j in range(number_of_loops):\r\n remaining_time = np.repeat(Del_t, ionmatrix[:,0].shape) # create a remaining time matrix for prior ions\r\n source_ions = ioncreation(n_ion, int(x_k_i[-1])) # birth new ions\r\n source_remaining_time = np.random.uniform(0, Del_t, source_ions[:,0].shape) # add a uniform random time [0, Del_t) remaining for the newly born ions (Reflects the fact that the ions can be born any time during the time step)\r\n \r\n # concatenate prior ions and recently born ions\r\n ionmatrix = np.concatenate((ionmatrix, source_ions)) # add new ions to ion matrix\r\n remaining_time = np.concatenate((remaining_time, source_remaining_time))\r\n \r\n ionmatrix = ionmotion(ionmatrix, remaining_time, andersfield)\r\n ionmatrix = ionmatrix[ionmatrix[:,2].argsort()] # sort after column\r\n counter+=1 # increment the number of loops performed\r\n \r\n icount = ioncount(ionmatrix)\r\n plt.figure()\r\n plt.plot(icount[:-1], '.', color='k')\r\n plt.title('Number of ions inside each shell')\r\n plt.xlabel('Shell number '+r'$k$')\r\n plt.ylabel('Number of ions')\r\n \r\n # idensity = iondensity(ioncount(ionmatrix))\r\n # plt.figure()\r\n # plt.plot(idensity[:-1], '.', color='k')\r\n # plt.title('Number density of ions')\r\n # plt.xlabel('Shell number '+r'$k$')\r\n # plt.ylabel('Number density [m'+'$^{-3}$]')\r\n\r\n # plt.plot(idensity[:-1]*x_k[1:-1]**2/(x_k[1:-1]-1), '.', color='k')","repo_name":"Falondil/cometproj","sub_path":"npPeanoSolver2.py","file_name":"npPeanoSolver2.py","file_ext":"py","file_size_in_byte":10119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7882832018","text":"import sys, time\n\nfrom .celltrackerfactory \timport CellTrackerFactory\nfrom . \t\t\t\t\t\timport os, np, pd, pdist2, matchpairs, Cell\nfrom scipy \t\t\t\t\timport interpolate\nfrom skimage.measure \t\timport regionprops\n\nclass CellTracker(CellTrackerFactory):\n\tcolumns = [\"xcoords\", \"ycoords\", \"bbox\"]\n\tMAX_VALUE = np.finfo(np.float64).max\n\n\tdef __init__(self, root, load_dir, img_shape = None, mitosis_filename = None, **kwargs):\n\t\tsuper().__init__(**kwargs)\n\t\t\n\t\tself.root = root\n\t\tself.load_dir = load_dir\n\t\t\n\t\tself.limits = kwargs.get(\"limits\")\n\t\tif self.limits is None:\n\t\t\tself.limits = []\n\t\t\t\n\t\tself.dtf_mitosis = pd.DataFrame()\n\t\twhile True:\n\t\t\tif mitosis_filename is None:\n\t\t\t\tbreak\n\n\t\t\tprint(f'Loading mitosis from {mitosis_filename}')\n\t\t\tif mitosis_filename.endswith('pkl'):\n\t\t\t\tself.dtf_mitosis = pd.read_pickle(os.path.join(self.root, mitosis_filename))\n\t\t\tif mitosis_filename.endswith('csv'):\n\t\t\t\tself.dtf_mitosis = pd.read_csv(os.path.join(self.root, mitosis_filename))\n\n\t\t\tif self.dtf_mitosis.shape[0] == 0:\n\t\t\t\tbreak\n\n\t\t\tself.dtf_mitosis[\"lineage_label\"] = None\n\t\t\tself.dtf_mitosis[\"track_label\"] = None\n\t\t\tself.dtf_mitosis[\"daughters_found\"] = False\n\t\t\tself.mit_cutoff = 8 * 8\n\n\t\t\tif len(self.limits) > 0:\n\t\t\t\tself.dtf_mitosis = self.dtf_mitosis.loc[\n\t\t\t\t\t\t\t\t\t\t\t\t\t(self.dtf_mitosis[\"xm\"] > self.limits[0]) & \n\t\t\t\t\t\t\t\t\t\t\t\t\t(self.dtf_mitosis[\"xm\"] < self.limits[2]) &\n\t\t\t\t\t\t\t\t\t\t\t\t\t(self.dtf_mitosis[\"ym\"] > self.limits[1]) &\n\t\t\t\t\t\t\t\t\t\t\t\t\t(self.dtf_mitosis[\"ym\"] < self.limits[3])\n\t\t\t\t\t\t\t\t\t\t\t\t ]\n\t\t\tbreak\n\n\t\tif img_shape is not None:\n\t\t\tself.shape = img_shape\n\n\t# initialize the first frame\n\tdef _init(self, frame):\n\n\t\tdf = pd.read_pickle(os.path.join(self.load_dir, f'cells-{frame:04}.pkl'))\n\n\t\tdf[\"track_label\"] = np.arange(df.shape[0], dtype = 'int')\n\t\tdf[\"lineage_label\"] = np.arange(df.shape[0], dtype = 'int')\n\t\tdf[\"new_cell\"] = True\n\t\tdf[\"track_length\"] = 0\n\t\tself.max_label = df.shape[0] \n\t\t\n\t\treturn df\n\t\n\t# MITOSIS MATCH PAIRING IS RIGHT HERE\n\tdef _mitosis(self, xy0, xy1, frame, **kwargs):\n\t\tif self.dtf_mitosis.shape[0] == 0:\n\t\t\treturn None\n\n\t\tself.mit = self.dtf_mitosis[(self.dtf_mitosis[\"frame\"] <= frame)]\n\t\tself.mit = self.mit[self.mit[\"track_label\"].isnull() | \n\t\t\t\t\t\t\t\t (self.mit[\"daughters_found\"] == False)]\n\t\t\n\t\t# Frame check -> If I cannot find the mitosis, then I will never find it. \n\t\tself.mit = self.mit[self.mit[\"frame\"] > frame - self.mitosis_time_cutoff]\n\t\tif self.mit.shape[0] == 0:\n\t\t\treturn None\n\t\t\n\t\tif len(self.limits) > 0:\n\t\t\txym = np.array([[r[\"xm\"]-self.limits[0], r[\"ym\"]-self.limits[1]] for index, r in self.mit.iterrows()])\n\t\telse:\n\t\t\txym = np.array([[r[\"xm\"], r[\"ym\"]] for index, r in self.mit.iterrows()])\n\t\t\t\n\t\tdsq = pdist2(xy0, xym)\n\t\tdsq_min = np.min(dsq, axis = 0)\n\t\t\n\t\tid0m = np.zeros(dsq_min.shape)\n\t\tfor ii in range(len(id0m)):\n\t\t\tid0m[ii] = self.id0[dsq[:, ii] == dsq_min[ii]]\n\n\t\tmothers_to_keep = dsq_min <= self.mit_cutoff\n\t\tmothers_to_keep = mothers_to_keep * (self.mit[\"track_label\"].isnull().values) > 0\n\t\t\n\t\t# Update the mitosis dataframe with the true mothers\n\t\ttrue_mothers = id0m[mothers_to_keep]\n\t\t\n\t\tself.mit.loc[mothers_to_keep, \"lineage_label\"] \t\t\t\t\t\t= self.dtf0.loc[true_mothers, \"lineage_label\"].values\n\t\tself.dtf_mitosis.loc[self.mit.loc[mothers_to_keep].index, \"lineage_label\"] \t= self.dtf0.loc[true_mothers, \"lineage_label\"].values\n\t\tself.mit.loc[mothers_to_keep, \"track_label\"] \t\t\t\t\t\t= self.dtf0.loc[true_mothers, \"track_label\"].values\n\t\tself.dtf_mitosis.loc[self.mit.loc[mothers_to_keep].index, \"track_label\"] \t= self.dtf0.loc[true_mothers, \"track_label\"].values\n\t\t\n\t\t# Daughter one\n\t\tif len(self.limits) > 0:\n\t\t\txyd1 = np.array([[r[\"xd1\"]-self.limits[0], r[\"yd1\"]-self.limits[1]] for index, r in self.mit.iterrows()])\n\t\telse:\n\t\t\txyd1 = np.array([[r[\"xd1\"], r[\"yd1\"]] for index, r in self.mit.iterrows()])\n\t\t\n\t\tdsq = pdist2(xy1, xyd1)\n\t\tdsq_min = np.min(dsq, axis = 0) \n\t\tid1d1 = np.zeros(dsq_min.shape)\n\t\tfor ii in range(len(id1d1)):\n\t\t\tid1d1[ii] = self.id1[dsq[:, ii] == dsq_min[ii]]\n\t\t\n\t\tdaughters_to_keep = dsq_min <= self.mit_cutoff\n\t\t\n\t\t# Daughter two\n\t\tif len(self.limits) > 0:\n\t\t\txyd2 = np.array([[r[\"xd2\"]-self.limits[0], r[\"yd2\"]-self.limits[1]] for index, r in self.mit.iterrows()])\n\t\telse:\n\t\t\txyd2 = np.array([[r[\"xd2\"], r[\"yd2\"]] for index, r in self.mit.iterrows()])\n\t\t\t\n\t\tdsq = pdist2(xy1, xyd2)\n\t\tdsq_min = np.min(dsq, axis = 0)\n\t\tid1d2 = np.zeros(dsq_min.shape)\n\t\tfor ii in range(len(id1d2)):\n\t\t\tid1d2[ii] = self.id1[dsq[:, ii] == dsq_min[ii]]\n\t\t\n\t\tdaughters_to_keep = daughters_to_keep * (dsq_min <= self.mit_cutoff) > 0\n\t\t\n\t\tdfd1 = self.dtf1.loc[id1d1]\n\t\tdfd2 = self.dtf1.loc[id1d2]\n\t\t\n\t\t# Check if they map to the same daughter\n\t\tdaughters_to_keep = daughters_to_keep * (dfd1.index != dfd2.index)\n\t\tdaughters_to_keep = daughters_to_keep * (self.mit[\"lineage_label\"].isnull().values == False) > 0\n\t\tid1d1 = id1d1[daughters_to_keep]\n\t\tid1d2 = id1d2[daughters_to_keep]\n\t\tif len(id1d1) == 0:\n\t\t\treturn None\n\t\t\n\t\tself.dtf_mitosis.loc[self.mit.loc[daughters_to_keep].index, \"daughters_found\"] = True\n\t\tself.mit.loc[daughters_to_keep, \"daughters_found\"] = True\n\t\tself.dtf1.loc[id1d1, \"lineage_label\"] = self.mit.loc[daughters_to_keep, \"lineage_label\"].values\n\t\tself.dtf1.loc[id1d2, \"lineage_label\"] = self.mit.loc[daughters_to_keep, \"lineage_label\"].values\n\t\t\n\t\tself.dtf1.loc[id1d1, \"track_label\"] \t= self.max_label + np.arange(np.sum(daughters_to_keep), dtype = 'int')\n\t\tself.max_label \t\t\t\t\t\t\t= self.max_label + np.sum(daughters_to_keep)\n\t\tself.dtf1.loc[id1d2, \"track_label\"] \t= self.max_label + np.arange(np.sum(daughters_to_keep), dtype = 'int')\n\t\tself.max_label \t\t\t\t\t\t\t= self.max_label + np.sum(daughters_to_keep)\n\t\t\n\t\tself.dtf0.loc[np.in1d(self.dtf0[\"track_label\"].values, self.mit.loc[daughters_to_keep, \"track_label\"].values), \"mitosis\"] = True\n\t\tself.dtf1.loc[id1d1, \"mitosis\"] \t\t= True\n\t\tself.dtf1.loc[id1d2, \"mitosis\"] \t\t= True\n\t\tself.dtf1.loc[id1d1, \"mother_label\"] \t= self.mit.loc[daughters_to_keep, \"track_label\"].values\n\t\tself.dtf1.loc[id1d2, \"mother_label\"] \t= self.mit.loc[daughters_to_keep, \"track_label\"].values\n\t\treturn None\n\t\n\tdef _run(self, t0 = 0, tf = 0, save_path = None, dt = 1, frames = None):\n\t\tcolumns = CellTracker.columns\n\t\tif frames is None:\n\t\t\tframes = range(t0, tf+1, dt)\n\n\t\tself.dt = dt\n\t\tif not os.path.isfile(os.path.join(self.load_dir, f'cells-{frames[-1]+dt:04}.pkl')):\n\t\t\tframes = frames[0:-1]\n\t\t\twhile True:\n\t\t\t\tif not os.path.isfile(os.path.join(self.load_dir, f'cells-{frames[-1]+dt:04}.pkl')):\n\t\t\t\t\tframes = frames[0:-1]\n\t\t\t\t\tcontinue\n\t\t\t\tbreak\n\n\t\twith open(save_path.replace('csv', 'txt'), 'w') as log_file:\n\t\t\tlog_file.write(save_path)\n\t\t\tlog_file.write('\\n')\n\n\t\tfor frame in frames:\n\t\t\twith open(save_path.replace('csv', 'txt'), 'a') as log_file:\n\t\t\t\ttime0 = time.time()\n\t\t\t\tif frame == t0:\n\t\t\t\t\tself.dtf0 = self._init(frame)\n\t\t\t\t\tself.dtf0.drop(columns = columns).to_csv(save_path, index = False)\n\t\t\t\t\tcolumns = [column for column in columns if column in self.dtf0]\n\t\t\t\t\tlog_file.write(\"Initializing\\n\")\n\t\t\t\t\tlog_file.write(f'dropping these columns: {columns}\\n')\n\t\t\t\t# Load frame 1 regionprops\n\n\t\t\t\tself.dtf1 = pd.read_pickle(os.path.join(self.load_dir, f'cells-{frame+dt:04}.pkl'))\n\t\t\t\tself.dtf1[\"track_length\"] = 0\n\t\t\t\tself.dtf1[\"new_cell\"] = None\n\n\t\t\t\twhile True:\n\t\t\t\t\t# Index of the dataframe\n\t\t\t\t\tself.id0 = self.dtf0.index.values\n\t\t\t\t\tself.id1 = self.dtf1.index.values\n\t\t\t\t\t\n\t\t\t\t\txy0 = self._centroid(self.dtf0)\n\t\t\t\t\txy1 = self._centroid(self.dtf1)\n\t\t\t\t\t\n\t\t\t\t\tmit = self._mitosis(xy0, xy1, frame = frame)\n\t\t\t\t\t\n\t\t\t\t\tself.id0 = self.id0[self.dtf0[\"mitosis\"] == False]\n\t\t\t\t\tself.id1 = self.id1[self.dtf1[\"mitosis\"] == False]\n\t\t\t\t\t\n\t\t\t\t\txy0 = xy0[self.dtf0[\"mitosis\"] == False, :]\n\t\t\t\t\txy1 = xy1[self.dtf1[\"mitosis\"] == False, :]\n\n\t\t\t\t\tif mit == 0:\n\t\t\t\t\t\treturn\n\t\t\t\t\t\n\t\t\t\t\tdsq = pdist2(xy0, xy1)\n\t\t\t\t\tdsq[dsq > self.max_disp * self.max_disp] = self.MAX_VALUE\n\t\t\t\t\tidx = dsq < self.MAX_VALUE\n\t\t\t\t\t\n\t\t\t\t\tid0 \t\t\t= np.arange(idx.shape[0], dtype = 'int')\n\t\t\t\t\tid1 \t\t\t= np.arange(idx.shape[1], dtype = 'int')\n\t\t\t\t\tdeg0 = np.sum(idx, axis = 1)\n\t\t\t\t\tself.overlaps = np.zeros(dsq.shape)\n\t\t\t\t\tfor ii in id0[deg0 > 0]:\n\t\t\t\t\t\tplist0 = self._pixellist(self.dtf0.loc[self.id0[ii], \"xcoords\"], self.dtf0.loc[self.id0[ii], \"ycoords\"])\n\t\t\t\t\t\tfor jj in id1[idx[ii, :]]:\n\t\t\t\t\t\t\tplist1 = self._pixellist(self.dtf1.loc[self.id1[jj], \"xcoords\"], self.dtf1.loc[self.id1[jj], \"ycoords\"])\n\t\t\t\t\t\t\tself.overlaps[ii, jj] = np.sum(np.in1d(plist0, plist1)) / len(plist0)\n\t\t\t\n\t\t\t\n\t\t\t\t\tdsq[self.overlaps < self.min_overlap] = self.MAX_VALUE\n\t\t\t\t\tidx[self.overlaps < self.min_overlap] = 0\n\t\t\t\t\t\n\t\t\t\t\tcost = dsq.copy()\n\t\t\t\t\tcost[cost < self.MAX_VALUE] = 1.0 * cost[cost < self.MAX_VALUE] / np.square(self.max_disp)\n\t\t\t\t\tcost[cost < self.MAX_VALUE] = cost[cost < self.MAX_VALUE] + 0.4 * (1 - self.overlaps[cost < self.MAX_VALUE])\n\n\t\t\t\t\t\n\t\t\t\t\t# pair together the objects\n\t\t\t\t\tself.M, self.uR, self.uC = matchpairs(cost)\n\n\t\t\t\t\tif self.M is None:\n\t\t\t\t\t\tself.uR = np.arange(xy0.shape[0], dtype = 'int')\n\t\t\t\t\t\tself.uC = np.arange(xy1.shape[0], dtype = 'int')\n\t\t\t\t\t\tself.M = None\n\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\tlog_file.write(f'{self.M.shape[0]} matches, {self.uR.shape[0]} unmapped rows, {self.uC.shape[0]} unmapped columns\\n')\n\t\t\t\t\texcept AttributeError:\n\t\t\t\t\t\tpass\n\t\t\t\t\t# After check unmapped columns -> make a new dataframe based on the iamge ...\n\t\t\t\t\tif self.M is not None:\n\t\t\t\t\t\tur = self._check_unmatched_rows(frame = frame)\n\t\t\t\t\t\tif ur == 0:\n\t\t\t\t\t\t\treturn\n\n\t\t\t\t\tif self.M is not None:\n\t\t\t\t\t\tself.dtf1.loc[self.id1[self.M[:, 1]], \"track_label\"] = self.dtf0.loc[self.id0[self.M[:, 0]], \"track_label\"].values\n\t\t\t\t\t\tself.dtf1.loc[self.id1[self.M[:, 1]], \"lineage_label\"] = self.dtf0.loc[self.id0[self.M[:, 0]], \"lineage_label\"].values\n\t\t\t\t\t\tself.dtf1.loc[self.id1[self.M[:, 1]], \"track_length\"] = self.dtf0.loc[self.id0[self.M[:, 0]], \"track_length\"].values + dt\n\t\t\t\t\t\t\n\n\t\t\t\t\tself.dtf1.loc[self.id1[self.uC], \"new_cell\"] = True\n\t\t\t\t\tself.dtf1.loc[self.id1[self.uC], \"track_label\"] = self.max_label + np.arange(self.uC.shape[0], dtype = 'int')\n\t\t\t\t\tself.dtf1.loc[self.id1[self.uC], \"lineage_label\"] = self.max_label + np.arange(self.uC.shape[0], dtype = 'int')\n\t\t\t\t\tself.max_label = self.max_label + self.uC.shape[0]\n\t\t\t\t\t\n\t\t\t\t\t\n\n\t\t\t\t\tfor ii in self.uR:\n\t\t\t\t\t\tlabel = self.dtf0.loc[self.id0[ii], \"track_label\"]\n\t\t\t\t\t\tlength = self.dtf0.loc[self.id0[ii], \"track_length\"]\n\t\t\t\t\t\tif (length < 5) and (self.dtf0.loc[self.id0[ii], \"lineage_label\"] == label):\n\t\t\t\t\t\t\tself.uR[self.uR == ii] = -1\n\t\t\t\t\t\n\t\t\t\t\tself.uR = self.uR[self.uR >= 0]\n\t\t\t\t\t\n\t\t\t\t\tself.dtf0.loc[self.id0[self.uR], \"mem\"] = self.dtf0.loc[self.id0[self.uR], \"mem\"] + dt\n\t\t\t\t\tself.uR = self.uR[(self.dtf0.loc[self.id0[self.uR], \"mem\"] <= self.mem)]\n\t\t\t\t\t\n\t\t\t\t\tself.dtf0.loc[self.id0[self.uR], \"frame\"] = frame + dt\n\t\t\t\t\tself.dtf1 = pd.concat([self.dtf1, self.dtf0.loc[self.id0[self.uR]]], ignore_index = True)\n\t\t\t\t\t\n\t\t\t\t\tself.dtf1 = self.dtf1[self.dtf1[\"track_label\"].isnull() == False]\n\t\t\t\t\tself.dtf1.loc[self.dtf1[\"mitosis\"] == True, \"mitosis\"] = False\n\t\t\t\t\t\n\t\t\t\t\tbreak\n\n\n\t\t\t\tself.dtf1.drop(columns = columns).to_csv(save_path, mode = \"a\", index = False, header = False)\n\t\t\t\tself.dtf0 = self.dtf1\n\t\t\t\ttf = time.time()\n\t\t\t\tlog_file.write(f\"Frame {frame:04}, {time.time()-time0} seconds\\n\")\n\n\t# Check unmatched rows ...\n\tdef _check_unmatched_rows(self, frame):\n\t\tfor ii in self.uR:\n\t\t\tif ii < 0:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tdtf_ii = self.dtf0.loc[self.id0[ii]]\n\t\t\t\n\t\t\toverlaps_ii = self.overlaps[ii, :]\n\t\t\tif not np.any(overlaps_ii > self.min_overlap):\n\t\t\t\tcontinue\n\t\t\t\n\t\t\t# Get the potential indices\n\t\t\tmax_overlap = np.max(overlaps_ii)\n\t\t\tmerged_t1_idx = np.where(overlaps_ii == max_overlap)[0][0]\n\t\t\tdtf1_merged = self.dtf1.loc[self.id1[merged_t1_idx]]\n\t\t\t\n\t\t\t# Get the idx of any overlapping object ...\n\t\t\toverlaps_t1 = self.overlaps[:, merged_t1_idx]\n\t\t\toverlaps_idx = overlaps_t1 > self.min_overlap\n\t\t\t\n\t\t\t# All the merged objects\n\t\t\tmerged_t0_all = np.where(overlaps_idx)[0]\n\t\t\tmerged_t0_all = merged_t0_all[merged_t0_all != ii]\n\t\t\t\n\t\t\t# Get the idx of pre-merged object\n\t\t\tdtf0_merged = self.dtf0.loc[self.id0[merged_t0_all]]\n\t\t\t\n\t\t\t# Alternating mem objects\n\t\t\tif dtf0_merged.shape[0] == 1:\n\t\t\t\toverlap = self._overlap(dtf_ii, dtf0_merged.iloc[0])\n\t\t\t\tif overlap > 0.7: # BENSON - this is arbitrary\n\t\t\t\t\tmem_ii = dtf_ii[\"mem\"]\n\t\t\t\t\tmem_merged = dtf0_merged.iloc[0][\"mem\"]\n\t\t\t\t\tif dtf_ii[\"track_label\"] == dtf_ii[\"lineage_label\"]:\n\t\t\t\t\t\tif dtf0_merged.iloc[0][\"track_label\"] == dtf0_merged.iloc[0][\"lineage_label\"]:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t# This is the mapped object ...\n\t\t\t\t\t\t\tif mem_merged > 0:\n\t\t\t\t\t\t\t\tself.uR[self.uR == ii] = -1\n\t\t\t\t\t\t\t\tself.M[self.M[:, 0] == merged_t0_all, 0] = ii\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t# This is the unmapped row ...\n\t\t\t\t\t\t\tif mem_ii > 0:\n\t\t\t\t\t\t\t\tself.uR[self.uR == ii] = -1\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\n\t\t\t# Conditions for preventing the alternating mergers ... \n\t\t\tif dtf0_merged.shape[0] == 1:\n\t\t\t\tif max_overlap > 0.4: \n\t\t\t\t\tlength = dtf0_merged[\"track_length\"].values[0]\n\t\t\t\t\tlength_uR = dtf_ii[\"track_length\"]\n\t\t\t\t\tif dtf0_merged[\"track_label\"].values[0] == dtf0_merged[\"lineage_label\"].values[0]:\n\t\t\t\t\t\tif length_uR > length:\n\t\t\t\t\t\t\tself.uR[self.uR == ii] = -1\n\t\t\t\t\t\t\tself.M[self.M[:, 0] == merged_t0_all, 0] = ii\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t# Check how long the track is for dtf0_merged\n\t\t\t\t\n\t\t\t# Only check these if the max_overlap is not that significant?\n\t\t\tpii = dtf_ii[\"perimeter\"]\n\t\t\tp0 = dtf0_merged[\"perimeter\"].values\n\t\t\tp1 = dtf1_merged[\"perimeter\"]\n\t\t\tif p1 / (pii + np.sum(p0)) < 0.7:\n\t\t\t\tcontinue\n\n\t\t\taii = dtf_ii[\"area\"]\n\t\t\ta0 = dtf0_merged[\"area\"].values\n\t\t\ta1 = dtf1_merged[\"area\"]\n\t\t\tif a1 / (aii + np.sum(a0)) < 0.7:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tbbox_merged = dtf1_merged.bbox\n\t\t\t# --------------------------------------------------------------------\n\t\t\t# --------------------------------------------------------------------\n\t\t\t# Create a new image with the \"label\" being the idx of M[:, 0], uR\n\t\t\t# --------------------------------------------------------------------\n\t\t\t# --------------------------------------------------------------------\n\t\t\ttmp = np.zeros((bbox_merged[2] - bbox_merged[0], \n\t\t\t\t\t\t\tbbox_merged[3] - bbox_merged[1]), dtype = np.uint16);\n\t\t\t\n\t\t\tx = self._centroid_cropped(dtf_ii, bbox_merged[0], tmp.shape, dim = 0)\n\t\t\ty = self._centroid_cropped(dtf_ii, bbox_merged[1], tmp.shape, dim = 1)\n\t\t\ttmp[x, y] = ii\n\t\t\tfor cntr, (index, row) in enumerate(dtf0_merged.iterrows()):\n\t\t\t\tx = self._centroid_cropped(row, bbox_merged[0], tmp.shape, dim = 0)\n\t\t\t\ty = self._centroid_cropped(row, bbox_merged[1], tmp.shape, dim = 1)\n\t\t\t\ttmp[x, y] = merged_t0_all[cntr]\n\t\t\t\n\t\t\ttmp_merged = np.zeros(tmp.shape, dtype = np.uint8)\n\t\t\ttmp_merged[self._coords(dtf1_merged, bbox_merged[0], tmp.shape, dim = 0),\n\t\t\t\t\t self._coords(dtf1_merged, bbox_merged[1], tmp.shape, dim = 1)] = 1\n\t\t\t\n\t\t\txy = np.where(tmp > 0)\n\t\t\tinterp = interpolate.NearestNDInterpolator(np.transpose(xy), tmp[xy])\n\t\t\tB = interp(*np.indices(tmp.shape))\n\t\t\tB[tmp_merged == 0] = 0\n\t\t\t\t\n\t\t\treg = regionprops(B)\n\t\t\treg = [r for r in reg if r.area > self.min_area]\n\n\t\t\t# Create the new dataframe\n\t\t\tif len(reg) <= 1:\n\t\t\t\tself.uR[self.uR == ii] = -1\n\t\t\t\tcontinue\n\t\t\t\n\n\t\t\tdtf_unmerged = pd.DataFrame([Cell.from_regionprops(r, bbox = bbox_merged, frame = frame + self.dt) for r in reg])\n\t\t\t\n\t\t\t# Set the mean gfp properly\n\t\t\tdtf_unmerged[\"mean_gfp\"] = dtf1_merged[\"mean_gfp\"]\n\n\t\t\t# --------------------------------------------------------------------\n\t\t\t# dtf1_merged.name is the index of the first object\n\t\t\tindex = dtf1_merged.name\n\t\t\tmax_index = np.max(self.dtf1.index)\n\t\t\tdtf_unmerged.rename(index = {ii: max_index + ii for ii in dtf_unmerged.index[1:]}, inplace = True)\n\t\t\tdtf_unmerged.rename(index = {0:index}, inplace = True)\n\t\t\tdtf_unmerged[\"merged\"] = True\n\t\t\t\n\t\t\ttry:\n\t\t\t\tself.dtf1.loc[index] = dtf_unmerged.loc[index]\n\t\t\texcept KeyError as err:\n\t\t\t\tdisplay(len(reg))\n\t\t\t\tdisplay(index)\n\t\t\t\tdisplay(dtf_unmerged)\n\t\t\t\traise KeyError\n\t\t\t\n\t\t\tself.dtf1 = pd.concat([self.dtf1, dtf_unmerged.iloc[1:]])\n\t\t\tself.id1 = np.append(self.id1, dtf_unmerged.index[1:])\n\t\t\t\n\t\t\tnew_pairs = np.zeros((dtf_unmerged.shape[0], 2), dtype = 'int')\n\t\t\tfor cntr, (index, row) in enumerate(dtf_unmerged.iterrows()):\n\t\t\t\tnew_pairs[cntr, 0] = row[\"label\"]\n\t\t\t\tnew_pairs[cntr, 1] = np.where(self.id1 == index)[0][0]\n\t\t\t\n\t\t\tself.M[np.in1d(self.M[:, 0], merged_t0_all), :] = -1\n\t\t\tself.M = np.append(self.M, new_pairs, axis = 0)\n\t\t\tself.uR[np.in1d(self.uR, merged_t0_all)] = -1\n\t\t\tself.uR[self.uR == ii] = -1\n\t\t\n\t\tself.M = self.M[self.M[:, 0] >= 0, :]\n\t\tself.uR = self.uR[self.uR >= 0]\n\t\treturn None\n","repo_name":"usnistgov/WSDOM","sub_path":"src/cell_tracker/tracker/celltracker.py","file_name":"celltracker.py","file_ext":"py","file_size_in_byte":16836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"25619126437","text":"\"\"\"Layout for inline-level boxes.\"\"\"\n\nimport unicodedata\nfrom math import inf\n\nfrom ..css import computed_from_cascaded\nfrom ..css.computed_values import character_ratio, strut_layout\nfrom ..formatting_structure import boxes, build\nfrom ..text.line_break import can_break_text, create_layout, split_first_line\nfrom .absolute import AbsolutePlaceholder, absolute_layout\nfrom .flex import flex_layout\nfrom .float import avoid_collisions, float_layout\nfrom .leader import handle_leader\nfrom .min_max import handle_min_max_width\nfrom .percent import resolve_one_percentage, resolve_percentages\nfrom .preferred import (\n inline_min_content_width, shrink_to_fit, trailing_whitespace_size)\nfrom .replaced import inline_replaced_box_layout\nfrom .table import find_in_flow_baseline, table_wrapper_width\n\n\ndef iter_line_boxes(context, box, position_y, bottom_space, skip_stack,\n containing_block, absolute_boxes, fixed_boxes,\n first_letter_style):\n \"\"\"Return an iterator of ``(line, resume_at)``.\n\n ``line`` is a laid-out LineBox with as much content as possible that\n fits in the available width.\n\n \"\"\"\n resolve_percentages(box, containing_block)\n if skip_stack is None:\n # TODO: wrong, see https://github.com/Kozea/WeasyPrint/issues/679\n resolve_one_percentage(box, 'text_indent', containing_block.width)\n else:\n box.text_indent = 0\n while True:\n line, resume_at = get_next_linebox(\n context, box, position_y, bottom_space, skip_stack,\n containing_block, absolute_boxes, fixed_boxes, first_letter_style)\n if line:\n handle_leader(context, line, containing_block)\n position_y = line.position_y + line.height\n if line is None:\n return\n yield line, resume_at\n if resume_at is None:\n return\n skip_stack = resume_at\n box.text_indent = 0\n first_letter_style = None\n\n\ndef get_next_linebox(context, linebox, position_y, bottom_space, skip_stack,\n containing_block, absolute_boxes, fixed_boxes,\n first_letter_style):\n \"\"\"Return ``(line, resume_at)``.\"\"\"\n skip_stack = skip_first_whitespace(linebox, skip_stack)\n if skip_stack == 'continue':\n return None, None\n\n skip_stack = first_letter_to_box(linebox, skip_stack, first_letter_style)\n\n linebox.position_y = position_y\n\n if context.excluded_shapes:\n # Width and height must be calculated to avoid floats\n linebox.width = inline_min_content_width(\n context, linebox, skip_stack=skip_stack, first_line=True)\n linebox.height, _ = strut_layout(linebox.style, context)\n else:\n # No float, width and height will be set by the lines\n linebox.width = linebox.height = 0\n position_x, position_y, available_width = avoid_collisions(\n context, linebox, containing_block, outer=False)\n\n candidate_height = linebox.height\n\n excluded_shapes = context.excluded_shapes.copy()\n\n while True:\n original_position_x = linebox.position_x = position_x\n original_position_y = linebox.position_y = position_y\n original_width = linebox.width\n max_x = position_x + available_width\n position_x += linebox.text_indent\n\n line_placeholders = []\n line_absolutes = []\n line_fixed = []\n waiting_floats = []\n line_children = []\n\n (line, resume_at, preserved_line_break, first_letter,\n last_letter, float_width) = split_inline_box(\n context, linebox, position_x, max_x, bottom_space, skip_stack,\n containing_block, line_absolutes, line_fixed, line_placeholders,\n waiting_floats, line_children)\n linebox.width, linebox.height = line.width, line.height\n\n if is_phantom_linebox(line) and not preserved_line_break:\n line.height = 0\n break\n\n remove_last_whitespace(context, line)\n\n new_position_x, _, new_available_width = avoid_collisions(\n context, linebox, containing_block, outer=False)\n offset_x = text_align(\n context, line, new_available_width,\n last=(resume_at is None or preserved_line_break))\n if containing_block.style['direction'] == 'rtl':\n offset_x *= -1\n offset_x -= line.width\n\n bottom, top = line_box_verticality(line)\n assert top is not None\n assert bottom is not None\n line.baseline = -top\n line.position_y = top\n line.height = bottom - top\n offset_y = position_y - top\n line.margin_top = 0\n line.margin_bottom = 0\n\n line.translate(offset_x, offset_y)\n # Avoid floating point errors, as position_y - top + top != position_y\n # Removing this line breaks the position == linebox.position test below\n # See https://github.com/Kozea/WeasyPrint/issues/583\n line.position_y = position_y\n\n if line.height <= candidate_height:\n break\n candidate_height = line.height\n\n new_excluded_shapes = context.excluded_shapes\n context.excluded_shapes = excluded_shapes\n position_x, position_y, available_width = avoid_collisions(\n context, line, containing_block, outer=False)\n if containing_block.style['direction'] == 'ltr':\n condition = (position_x, position_y) == (\n original_position_x, original_position_y)\n else:\n condition = (position_x + line.width, position_y) == (\n original_position_x + original_width, original_position_y)\n if condition:\n context.excluded_shapes = new_excluded_shapes\n break\n\n absolute_boxes.extend(line_absolutes)\n fixed_boxes.extend(line_fixed)\n\n for placeholder in line_placeholders:\n if 'inline' in placeholder.style.specified['display']:\n # Inline-level static position:\n placeholder.translate(0, position_y - placeholder.position_y)\n else:\n # Block-level static position: at the start of the next line\n placeholder.translate(\n line.position_x - placeholder.position_x,\n position_y + line.height - placeholder.position_y)\n\n float_children = []\n waiting_floats_y = line.position_y + line.height\n for waiting_float in waiting_floats:\n waiting_float.position_y = waiting_floats_y\n new_waiting_float, waiting_float_resume_at = float_layout(\n context, waiting_float, containing_block, absolute_boxes,\n fixed_boxes, bottom_space, skip_stack=None)\n float_children.append(new_waiting_float)\n if waiting_float_resume_at:\n context.broken_out_of_flow[new_waiting_float] = (\n waiting_float, containing_block, waiting_float_resume_at)\n if float_children:\n line.children += tuple(float_children)\n\n return line, resume_at\n\n\ndef skip_first_whitespace(box, skip_stack):\n \"\"\"Return ``skip_stack`` to start just after removable leading spaces.\n\n See https://www.w3.org/TR/CSS21/text.html#white-space-model\n\n \"\"\"\n if skip_stack is None:\n index = 0\n next_skip_stack = None\n else:\n (index, next_skip_stack), = skip_stack.items()\n\n if isinstance(box, boxes.TextBox):\n assert next_skip_stack is None\n white_space = box.style['white_space']\n text = box.text.encode()\n if index == len(text):\n # Starting a the end of the TextBox, no text to see: Continue\n return 'continue'\n if white_space in ('normal', 'nowrap', 'pre-line'):\n text = text[index:]\n while text and text.startswith(b' '):\n index += 1\n text = text[1:]\n return {index: None} if index else None\n\n if isinstance(box, (boxes.LineBox, boxes.InlineBox)):\n if index == 0 and not box.children:\n return None\n result = skip_first_whitespace(box.children[index], next_skip_stack)\n if result == 'continue':\n index += 1\n if index >= len(box.children):\n return 'continue'\n result = skip_first_whitespace(box.children[index], None)\n return {index: result} if (index or result) else None\n\n assert skip_stack is None, f'unexpected skip inside {box}'\n return None\n\n\ndef remove_last_whitespace(context, box):\n \"\"\"Remove in place space characters at the end of a line.\n\n This also reduces the width and position of the inline parents of the\n modified text.\n\n \"\"\"\n ancestors = []\n while isinstance(box, (boxes.LineBox, boxes.InlineBox)):\n ancestors.append(box)\n if not box.children:\n return\n box = box.children[-1]\n if not (isinstance(box, boxes.TextBox) and\n box.style['white_space'] in ('normal', 'nowrap', 'pre-line')):\n return\n new_text = box.text.rstrip(' ')\n if new_text:\n if len(new_text) == len(box.text):\n return\n box.text = new_text\n new_box, resume, _ = split_text_box(context, box, None, 0)\n assert new_box is not None\n assert resume is None\n space_width = box.width - new_box.width\n box.width = new_box.width\n\n # RTL line, the trailing space is at the left of the box. We have to\n # translate the box to align the stripped text with the right edge of\n # the box.\n if new_box.pango_layout.first_line_direction % 2:\n box.position_x -= space_width\n for ancestor in ancestors:\n ancestor.position_x -= space_width\n else:\n space_width = box.width\n box.width = 0\n box.text = ''\n\n # RTL line, the textbox with a trailing space is now empty at the left\n # of the line. We have to translate the line to align it with the right\n # edge of the box.\n line = ancestors[0]\n if line.style['direction'] == 'rtl':\n line.translate(dx=-space_width, ignore_floats=True)\n\n for ancestor in ancestors:\n ancestor.width -= space_width\n\n # TODO: All tabs (U+0009) are rendered as a horizontal shift that\n # lines up the start edge of the next glyph with the next tab stop.\n # Tab stops occur at points that are multiples of 8 times the width\n # of a space (U+0020) rendered in the block's font from the block's\n # starting content edge.\n\n # TODO: If spaces (U+0020) or tabs (U+0009) at the end of a line have\n # 'white-space' set to 'pre-wrap', UAs may visually collapse them.\n\n\ndef first_letter_to_box(box, skip_stack, first_letter_style):\n \"\"\"Create a box for the ::first-letter selector.\"\"\"\n if first_letter_style and box.children:\n # Some properties must be ignored in first-letter boxes.\n # https://drafts.csswg.org/selectors-3/#application-in-css\n # At least, position is ignored to avoid layout troubles.\n first_letter_style['position'] = 'static'\n\n first_letter = ''\n child = box.children[0]\n if isinstance(child, boxes.TextBox):\n letter_style = computed_from_cascaded(\n cascaded={}, parent_style=first_letter_style, element=None)\n if child.element_tag.endswith('::first-letter'):\n letter_box = boxes.InlineBox(\n f'{box.element_tag}::first-letter', letter_style,\n box.element, [child])\n box.children = (\n (letter_box,) + tuple(box.children[1:]))\n elif child.text:\n character_found = False\n if skip_stack:\n child_skip_stack, = skip_stack.values()\n if child_skip_stack:\n index, = child_skip_stack\n child.text = child.text[index:]\n skip_stack = None\n while child.text:\n next_letter = child.text[0]\n category = unicodedata.category(next_letter)\n if category not in ('Ps', 'Pe', 'Pi', 'Pf', 'Po'):\n if character_found:\n break\n character_found = True\n first_letter += next_letter\n child.text = child.text[1:]\n if first_letter.lstrip('\\n'):\n # \"This type of initial letter is similar to an\n # inline-level element if its 'float' property is 'none',\n # otherwise it is similar to a floated element.\"\n if first_letter_style['float'] == 'none':\n letter_box = boxes.InlineBox(\n f'{box.element_tag}::first-letter',\n first_letter_style, box.element, [])\n text_box = boxes.TextBox(\n f'{box.element_tag}::first-letter', letter_style,\n box.element, first_letter)\n letter_box.children = (text_box,)\n box.children = (letter_box,) + tuple(box.children)\n else:\n letter_box = boxes.BlockBox(\n f'{box.element_tag}::first-letter',\n first_letter_style, box.element, [])\n letter_box.first_letter_style = None\n line_box = boxes.LineBox(\n f'{box.element_tag}::first-letter', letter_style,\n box.element, [])\n letter_box.children = (line_box,)\n text_box = boxes.TextBox(\n f'{box.element_tag}::first-letter', letter_style,\n box.element, first_letter)\n line_box.children = (text_box,)\n box.children = (letter_box,) + tuple(box.children)\n build.process_text_transform(text_box)\n if skip_stack and child_skip_stack:\n index, = skip_stack\n (child_index, grandchild_skip_stack), = (\n child_skip_stack.items())\n skip_stack = {\n index: {child_index + 1: grandchild_skip_stack}}\n elif isinstance(child, boxes.ParentBox):\n if skip_stack:\n child_skip_stack, = skip_stack.values()\n else:\n child_skip_stack = None\n child_skip_stack = first_letter_to_box(\n child, child_skip_stack, first_letter_style)\n if skip_stack:\n index, = skip_stack\n skip_stack = {index: child_skip_stack}\n return skip_stack\n\n\ndef atomic_box(context, box, position_x, skip_stack, containing_block,\n absolute_boxes, fixed_boxes):\n \"\"\"Compute the width and the height of the atomic ``box``.\"\"\"\n if isinstance(box, boxes.ReplacedBox):\n box = box.copy()\n inline_replaced_box_layout(box, containing_block)\n box.baseline = box.margin_height()\n elif isinstance(box, boxes.InlineBlockBox):\n if box.is_table_wrapper:\n containing_size = (containing_block.width, containing_block.height)\n table_wrapper_width(context, box, containing_size)\n box = inline_block_box_layout(\n context, box, position_x, skip_stack, containing_block,\n absolute_boxes, fixed_boxes)\n else: # pragma: no cover\n raise TypeError(f'Layout for {type(box).__name__} not handled yet')\n return box\n\n\ndef inline_block_box_layout(context, box, position_x, skip_stack,\n containing_block, absolute_boxes, fixed_boxes):\n from .block import block_container_layout\n\n resolve_percentages(box, containing_block)\n\n # https://www.w3.org/TR/CSS21/visudet.html#inlineblock-width\n if box.margin_left == 'auto':\n box.margin_left = 0\n if box.margin_right == 'auto':\n box.margin_right = 0\n # https://www.w3.org/TR/CSS21/visudet.html#block-root-margin\n if box.margin_top == 'auto':\n box.margin_top = 0\n if box.margin_bottom == 'auto':\n box.margin_bottom = 0\n\n inline_block_width(box, context, containing_block)\n\n box.position_x = position_x\n box.position_y = 0\n box, _, _, _, _, _ = block_container_layout(\n context, box, bottom_space=-inf, skip_stack=skip_stack,\n page_is_empty=True, absolute_boxes=absolute_boxes,\n fixed_boxes=fixed_boxes, adjoining_margins=None, discard=False,\n max_lines=None)\n box.baseline = inline_block_baseline(box)\n return box\n\n\ndef inline_block_baseline(box):\n \"\"\"Return the y position of the baseline for an inline block.\n\n Position is taken from the top of its margin box.\n\n https://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align\n\n \"\"\"\n if box.is_table_wrapper:\n # Inline table's baseline is its first row's baseline\n for child in box.children:\n if isinstance(child, boxes.TableBox):\n if child.children and child.children[0].children:\n first_row = child.children[0].children[0]\n return first_row.baseline\n elif box.style['overflow'] == 'visible':\n result = find_in_flow_baseline(box, last=True)\n if result:\n return result\n return box.position_y + box.margin_height()\n\n\n@handle_min_max_width\ndef inline_block_width(box, context, containing_block):\n available_content_width = containing_block.width - (\n box.margin_left + box.margin_right +\n box.border_left_width + box.border_right_width +\n box.padding_left + box.padding_right)\n if box.width == 'auto':\n box.width = shrink_to_fit(context, box, available_content_width)\n\n\ndef split_inline_level(context, box, position_x, max_x, bottom_space,\n skip_stack, containing_block, absolute_boxes,\n fixed_boxes, line_placeholders, waiting_floats,\n line_children):\n \"\"\"Fit as much content as possible from an inline-level box in a width.\n\n Return ``(new_box, resume_at, preserved_line_break, first_letter,\n last_letter)``. ``resume_at`` is ``None`` if all of the content\n fits. Otherwise it can be passed as a ``skip_stack`` parameter to resume\n where we left off.\n\n ``new_box`` is non-empty (unless the box is empty) and as big as possible\n while being narrower than ``available_width``, if possible (may overflow\n is no split is possible.)\n\n \"\"\"\n resolve_percentages(box, containing_block)\n float_widths = {'left': 0, 'right': 0}\n if isinstance(box, boxes.TextBox):\n box.position_x = position_x\n if skip_stack is None:\n skip = 0\n else:\n (skip, skip_stack), = skip_stack.items()\n skip = skip or 0\n assert skip_stack is None\n\n is_line_start = len(line_children) == 0\n new_box, skip, preserved_line_break = split_text_box(\n context, box, max_x - position_x, skip,\n is_line_start=is_line_start)\n\n if skip is None:\n resume_at = None\n else:\n resume_at = {skip: None}\n if box.text:\n first_letter = box.text[0]\n if skip is None:\n last_letter = box.text[-1]\n else:\n last_letter = box.text.encode()[:skip].decode()[-1]\n else:\n first_letter = last_letter = None\n elif isinstance(box, boxes.InlineBox):\n if box.margin_left == 'auto':\n box.margin_left = 0\n if box.margin_right == 'auto':\n box.margin_right = 0\n (new_box, resume_at, preserved_line_break, first_letter,\n last_letter, float_widths) = split_inline_box(\n context, box, position_x, max_x, bottom_space, skip_stack,\n containing_block, absolute_boxes, fixed_boxes, line_placeholders,\n waiting_floats, line_children)\n elif isinstance(box, boxes.AtomicInlineLevelBox):\n new_box = atomic_box(\n context, box, position_x, skip_stack, containing_block,\n absolute_boxes, fixed_boxes)\n new_box.position_x = position_x\n resume_at = None\n preserved_line_break = False\n # See https://www.w3.org/TR/css-text-3/#line-breaking\n # Atomic inlines behave like ideographic characters.\n first_letter = '\\u2e80'\n last_letter = '\\u2e80'\n elif isinstance(box, boxes.InlineFlexBox):\n box.position_x = position_x\n box.position_y = 0\n for side in ('top', 'right', 'bottom', 'left'):\n if getattr(box, f'margin_{side}') == 'auto':\n setattr(box, f'margin_{side}', 0)\n new_box, resume_at, _, _, _ = flex_layout(\n context, box, -inf, skip_stack, containing_block, False,\n absolute_boxes, fixed_boxes)\n preserved_line_break = False\n first_letter = '\\u2e80'\n last_letter = '\\u2e80'\n else: # pragma: no cover\n raise TypeError(f'Layout for {type(box).__name__} not handled yet')\n return (\n new_box, resume_at, preserved_line_break, first_letter, last_letter,\n float_widths)\n\n\ndef _out_of_flow_layout(context, box, containing_block, index, child,\n children, line_children, waiting_children,\n waiting_floats, absolute_boxes, fixed_boxes,\n line_placeholders, float_widths, max_x, position_x,\n bottom_space):\n if child.is_absolutely_positioned():\n child.position_x = position_x\n placeholder = AbsolutePlaceholder(child)\n line_placeholders.append(placeholder)\n waiting_children.append((index, placeholder, child))\n if child.style['position'] == 'absolute':\n absolute_boxes.append(placeholder)\n else:\n fixed_boxes.append(placeholder)\n\n elif child.is_floated():\n child.position_x = position_x\n float_width = shrink_to_fit(context, child, containing_block.width)\n\n # To retrieve the real available space for floats, we must remove\n # the trailing whitespaces from the line\n non_floating_children = [\n child_ for _, child_, _ in (children + waiting_children)\n if not child_.is_floated()]\n if non_floating_children:\n float_width -= trailing_whitespace_size(\n context, non_floating_children[-1])\n\n if float_width > max_x - position_x or waiting_floats:\n # TODO: the absolute and fixed boxes in the floats must be\n # added here, and not in iter_line_boxes\n waiting_floats.append(child)\n else:\n new_child, float_resume_at = float_layout(\n context, child, containing_block, absolute_boxes, fixed_boxes,\n bottom_space, skip_stack=None)\n if float_resume_at:\n context.broken_out_of_flow[child] = (\n child, containing_block, float_resume_at)\n waiting_children.append((index, new_child, child))\n child = new_child\n\n # Translate previous line children\n dx = max(child.margin_width(), 0)\n float_widths[child.style['float']] += dx\n if child.style['float'] == 'left':\n if isinstance(box, boxes.LineBox):\n # The parent is the line, update the current position\n # for the next child. When the parent is not the line\n # (it is an inline block), the current position of the\n # line is updated by the box itself (see next\n # split_inline_level call).\n position_x += dx\n elif child.style['float'] == 'right':\n # Update the maximum x position for the next children\n max_x -= dx\n for _, old_child in line_children:\n if not old_child.is_in_normal_flow():\n continue\n if ((child.style['float'] == 'left' and\n box.style['direction'] == 'ltr') or\n (child.style['float'] == 'right' and\n box.style['direction'] == 'rtl')):\n old_child.translate(dx=dx)\n\n elif child.is_running():\n running_name = child.style['position'][1]\n page = context.current_page\n context.running_elements[running_name][page].append(child)\n\n\ndef _break_waiting_children(context, box, max_x, bottom_space,\n initial_skip_stack, absolute_boxes, fixed_boxes,\n line_placeholders, waiting_floats, line_children,\n children, waiting_children):\n if waiting_children:\n # Too wide, try to cut inside waiting children, starting from the end.\n # TODO: we should take care of children added into absolute_boxes,\n # fixed_boxes and other lists.\n waiting_children_copy = waiting_children.copy()\n while waiting_children_copy:\n child_index, child, original_child = waiting_children_copy.pop()\n if not child.is_in_normal_flow() or not can_break_inside(child):\n continue\n\n if initial_skip_stack and child_index in initial_skip_stack:\n child_skip_stack = initial_skip_stack[child_index]\n else:\n child_skip_stack = None\n\n # Break the waiting child at its last possible breaking point.\n # TODO: The dirty solution chosen here is to decrease the\n # actual size by 1 and render the waiting child again with this\n # constraint. We may find a better way.\n max_x = child.position_x + child.margin_width() - 1\n while max_x > child.position_x:\n new_child, child_resume_at, _, _, _, _ = split_inline_level(\n context, original_child, child.position_x, max_x,\n bottom_space, child_skip_stack, box, absolute_boxes,\n fixed_boxes, line_placeholders, waiting_floats,\n line_children)\n if child_resume_at:\n break\n max_x -= 1\n else:\n # No line break found\n continue\n\n children.extend(waiting_children_copy)\n if new_child is None:\n # May be None where we have an empty TextBox.\n assert isinstance(child, boxes.TextBox)\n else:\n children.append((child_index, new_child, child))\n\n return {child_index: child_resume_at}\n\n if children:\n # Too wide, can't break waiting children and the inline is\n # non-empty: put child entirely on the next line.\n return {children[-1][0] + 1: None}\n\n\ndef split_inline_box(context, box, position_x, max_x, bottom_space, skip_stack,\n containing_block, absolute_boxes, fixed_boxes,\n line_placeholders, waiting_floats, line_children):\n \"\"\"Same behavior as split_inline_level.\"\"\"\n\n # In some cases (shrink-to-fit result being the preferred width)\n # max_x is coming from Pango itself,\n # but floating point errors have accumulated:\n # width2 = (width + X) - X # in some cases, width2 < width\n # Increase the value a bit to compensate and not introduce\n # an unexpected line break. The 1e-9 value comes from PEP 485.\n max_x *= 1 + 1e-9\n\n is_start = skip_stack is None\n initial_position_x = position_x\n initial_skip_stack = skip_stack\n assert isinstance(box, (boxes.LineBox, boxes.InlineBox))\n left_spacing = (\n box.padding_left + box.margin_left + box.border_left_width)\n right_spacing = (\n box.padding_right + box.margin_right + box.border_right_width)\n content_box_left = position_x\n\n children = []\n waiting_children = []\n preserved_line_break = False\n first_letter = last_letter = None\n float_widths = {'left': 0, 'right': 0}\n float_resume_index = 0\n\n if box.style['position'] == 'relative':\n absolute_boxes = []\n\n if is_start:\n skip = 0\n else:\n (skip, skip_stack), = skip_stack.items()\n\n for i, child in enumerate(box.children[skip:]):\n index = i + skip\n child.position_y = box.position_y\n\n if not child.is_in_normal_flow():\n _out_of_flow_layout(\n context, box, containing_block, index, child, children,\n line_children, waiting_children, waiting_floats,\n absolute_boxes, fixed_boxes, line_placeholders, float_widths,\n max_x, position_x, bottom_space)\n if child.is_floated():\n float_resume_index = index + 1\n if child not in waiting_floats:\n max_x -= child.margin_width()\n continue\n\n is_last_child = (index == len(box.children) - 1)\n available_width = max_x\n child_waiting_floats = []\n new_child, resume_at, preserved, first, last, new_float_widths = (\n split_inline_level(\n context, child, position_x, available_width, bottom_space,\n skip_stack, containing_block, absolute_boxes, fixed_boxes,\n line_placeholders, child_waiting_floats, line_children))\n if box.style['direction'] == 'rtl':\n end_spacing = left_spacing\n max_x -= new_float_widths['left']\n else:\n end_spacing = right_spacing\n max_x -= new_float_widths['right']\n if is_last_child and end_spacing and resume_at is None:\n # TODO: we should take care of children added into absolute_boxes,\n # fixed_boxes and other lists.\n available_width -= end_spacing\n new_child, resume_at, preserved, first, last, new_float_widths = (\n split_inline_level(\n context, child, position_x, available_width, bottom_space,\n skip_stack, containing_block, absolute_boxes, fixed_boxes,\n line_placeholders, child_waiting_floats, line_children))\n\n skip_stack = None\n if preserved:\n preserved_line_break = True\n\n can_break = None\n if last_letter is True:\n last_letter = ' '\n elif last_letter is False:\n last_letter = ' ' # no-break space\n elif box.style['white_space'] in ('pre', 'nowrap'):\n can_break = False\n if can_break is None:\n if None in (last_letter, first):\n can_break = False\n elif first in (True, False):\n can_break = first\n else:\n can_break = can_break_text(\n last_letter + first, child.style['lang'])\n\n if can_break:\n children.extend(waiting_children)\n waiting_children = []\n\n if first_letter is None:\n first_letter = first\n if child.trailing_collapsible_space:\n last_letter = True\n else:\n last_letter = last\n\n if new_child is None:\n # May be None where we have an empty TextBox.\n assert isinstance(child, boxes.TextBox)\n else:\n if isinstance(box, boxes.LineBox):\n line_children.append((index, new_child))\n trailing_whitespace = (\n isinstance(new_child, boxes.TextBox) and\n new_child.text and\n unicodedata.category(new_child.text[-1]) == 'Zs')\n new_position_x = new_child.position_x + new_child.margin_width()\n\n if new_position_x > max_x and not trailing_whitespace:\n previous_resume_at = _break_waiting_children(\n context, box, max_x, bottom_space, initial_skip_stack,\n absolute_boxes, fixed_boxes, line_placeholders,\n waiting_floats, line_children, children, waiting_children)\n if previous_resume_at:\n resume_at = previous_resume_at\n break\n\n position_x = new_position_x\n waiting_children.append((index, new_child, child))\n\n waiting_floats.extend(child_waiting_floats)\n if resume_at is not None:\n children.extend(waiting_children)\n resume_at = {index: resume_at}\n break\n else:\n children.extend(waiting_children)\n resume_at = None\n\n # Reorder inline blocks when direction is rtl\n if box.style['direction'] == 'rtl' and len(children) > 1:\n in_flow_children = [\n box_child for _, box_child, _ in children\n if box_child.is_in_normal_flow()]\n position_x = in_flow_children[0].position_x\n for child in in_flow_children[::-1]:\n child.translate(\n dx=(position_x - child.position_x), ignore_floats=True)\n position_x += child.margin_width()\n\n is_end = resume_at is None\n new_box = box.copy_with_children(\n [box_child for index, box_child, _ in children])\n new_box.remove_decoration(start=not is_start, end=not is_end)\n if isinstance(box, boxes.LineBox):\n # We must reset line box width according to its new children\n new_box.width = 0\n children = new_box.children\n if new_box.style['direction'] == 'ltr':\n children = children[::-1]\n for child in children:\n if child.is_in_normal_flow():\n new_box.width = (\n child.position_x + child.margin_width() -\n new_box.position_x)\n break\n else:\n new_box.position_x = initial_position_x\n if box.style['box_decoration_break'] == 'clone':\n translation_needed = True\n else:\n translation_needed = (\n is_start if box.style['direction'] == 'ltr' else is_end)\n if translation_needed:\n for child in new_box.children:\n child.translate(dx=left_spacing)\n new_box.width = position_x - content_box_left\n new_box.translate(dx=float_widths['left'], ignore_floats=True)\n\n line_height, new_box.baseline = strut_layout(box.style, context)\n new_box.height = box.style['font_size']\n half_leading = (line_height - new_box.height) / 2\n # Set margins to the half leading but also compensate for borders and\n # paddings. We want margin_height() == line_height\n new_box.margin_top = (\n half_leading - new_box.border_top_width - new_box.padding_top)\n new_box.margin_bottom = (\n half_leading - new_box.border_bottom_width - new_box.padding_bottom)\n\n if new_box.style['position'] == 'relative':\n for absolute_box in absolute_boxes:\n absolute_layout(\n context, absolute_box, new_box, fixed_boxes, bottom_space,\n skip_stack=None)\n\n if resume_at is not None:\n index = tuple(resume_at)[0]\n if index < float_resume_index:\n resume_at = {float_resume_index: None}\n\n if box.is_leader:\n first_letter = True\n last_letter = False\n\n return (\n new_box, resume_at, preserved_line_break, first_letter, last_letter,\n float_widths)\n\n\ndef split_text_box(context, box, available_width, skip, is_line_start=True):\n \"\"\"Keep as much text as possible from a TextBox in a limited width.\n\n Try not to overflow but always have some text in ``new_box``.\n\n Return ``(new_box, skip, preserved_line_break)``. ``skip`` is the number of\n UTF-8 bytes to skip form the start of the TextBox for the next line, or\n ``None`` if all of the text fits.\n\n Also break on preserved line breaks.\n\n \"\"\"\n assert isinstance(box, boxes.TextBox)\n font_size = box.style['font_size']\n text = box.text.encode()[skip:]\n if font_size == 0 or not text:\n return None, None, False\n layout, length, resume_index, width, height, baseline = split_first_line(\n text.decode(), box.style, context, available_width,\n box.justification_spacing, is_line_start=is_line_start)\n assert resume_index != 0\n\n if length > 0:\n box = box.copy_with_text(layout.text)\n box.width = width\n box.pango_layout = layout\n # \"The height of the content area should be based on the font,\n # but this specification does not specify how.\"\n # https://www.w3.org/TR/CSS21/visudet.html#inline-non-replaced\n # We trust Pango and use the height of the LayoutLine.\n box.height = height\n # \"only the 'line-height' is used when calculating the height\n # of the line box.\"\n # Set margins so that margin_height() == line_height\n line_height, _ = strut_layout(box.style, context)\n half_leading = (line_height - height) / 2\n box.margin_top = half_leading\n box.margin_bottom = half_leading\n # form the top of the content box\n box.baseline = baseline\n # form the top of the margin box\n box.baseline += box.margin_top\n else:\n box = None\n\n if resume_index is None:\n preserved_line_break = False\n else:\n between = text[length:resume_index].decode()\n preserved_line_break = (\n (length != resume_index) and between.strip(' '))\n if preserved_line_break:\n # See https://unicode.org/reports/tr14/\n # \\r is already handled by process_whitespace\n line_breaks = ('\\n', '\\t', '\\f', '\\u0085', '\\u2028', '\\u2029')\n assert between in line_breaks, (\n 'Got %r between two lines. '\n 'Expected nothing or a preserved line break' % (between,))\n resume_index += skip\n\n return box, resume_index, preserved_line_break\n\n\ndef line_box_verticality(box):\n \"\"\"Handle ``vertical-align`` within a :class:`LineBox`.\n\n Place all boxes vertically assuming that the baseline of ``box``\n is at `y = 0`.\n\n Return ``(max_y, min_y)``, the maximum and minimum vertical position\n of margin boxes.\n\n \"\"\"\n top_bottom_subtrees = []\n max_y, min_y = aligned_subtree_verticality(\n box, top_bottom_subtrees, baseline_y=0)\n subtrees_with_min_max = [\n (subtree, sub_max_y, sub_min_y)\n for subtree in top_bottom_subtrees\n for sub_max_y, sub_min_y in [\n (None, None) if subtree.is_floated()\n else aligned_subtree_verticality(\n subtree, top_bottom_subtrees, baseline_y=0)]]\n\n if subtrees_with_min_max:\n sub_positions = [\n sub_max_y - sub_min_y\n for subtree, sub_max_y, sub_min_y in subtrees_with_min_max\n if not subtree.is_floated()]\n if sub_positions:\n highest_sub = max(sub_positions)\n max_y = max(max_y, min_y + highest_sub)\n\n for subtree, sub_max_y, sub_min_y in subtrees_with_min_max:\n if subtree.is_floated():\n dy = min_y - subtree.position_y\n elif subtree.style['vertical_align'] == 'top':\n dy = min_y - sub_min_y\n else:\n assert subtree.style['vertical_align'] == 'bottom'\n dy = max_y - sub_max_y\n translate_subtree(subtree, dy)\n return max_y, min_y\n\n\ndef translate_subtree(box, dy):\n if isinstance(box, boxes.InlineBox):\n box.position_y += dy\n if box.style['vertical_align'] in ('top', 'bottom'):\n for child in box.children:\n translate_subtree(child, dy)\n else:\n # Text or atomic boxes\n box.translate(dy=dy)\n\n\ndef aligned_subtree_verticality(box, top_bottom_subtrees, baseline_y):\n max_y, min_y = inline_box_verticality(box, top_bottom_subtrees, baseline_y)\n # Account for the line box itself:\n top = baseline_y - box.baseline\n bottom = top + box.margin_height()\n if min_y is None or top < min_y:\n min_y = top\n if max_y is None or bottom > max_y:\n max_y = bottom\n\n return max_y, min_y\n\n\ndef inline_box_verticality(box, top_bottom_subtrees, baseline_y):\n \"\"\"Handle ``vertical-align`` within an :class:`InlineBox`.\n\n Place all boxes vertically assuming that the baseline of ``box``\n is at `y = baseline_y`.\n\n Return ``(max_y, min_y)``, the maximum and minimum vertical position\n of margin boxes.\n\n \"\"\"\n max_y = None\n min_y = None\n if not isinstance(box, (boxes.LineBox, boxes.InlineBox)):\n return max_y, min_y\n\n for child in box.children:\n if not child.is_in_normal_flow():\n if child.is_floated():\n top_bottom_subtrees.append(child)\n continue\n vertical_align = child.style['vertical_align']\n if vertical_align == 'baseline':\n child_baseline_y = baseline_y\n elif vertical_align == 'middle':\n one_ex = box.style['font_size'] * character_ratio(box.style, 'x')\n top = baseline_y - (one_ex + child.margin_height()) / 2\n child_baseline_y = top + child.baseline\n elif vertical_align == 'text-top':\n # align top with the top of the parent’s content area\n top = (baseline_y - box.baseline + box.margin_top +\n box.border_top_width + box.padding_top)\n child_baseline_y = top + child.baseline\n elif vertical_align == 'text-bottom':\n # align bottom with the bottom of the parent’s content area\n bottom = (baseline_y - box.baseline + box.margin_top +\n box.border_top_width + box.padding_top + box.height)\n child_baseline_y = bottom - child.margin_height() + child.baseline\n elif vertical_align in ('top', 'bottom'):\n # TODO: actually implement vertical-align: top and bottom\n # Later, we will assume for this subtree that its baseline\n # is at y=0.\n child_baseline_y = 0\n else:\n # Numeric value: The child’s baseline is `vertical_align` above\n # (lower y) the parent’s baseline.\n child_baseline_y = baseline_y - vertical_align\n\n # the child’s `top` is `child.baseline` above (lower y) its baseline.\n top = child_baseline_y - child.baseline\n if isinstance(child, (boxes.InlineBlockBox, boxes.InlineFlexBox)):\n # This also includes table wrappers for inline tables.\n child.translate(dy=top - child.position_y)\n else:\n child.position_y = top\n # grand-children for inline boxes are handled below\n\n if vertical_align in ('top', 'bottom'):\n # top or bottom are special, they need to be handled in\n # a later pass.\n top_bottom_subtrees.append(child)\n continue\n\n bottom = top + child.margin_height()\n if min_y is None or top < min_y:\n min_y = top\n if max_y is None or bottom > max_y:\n max_y = bottom\n if isinstance(child, boxes.InlineBox):\n children_max_y, children_min_y = inline_box_verticality(\n child, top_bottom_subtrees, child_baseline_y)\n if children_min_y is not None and children_min_y < min_y:\n min_y = children_min_y\n if children_max_y is not None and children_max_y > max_y:\n max_y = children_max_y\n return max_y, min_y\n\n\ndef text_align(context, line, available_width, last):\n \"\"\"Return the line horizontal offset according to ``text-align``.\"\"\"\n\n # \"When the total width of the inline-level boxes on a line is less than\n # the width of the line box containing them, their horizontal distribution\n # within the line box is determined by the 'text-align' property.\"\n if line.width >= available_width:\n return 0\n\n align = line.style['text_align_all']\n if last:\n align_last = line.style['text_align_last']\n align = align if align_last == 'auto' else align_last\n space_collapse = line.style['white_space'] in (\n 'normal', 'nowrap', 'pre-line')\n if align in ('left', 'right'):\n if (align == 'left') ^ (line.style['direction'] == 'rtl'):\n align = 'start'\n else:\n align = 'end'\n if align == 'start':\n return 0\n offset = available_width - line.width\n if align == 'justify':\n if space_collapse:\n # Justification of texts where white space is not collapsing is\n # - forbidden by CSS 2, and\n # - not required by CSS 3 Text.\n justify_line(context, line, offset)\n return 0\n if align == 'center':\n return offset / 2\n else:\n assert align == 'end'\n return offset\n\n\ndef justify_line(context, line, extra_width):\n # TODO: We should use a better algorithm here, see\n # https://www.w3.org/TR/css-text-3/#justify-algos\n nb_spaces = count_spaces(line)\n if nb_spaces == 0:\n return\n add_word_spacing(context, line, extra_width / nb_spaces, 0)\n\n\ndef count_spaces(box):\n if isinstance(box, boxes.TextBox):\n # TODO: remove trailing spaces correctly\n return box.text.count(' ')\n elif isinstance(box, (boxes.LineBox, boxes.InlineBox)):\n return sum(count_spaces(child) for child in box.children)\n else:\n return 0\n\n\ndef add_word_spacing(context, box, justification_spacing, x_advance):\n if isinstance(box, boxes.TextBox):\n box.justification_spacing = justification_spacing\n box.position_x += x_advance\n nb_spaces = count_spaces(box)\n if nb_spaces > 0:\n layout = create_layout(\n box.text, box.style, context, max_width=None,\n justification_spacing=box.justification_spacing)\n layout.deactivate()\n extra_space = justification_spacing * nb_spaces\n x_advance += extra_space\n box.width += extra_space\n box.pango_layout = layout\n elif isinstance(box, (boxes.LineBox, boxes.InlineBox)):\n box.position_x += x_advance\n previous_x_advance = x_advance\n for child in box.children:\n if child.is_in_normal_flow():\n x_advance = add_word_spacing(\n context, child, justification_spacing, x_advance)\n box.width += x_advance - previous_x_advance\n else:\n # Atomic inline-level box\n box.translate(x_advance, 0)\n return x_advance\n\n\ndef is_phantom_linebox(linebox):\n # See https://www.w3.org/TR/CSS21/visuren.html#phantom-line-box\n for child in linebox.children:\n if isinstance(child, boxes.InlineBox):\n if not is_phantom_linebox(child):\n return False\n for side in ('top', 'right', 'bottom', 'left'):\n if (getattr(child.style[f'margin_{side}'], 'value', None) or\n child.style[f'border_{side}_width'] or\n child.style[f'padding_{side}'].value):\n return False\n elif child.is_in_normal_flow():\n return False\n return True\n\n\ndef can_break_inside(box):\n # See https://www.w3.org/TR/css-text-3/#white-space-property\n text_wrap = box.style['white_space'] in ('normal', 'pre-wrap', 'pre-line')\n if isinstance(box, boxes.AtomicInlineLevelBox):\n return False\n elif text_wrap and isinstance(box, boxes.TextBox):\n return can_break_text(box.text, box.style['lang'])\n elif text_wrap and isinstance(box, boxes.ParentBox):\n return any(can_break_inside(child) for child in box.children)\n return False\n","repo_name":"Kozea/WeasyPrint","sub_path":"weasyprint/layout/inline.py","file_name":"inline.py","file_ext":"py","file_size_in_byte":47576,"program_lang":"python","lang":"en","doc_type":"code","stars":6201,"dataset":"github-code","pt":"85"} +{"seq_id":"7865755993","text":"'''\r\n1. WAP to accept a name of a file from user and print count of lines present in that file based on following filters\r\n\t- if filter comes as a empty string - count total lines using readline()\r\n\t- if filter=\"^substr\" the line count should be of lines which starts with \"substr\"\r\n\t- if filter=\"substr$\" - count ends with substr\r\n\t- if neither above then check for contains \"substr\" and count lines.\r\n'''\r\ndef findsubstr(szStr, szFilter):\r\n\tiCnt = 0\r\n\tszFilter = szFilter.lower()\r\n\tif szFilter.startswith(\"^\"):\r\n\t\tszTemp = szStr[0: len(szFilter)-1:]\r\n\t\tszTemp = szTemp.lower()\r\n\t\tif szTemp == szFilter[1:]:\r\n\t\t\tiCnt = 1\r\n\telif szFilter.endswith(\"$\"):\r\n\t\tszTemp = szStr[len(szStr) - (len(szFilter) -1 )- 1: len(szStr) - 1:]\r\n\t\tszTemp = szTemp.lower()\r\n\t\tif szTemp == szFilter[0: (len(szFilter) - 1)]:\r\n\t\t\tiCnt = 1\r\n\telif szFilter in szStr:\r\n\t\tszStr = szStr.lower()\r\n\t\tif 1 <= szStr.count(szFilter):\r\n\t\t\tiCnt = 1\r\n\telse:\r\n\t\tiCnt = 1\r\n\t\t\r\n\treturn iCnt\r\n\r\ndef findfile(filename, szFilter = \"\"):\r\n\tiCnt = 0\r\n\tfp = open(filename, \"r\")\r\n\tline = fp.readline()\r\n\twhile line != \"\":\r\n\t\tiCnt = iCnt + findsubstr(line, szFilter)\r\n\t\tline = fp.readline()\r\n\t\t\r\n\tprint(\"Total Lines :{}\".format(iCnt))\r\n\t\t\r\ndef main():\r\n\tinFilename = \"Hello.txt\"\r\n\t#inFilename = input(\"Enter filename:\")\r\n\tszFilter = input(\"Enter filter(^Hello, Hello$, Hello):\")\r\n\tfindfile(inFilename, szFilter)\r\n\t\r\nif __name__ == '__main__':\r\n\tmain()\r\n","repo_name":"palandesupriya/python","sub_path":"file handling/filefilter.py","file_name":"filefilter.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28670939505","text":"import cv2\nimport RPi.GPIO as gp\nimport time\nimport os\n#from switch_cam import switch_camera\n\nclass Adapter:\n SHOW_FRAME = 0\n WIDTH = 640\n HEIGHT = 480\n FPS = 30\n\n def __init__(self):\n self.setup_gpio()\n\n self.switch_camera('A')\n\n print(f'Using OpenCV version {cv2.__version__}')\n \n \n self.cap = cv2.VideoCapture(0)\n self.cap.set(cv2.CAP_PROP_FRAME_WIDTH,self.WIDTH)\n self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT,self.HEIGHT)\n self.cap.set(cv2.CAP_PROP_FPS,self.FPS)\n\n self.test_adapter()\n\n self.cameras = []\n\n for cam_id in 'AC':\n if (self.test_camera(cam_id)):\n self.cameras.append(Camera(cam_id))\n\n def setup_gpio(self):\n gp.setwarnings(False)\n gp.setmode(gp.BOARD)\n\n gp.setup(7, gp.OUT)\n gp.setup(11, gp.OUT)\n gp.setup(12, gp.OUT)\n\n def test_adapter(self):\n if(not self.cap.isOpened()):\n print(f'Adapter is not connected')\n else:\n print(f'Adapter connection is good')\n\n #FIXME doesn't actually test cam, just tests adapter\n def test_camera(self, cam_id):\n self.switch_camera(cam_id)\n rt, frame = self.cap.read()\n if not rt:\n print(f'Cam {cam_id} not working')\n return False\n else:\n return True\n\n \n def create_writers(self, file_num):\n for cam in self.cameras:\n cam.create_writer(file_num)\n\n def record_frame(self):\n for cam in self.cameras:\n self.switch_camera(cam.cam_id)\n \n #self.cap.read()\n rt, cam.frame = self.cap.read()\n if not rt:\n print(\"Failed to get a frame\")\n\n hms = time.strftime('%H-%M-%S', time.localtime())\n cv2.putText(cam.frame, str(hms), (0, 35), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255))\n cam.writer.write(cam.frame)\n #time.sleep(0.09)\n\n \n if self.SHOW_FRAME:\n cv2.imshow('frame', frame)\n\n def close_writers(self):\n for cam in self.cameras:\n cam.close_writer()\n\n def close(self):\n self.cap.release()\n cv2.destroyAllWindows()\n\n def switch_camera(self, cam = 'A'):\n\n if cam == 'A':\n i2c = \"i2cset -y 1 0x70 0x00 0x04\"\n os.system(i2c)\n\n gp.output(7, False)\n gp.output(11, False)\n gp.output(12, True)\n\n elif cam == 'B':\n i2c = \"i2cset -y 1 0x70 0x00 0x05\"\n os.system(i2c)\n \n gp.output(7, True)\n gp.output(11, False)\n gp.output(12, True)\n\n elif cam == 'C':\n i2c = \"i2cset -y 1 0x70 0x00 0x06\"\n os.system(i2c)\n\n gp.output(7, False)\n gp.output(11, True)\n gp.output(12, False)\n\n elif cam == 'D':\n i2c = \"i2cset -y 1 0x70 0x00 0x06\"\n os.system(i2c)\n\n gp.output(7, True)\n gp.output(11, True)\n gp.output(12, False)\n\n print(f'Turned on Camera {cam}') \n\n\nclass Camera:\n SHOW_FRAME = 0\n WIDTH = 640\n HEIGHT = 480\n FPS = 15\n \n def __init__(self, cam_id, output_dir=\"/home/pi\", pin=37):\n self.cam_id = cam_id\n self.fcc = cv2.VideoWriter_fourcc(*'XVID')\n self.output_dir = output_dir\n self.frame = None\n #print(f'Using OpenCV version {cv2.__version__} on cam {cam_id}')\n\n \n def create_writer(self, file_num):\n file_name = f'{self.output_dir}/cam{self.cam_id}_file{file_num}.avi'\n self.writer = cv2.VideoWriter(file_name, self.fcc, self.FPS, (self.WIDTH, self.HEIGHT))\n\n def close_writer(self):\n self.writer.release()\n\n def close_camera(self):\n self.cam.release()\n cv2.destroyAllWindows()\n \n\n\n \nif __name__ == \"__main__\":\n cam = Camera('C')\n cam.create_cam()\n cam.test_camera()\n for file_num in range(3):\n cam.create_writer(file_num)\n for frame_num in range(90):\n cam.record_frame()\n cam.closerWriter()\n\n cam.close()\n\n","repo_name":"Apogee-Robotics/Cameras","sub_path":"pi_cameras.py","file_name":"pi_cameras.py","file_ext":"py","file_size_in_byte":4120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5826421089","text":"import json\nimport requests\nimport pprint \nimport james_stein as js\nimport numpy as np\n\ndef main():\n stock_data = np.load(\"stock_data.npy\")\n t_stock_data = np.transpose(stock_data)\n r = np.subtract(np.asarray(t_stock_data[len(t_stock_data) - 1], dtype = float),np.asarray(t_stock_data[0], dtype = float))\n (MLE_avg, MLE_var) = MLE_params(stock_data)\n s_and_p = np.mean(MLE_avg)\n beta = js.getBeta(r, t_stock_data, s_and_p)\n \ndef MLE_params(matrix):\n means = []\n variances = []\n \n for vector in matrix:\n vector_mean = np.mean(vector.astype(float))\n means.append(vector_mean)\n var = []\n for elem in vector:\n var.append((float(elem) - float(vector_mean))**2)\n variances.append(np.mean(var))\n return (means, variances)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rgdagir/cme240","sub_path":"assign1.py","file_name":"assign1.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19826509948","text":"import unittest\nfrom unittest.mock import patch\n\nimport attr\n\nfrom recidiviz.common.constants.states import StateCode\nfrom recidiviz.ingest.direct.raw_data.raw_file_configs import (\n DirectIngestRawFileConfig,\n RawDataClassification,\n RawTableColumnFieldType,\n RawTableColumnInfo,\n)\nfrom recidiviz.ingest.direct.regions.direct_ingest_region_utils import (\n get_existing_direct_ingest_states,\n)\nfrom recidiviz.ingest.direct.types.direct_ingest_instance import DirectIngestInstance\nfrom recidiviz.ingest.direct.views.direct_ingest_latest_view_collector import (\n DirectIngestRawDataTableLatestViewBuilder,\n DirectIngestRawDataTableLatestViewCollector,\n)\nfrom recidiviz.tests.ingest.direct.fakes.fake_direct_ingest_controller import (\n FakeDirectIngestRegionRawFileConfig,\n)\n\nNON_HISTORICAL_LATEST_VIEW_QUERY = \"\"\"\nWITH filtered_rows AS (\n SELECT\n * EXCEPT (recency_rank)\n FROM (\n SELECT\n *,\n ROW_NUMBER() OVER (PARTITION BY col1, col2\n ORDER BY update_datetime DESC, CAST(seq_num AS INT64)) AS recency_rank\n FROM\n `recidiviz-456.us_xx_raw_data.table_name`\n \n ) a\n WHERE\n recency_rank = 1\n AND is_deleted = False\n)\nSELECT col1, col2\nFROM filtered_rows\n\"\"\"\n\n\nHISTORICAL_LATEST_VIEW_QUERY = \"\"\"\nWITH max_update_datetime AS (\n SELECT\n MAX(update_datetime) AS update_datetime\n FROM\n `recidiviz-456.us_xx_raw_data.table_name`\n \n),\nmax_file_id AS (\n SELECT\n MAX(file_id) AS file_id\n FROM\n `recidiviz-456.us_xx_raw_data.table_name`\n WHERE\n update_datetime = (SELECT update_datetime FROM max_update_datetime)\n),\nfiltered_rows AS (\n SELECT *\n FROM\n `recidiviz-456.us_xx_raw_data.table_name`\n WHERE\n file_id = (SELECT file_id FROM max_file_id)\n)\nSELECT col1, col2\nFROM filtered_rows\n\"\"\"\n\n\nclass DirectIngestRawDataTableLatestViewBuilderTest(unittest.TestCase):\n \"\"\"Tests DirectIngestRawDataTableLatestViewBuilder\"\"\"\n\n def setUp(self) -> None:\n self.project_id = \"recidiviz-456\"\n self.metadata_patcher = patch(\"recidiviz.utils.metadata.project_id\")\n self.mock_project_id_fn = self.metadata_patcher.start()\n self.mock_project_id_fn.return_value = self.project_id\n self.raw_file_config = DirectIngestRawFileConfig(\n file_tag=\"table_name\",\n file_path=\"path/to/file.yaml\",\n file_description=\"file description\",\n data_classification=RawDataClassification.SOURCE,\n primary_key_cols=[\"col1\", \"col2\"],\n columns=[\n RawTableColumnInfo(\n name=\"col1\",\n field_type=RawTableColumnFieldType.STRING,\n is_pii=False,\n description=\"col1 description\",\n ),\n RawTableColumnInfo(\n name=\"col2\",\n field_type=RawTableColumnFieldType.STRING,\n is_pii=False,\n description=\"col2 description\",\n ),\n ],\n supplemental_order_by_clause=\"CAST(seq_num AS INT64)\",\n encoding=\"any-encoding\",\n separator=\"@\",\n custom_line_terminator=None,\n ignore_quotes=False,\n always_historical_export=False,\n no_valid_primary_keys=False,\n import_chunk_size_rows=10,\n infer_columns_from_config=False,\n table_relationships=[],\n )\n\n def tearDown(self) -> None:\n self.metadata_patcher.stop()\n\n def test_build_latest_view(self) -> None:\n view = DirectIngestRawDataTableLatestViewBuilder(\n region_code=\"us_xx\",\n raw_data_source_instance=DirectIngestInstance.PRIMARY,\n raw_file_config=self.raw_file_config,\n ).build(address_overrides=None)\n\n self.assertEqual(self.project_id, view.project)\n self.assertEqual(\"us_xx_raw_data_up_to_date_views\", view.dataset_id)\n self.assertEqual(\"table_name_latest\", view.table_id)\n self.assertEqual(\"table_name_latest\", view.view_id)\n\n self.assertEqual(NON_HISTORICAL_LATEST_VIEW_QUERY, view.view_query)\n self.assertEqual(\n \"SELECT * FROM `recidiviz-456.us_xx_raw_data_up_to_date_views.table_name_latest`\",\n view.select_query,\n )\n self.assertTrue(view.should_deploy())\n\n def test_build_historical_file_latest_view(self) -> None:\n raw_file_config = attr.evolve(\n self.raw_file_config, always_historical_export=True\n )\n view = DirectIngestRawDataTableLatestViewBuilder(\n region_code=\"us_xx\",\n raw_data_source_instance=DirectIngestInstance.PRIMARY,\n raw_file_config=raw_file_config,\n ).build(address_overrides=None)\n\n self.assertEqual(self.project_id, view.project)\n self.assertEqual(\"us_xx_raw_data_up_to_date_views\", view.dataset_id)\n self.assertEqual(\"table_name_latest\", view.table_id)\n self.assertEqual(\"table_name_latest\", view.view_id)\n\n self.assertEqual(HISTORICAL_LATEST_VIEW_QUERY, view.view_query)\n self.assertEqual(\n \"SELECT * FROM `recidiviz-456.us_xx_raw_data_up_to_date_views.table_name_latest`\",\n view.select_query,\n )\n self.assertTrue(view.should_deploy())\n\n def test_build_no_primary_keys_no_throw(self) -> None:\n for no_valid_primary_keys in (True, False):\n raw_file_config = attr.evolve(\n self.raw_file_config,\n # primary_key_cols=[] is allowed for any value of no_valid_primary_keys\n primary_key_cols=[],\n no_valid_primary_keys=no_valid_primary_keys,\n )\n if no_valid_primary_keys:\n # If no_valid_primary_keys is explicitly set to True, then this config\n # does count as documented\n self.assertFalse(raw_file_config.is_undocumented)\n else:\n self.assertTrue(raw_file_config.is_undocumented)\n\n _ = DirectIngestRawDataTableLatestViewBuilder(\n region_code=\"us_xx\",\n raw_data_source_instance=DirectIngestInstance.PRIMARY,\n raw_file_config=raw_file_config,\n ).build(address_overrides=None)\n\n def test_build_primary_keys_nonempty_no_throw(self) -> None:\n raw_file_config = attr.evolve(\n self.raw_file_config,\n primary_key_cols=[\"col1\"],\n no_valid_primary_keys=False,\n )\n\n _ = DirectIngestRawDataTableLatestViewBuilder(\n region_code=\"us_xx\",\n raw_data_source_instance=DirectIngestInstance.PRIMARY,\n raw_file_config=raw_file_config,\n ).build(address_overrides=None)\n\n def test_build_primary_keys_throw(self) -> None:\n with self.assertRaisesRegex(\n ValueError,\n r\"Incorrect primary key setup found for file_tag=table_name: `no_valid_primary_keys`=True and \"\n r\"`primary_key_cols` is not empty: \\['primary_key'\\]\",\n ):\n _ = attr.evolve(\n self.raw_file_config,\n primary_key_cols=[\"primary_key\"],\n no_valid_primary_keys=True,\n )\n\n def test_build_no_documented_columns_throws(self) -> None:\n # Columns with no documentation\n raw_file_config = attr.evolve(\n self.raw_file_config,\n always_historical_export=True,\n columns=[\n RawTableColumnInfo(\n name=\"col1\",\n field_type=RawTableColumnFieldType.STRING,\n is_pii=False,\n description=None,\n ),\n RawTableColumnInfo(\n name=\"col2\",\n field_type=RawTableColumnFieldType.STRING,\n is_pii=False,\n description=None,\n ),\n ],\n )\n with self.assertRaisesRegex(\n ValueError,\n r\"Found no available \\(documented\\) columns for file \\[table_name\\]\",\n ):\n _ = DirectIngestRawDataTableLatestViewBuilder(\n region_code=\"us_xx\",\n raw_data_source_instance=DirectIngestInstance.PRIMARY,\n raw_file_config=raw_file_config,\n ).build(address_overrides=None)\n\n def test_build_no_columns_throws(self) -> None:\n # Config with no columns\n raw_file_config = attr.evolve(\n self.raw_file_config,\n always_historical_export=True,\n columns=[],\n primary_key_cols=[],\n )\n with self.assertRaisesRegex(\n ValueError,\n r\"Found no available \\(documented\\) columns for file \\[table_name\\]\",\n ):\n _ = DirectIngestRawDataTableLatestViewBuilder(\n region_code=\"us_xx\",\n raw_data_source_instance=DirectIngestInstance.PRIMARY,\n raw_file_config=raw_file_config,\n ).build(address_overrides=None)\n\n\nclass DirectIngestRawDataTableLatestViewCollectorTest(unittest.TestCase):\n \"\"\"Tests DirectIngestRawDataTableLatestViewCollector\"\"\"\n\n def setUp(self) -> None:\n self.project_id = \"recidiviz-456\"\n self.metadata_patcher = patch(\"recidiviz.utils.metadata.project_id\")\n self.mock_project_id_fn = self.metadata_patcher.start()\n self.mock_project_id_fn.return_value = self.project_id\n\n def tearDown(self) -> None:\n self.metadata_patcher.stop()\n\n def test_collect_latest_view_builders(self) -> None:\n with patch(\n \"recidiviz.ingest.direct.views.direct_ingest_latest_view_collector.DirectIngestRegionRawFileConfig\",\n ) as config_cls:\n config_cls.return_value = FakeDirectIngestRegionRawFileConfig(\n StateCode.US_XX.value\n )\n collector = DirectIngestRawDataTableLatestViewCollector(\n StateCode.US_XX.value, DirectIngestInstance.PRIMARY\n )\n\n builders = collector.collect_view_builders()\n self.assertCountEqual(\n [\n \"tagFullyEmptyFile_latest\",\n \"tagHeadersNoContents_latest\",\n \"tagBasicData_latest\",\n \"tagMoreBasicData_latest\",\n # Excludes tagWeDoNotIngest which has no documented columns\n ],\n [b.view_id for b in builders],\n )\n\n def test_collect_latest_view_builders_all(self) -> None:\n for state_code in get_existing_direct_ingest_states():\n collector = DirectIngestRawDataTableLatestViewCollector(\n state_code.value, DirectIngestInstance.PRIMARY\n )\n\n # Just make sure we don't crash\n _ = collector.collect_view_builders()\n","repo_name":"Recidiviz/pulse-data","sub_path":"recidiviz/tests/ingest/direct/views/direct_ingest_latest_view_collector_test.py","file_name":"direct_ingest_latest_view_collector_test.py","file_ext":"py","file_size_in_byte":10873,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"85"} +{"seq_id":"12975155274","text":"from typing import List\n\n\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n\n row_len = len(matrix)\n col_len = len(matrix[0])\n\n zero_col_flagged = False\n zero_row_flagged = False\n #determine if [0][0] is flagged\n for row in range(row_len):\n if matrix[row][0] == 0:\n zero_row_flagged = True\n for col in range(col_len):\n if matrix[0][col] == 0:\n zero_col_flagged = True\n\n # flag all rows and columns\n for row in range(1, row_len):\n for col in range(1, col_len):\n if matrix[row][col] == 0:\n matrix[0][col] = 0\n matrix[row][0] = 0\n\n # set columns\n if col_len > 1:\n # start at 1 to not overwrite the flags - yet\n for row in range(1, row_len):\n # if the column isn't flagged ignore it\n if matrix[row][0] != 0:\n continue\n for col in range(col_len):\n matrix[row][col] = 0\n\n # set rows\n if row_len > 1:\n # start at 1 to not overwrite the flags - yet\n for col in range(1, col_len):\n # if the row isn't flagged ignore it\n if matrix[0][col] != 0:\n continue\n for row in range(row_len):\n matrix[row][col] = 0\n\n # handle the flags columns and rows\n if zero_row_flagged:\n for row in range(row_len):\n matrix[row][0] = 0\n\n if zero_col_flagged:\n for col in range(col_len):\n matrix[0][col] = 0\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n\n input = [\n [1, 0, 1],\n [1, 1, 2]\n ]\n sol.setZeroes(input)\n assert input == [\n [0, 0, 0],\n [1, 0, 2]\n ]\n\n input = [\n [0, 1, 1],\n [1, 1, 2]\n ]\n sol.setZeroes(input)\n assert input == [\n [0, 0, 0],\n [0, 1, 2]\n ]\n\n input = [\n [1, 1, 1],\n [1, 0, 2]\n ]\n sol.setZeroes(input)\n assert input == [\n [1, 0, 1],\n [0, 0, 0]\n ]\n\n input = [\n [1, 1, 1],\n [0, 1, 2]\n ]\n sol.setZeroes(input)\n assert input == [\n [0, 1, 1],\n [0, 0, 0]\n ]\n\n input = [\n [1, 2, 3, 0, 5]\n ]\n sol.setZeroes(input)\n assert input == [\n [0, 0, 0, 0, 0]\n ]\n\n input = [\n [1],\n [2],\n [3],\n [0],\n [5]\n ]\n sol.setZeroes(input)\n assert input == [\n [0],\n [0],\n [0],\n [0],\n [0]\n ]\n\n input = [\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4, 5],\n [1, 2, 3, 0, 5],\n [1, 0, 3, 4, 5],\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4, 5],\n ]\n sol.setZeroes(input)\n assert input == [\n [1, 0, 3, 0, 5],\n [1, 0, 3, 0, 5],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [1, 0, 3, 0, 5],\n [1, 0, 3, 0, 5]\n ]\n\n input = [\n [0, 1, 2, 0],\n [3, 4, 5, 2],\n [1, 3, 1, 5]\n ]\n sol.setZeroes(input)\n assert input == [\n [0, 0, 0, 0],\n [0, 4, 5, 0],\n [0, 3, 1, 0]\n ]\n","repo_name":"ejwessel/LeetCodeProblems","sub_path":"73_SetMatrixZeroes/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26304250534","text":"import re\nfrom bs4 import BeautifulSoup\nfrom bs4 import Comment\n\ndef get_tag_index(tag_name, start_index, content):\n bFound = False\n iter_char = start_index\n iter_char_end = len(content)\n tag_pointer_start = 0\n tag_pointer_end = len(tag_name)\n state = 0\n start_index = -1\n while iter_char < iter_char_end:\n if state == 0:\n if tag_name[tag_pointer_start] == content[iter_char]:\n tag_pointer_start = 1\n state = 1\n elif state == 1:\n if tag_name[tag_pointer_start] == content[iter_char]:\n tag_pointer_start += 1\n if tag_pointer_start == tag_pointer_end:\n bFound = True\n break\n else:\n tag_pointer_start = 0\n state = 0 \n iter_char += 1\n return bFound, iter_char - tag_pointer_end, iter_char + 1\n\nclass HTMLParse:\n def __init__(self, filename):\n self.filename = filename\n self.tags_to_skip = []\n self.tags_to_consolidate = ['a', 'b', 'font', 'div'] \n self.consolidated_name = 'X'\n \n def parse_children(self, parent_tag, root_key, html_parts, tag):\n if tag.name is not None and tag.name not in self.tags_to_skip and tag.contents is not None:\n child_tag = parent_tag\n if tag.name not in self.tags_to_consolidate:\n child_tag += tag.name + \"/\"\n root_key += 1\n #print('[{}:{}]: {}'.format(root_key, child_tag, \"has_children\"))\n for children in tag.contents:\n if not isinstance(children, Comment):\n root_key = self.parse_children(child_tag, root_key, html_parts, children)\n else:\n if tag.string is not None and len(tag.string.strip()) > 0:\n #print('[{}:{}]: {}'.format(root_key, parent_tag, tag.string.strip()))\n data = tag.string.strip()\n if root_key not in html_parts:\n html_parts[root_key] = {}\n if parent_tag not in html_parts[root_key]:\n html_parts[root_key][parent_tag] = data\n else:\n html_parts[root_key][parent_tag] += ' ' + data\n return root_key\n\n def get_html_parts(self):\n html_parts = {}\n with open(self.filename) as fp:\n soup = BeautifulSoup(fp, \"html5lib\") \n root_key = 0\n for tag in soup.body.contents: \n if tag.name is not None and tag.contents is not None:\n #print('[{}:{}]: {}'.format(root_key, tag.name, \"has_children\"))\n root_key = self.parse_children('/', root_key, html_parts, tag)\n root_key += 1\n return html_parts\n\n def remove_nonascii_string(self, s):\n return re.sub(r'[^\\x00-\\x7f]',r' ', s)\n \n def get_cleaned_string(self, s):\n toRet = self.remove_nonascii_string(s).replace('\\n', ' ').lower().strip()\n if toRet.startswith('i tem '):\n toRet = toRet.replace('i tem ', 'item ')\n return toRet\n \n def get_form_parts(self, html_parts):\n form_parts = {}\n part_key = ''\n item_key = ''\n for key in html_parts:\n for tag in html_parts[key]:\n data = html_parts[key][tag]\n cleaned_data = self.get_cleaned_string(data)\n #print('[{}:{}]: #{}#'.format(key, tag, cleaned_data[0:10]))\n if cleaned_data.startswith('part '):\n part_key = cleaned_data\n item_key = ''\n form_parts[part_key] = {}\n elif cleaned_data.startswith('item '):\n if part_key == '' and cleaned_data.startswith('item 1'):\n part_key = \"PART_INS\"\n form_parts[part_key] = {}\n if part_key != '':\n item_key = cleaned_data\n form_parts[part_key][item_key] = []\n else:\n if part_key != '' and item_key != '':\n if part_key in form_parts and item_key in form_parts[part_key]:\n form_parts[part_key][item_key].append(self.remove_nonascii_string(data))\n return form_parts\n \n def parse_html(self, cik, filingdt):\n print('...parsing: {}'.format(self.filename))\n parsed_data = {}\n parsed_data['cik'] = cik\n parsed_data['filingdt'] = filingdt \n parsed_data['fullpath'] = self.filename \n html_parts = self.get_html_parts()\n form_parts = self.get_form_parts(html_parts) \n parsed_data['text'] = form_parts \n return parsed_data\n","repo_name":"hussainbohra/edgar","sub_path":"daizika/utils/ParserUtils.py","file_name":"ParserUtils.py","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"23819233983","text":"# 간단한 다익스트라 알고리즘\n# 시간복잡도 O(V^2), V는 노드 개수\n\nimport sys\ninput = sys.stdin.readline\nINF = int(1e9) \n\nn, m = map(int, input().split()) # 노드 개수, 간선 개수 입력\nstart = int(input()) # 시작노드 입력\ngraph = [[] for i in range(n+1)] # 노드 정보 리스트, 인덱스 번호와 맞추기 위해 크기는 n+1로\nvisited = [False] * (n+1) # 방문 기록\ndistance = [INF] * (n+1) # 최단거리 기록\n\nfor _ in range(m):\n a, b, c = map(int, input().split()) # a번 노드에서 b번 노드로 가는 비용이 c\n graph[a].append((b,c))\n\ndef get_smallest_node():\n min_value = INF\n index = 0\n for i in range(1, n+1):\n if distance[i] < min_value and not visited[i]:\n min_value = distance[i]\n index = i\n return index\n\ndef dijkstra(start):\n distance[start] = 0\n visited[start] = True\n for j in graph[start]:\n distance[j[0]] = j[1] # j[0]은 시작 노드와 연결된 노드 번호, j[1]은 그 노드로 가는 비용\n for i in range(n-1):\n now = get_smallest_node()\n visited[now] = True\n for j in graph[now]:\n cost = distance[now] + j[1]\n if cost < distance[j[0]]:\n distance[j[0]] = cost\n\ndijkstra(start)\n\nfor i in range(1, n+1):\n if distance[i] == INF:\n print(\"INFINITY\")\n else:\n print(distance[i])","repo_name":"juhan-y/Algorithm_Study","sub_path":"이민지/[지난회차]/[7주차]최단경로/9-1.py","file_name":"9-1.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"71683546838","text":"import logging\r\n\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport xarray as xr\r\n\r\nfrom ..handler import add_handler\r\n\r\nlogger = logging.getLogger(__name__)\r\nlogger = add_handler(logger)\r\n\r\n\r\nclass Plotting(object):\r\n @staticmethod\r\n def imshow(\r\n data,\r\n mask=False,\r\n nodata=0,\r\n flip=False,\r\n text_color='black',\r\n rot=30,\r\n **kwargs\r\n ):\r\n\r\n \"\"\"Shows an image on a plot.\r\n\r\n Args:\r\n data (``xarray.DataArray`` or ``xarray.Dataset``): The data to plot.\r\n mask (Optional[bool]): Whether to mask 'no data' values (given by ``nodata``).\r\n nodata (Optional[int or float]): The 'no data' value.\r\n flip (Optional[bool]): Whether to flip an RGB array's band order.\r\n text_color (Optional[str]): The text color.\r\n rot (Optional[int]): The degree rotation for the x-axis tick labels.\r\n kwargs (Optional[dict]): Keyword arguments passed to ``xarray.plot.imshow``.\r\n\r\n Returns:\r\n ``matplotlib`` axis object\r\n\r\n Examples:\r\n >>> import geowombat as gw\r\n >>>\r\n >>> # Open a 3-band image and plot the first band\r\n >>> with gw.open('image.tif') as ds:\r\n >>> ax = ds.sel(band=1).gw.imshow()\r\n >>>\r\n >>> # Open and plot a 3-band image\r\n >>> with gw.open('image.tif') as ds:\r\n >>>\r\n >>> ax = ds.sel(band=['red', 'green', 'blue']).gw.imshow(mask=True,\r\n >>> nodata=0,\r\n >>> vmin=0.1,\r\n >>> vmax=0.9,\r\n >>> robust=True)\r\n \"\"\"\r\n\r\n if data.gw.nbands != 1:\r\n\r\n if data.gw.nbands != 3:\r\n logger.exception(\r\n ' Only 1-band or 3-band arrays can be plotted.'\r\n )\r\n\r\n plt.rcParams['axes.titlesize'] = 5\r\n plt.rcParams['axes.titlepad'] = 5\r\n plt.rcParams['text.color'] = text_color\r\n plt.rcParams['axes.labelcolor'] = text_color\r\n plt.rcParams['xtick.color'] = text_color\r\n plt.rcParams['ytick.color'] = text_color\r\n plt.rcParams['figure.dpi'] = kwargs['dpi'] if 'dpi' in kwargs else 150\r\n plt.rcParams['savefig.bbox'] = 'tight'\r\n plt.rcParams['savefig.pad_inches'] = 0.5\r\n\r\n if 'ax' not in kwargs:\r\n fig, ax = plt.subplots()\r\n kwargs['ax'] = ax\r\n\r\n ax = kwargs['ax']\r\n\r\n if mask:\r\n\r\n if isinstance(data, xr.Dataset):\r\n\r\n if data.gw.nbands == 1:\r\n plot_data = data.where(\r\n (data['mask'] < 3) & (data != nodata)\r\n )\r\n else:\r\n plot_data = data.where(\r\n (data['mask'] < 3) & (data.max(axis=0) != nodata)\r\n )\r\n\r\n else:\r\n\r\n if data.gw.nbands == 1:\r\n plot_data = data.where(data != nodata)\r\n else:\r\n plot_data = data.where(data.max(axis=0) != nodata)\r\n\r\n else:\r\n plot_data = data\r\n\r\n if plot_data.gw.nbands == 3:\r\n\r\n plot_data = plot_data.transpose('y', 'x', 'band')\r\n\r\n if flip:\r\n plot_data = plot_data[..., ::-1]\r\n\r\n plot_data.plot.imshow(rgb='band', **kwargs)\r\n\r\n else:\r\n plot_data.squeeze().plot.imshow(**kwargs)\r\n\r\n ax.xaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))\r\n ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))\r\n\r\n for tick in ax.get_xticklabels():\r\n tick.set_rotation(rot)\r\n\r\n return ax\r\n","repo_name":"jgrss/geowombat","sub_path":"src/geowombat/util/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","stars":152,"dataset":"github-code","pt":"85"} +{"seq_id":"35978348640","text":"# -*- coding: utf-8 -*-\n\nimport calendar\nimport datetime\nimport itertools\nimport math\nimport unittest\nfrom cronexp._day_field import DayOfMonthField, day_of_month_w\n\n\nclass DayOfMonthWTest(unittest.TestCase):\n def test_weekday(self):\n self.assertEqual(day_of_month_w(14, 2019, 2), 14)\n\n def test_saturday(self):\n self.assertEqual(day_of_month_w(23, 2019, 11), 22)\n\n def test_sunday(self):\n self.assertEqual(day_of_month_w(11, 2019, 8), 12)\n\n def test_1st(self):\n self.assertEqual(day_of_month_w(1, 2019, 6), 3)\n\n def test_last(self):\n self.assertEqual(day_of_month_w(31, 2019, 3), 29)\n\n\nclass DayOfMonthFieldTest(unittest.TestCase):\n def test_normal(self):\n field = DayOfMonthField('*/5', non_standard=False)\n year = 2019\n for month, day in itertools.product(\n range(1, 13),\n (None, *range(1, 32))):\n lastday = calendar.monthrange(year, month)[1]\n expected = math.ceil(day / 5) * 5 + 1 if day is not None else 1\n if expected is not None and expected > lastday:\n expected = None\n with self.subTest(year=year, month=month, day=day):\n self.assertEqual(field.next(year, month, day), expected)\n\n def test_blank(self):\n field = DayOfMonthField('?', non_standard=True)\n self.assertTrue(field.is_blank)\n date = datetime.date(year=2019, month=1, day=1)\n self.assertEqual(field.next(date.year, date.month, date.day), None)\n\n def test_l(self):\n field = DayOfMonthField('15,L', non_standard=True)\n year = 2019\n for month, day in itertools.product(\n range(1, 13),\n (None, *range(1, 32))):\n lastday = calendar.monthrange(year, month)[1]\n with self.subTest(year=year, month=month, day=day):\n self.assertEqual(\n field.next(year, month, day),\n 15 if day is None or day < 15\n else lastday if day < lastday\n else None)\n\n def test_w(self):\n field = DayOfMonthField('10W,20W,30W', non_standard=True)\n year = 2019\n expected_table = [\n [10, 21, 30], # 2019/01\n [11, 20, 28], # 2019/02\n [11, 20, 29], # 2019/03,\n [10, 19, 30], # 2019/04\n [10, 20, 30], # 2019/05\n [10, 20, 28], # 2019/06\n [10, 19, 30], # 2019/07\n [9, 20, 30], # 2019/08\n [10, 20, 30], # 2019/09\n [10, 21, 30], # 2019/10\n [11, 20, 29], # 2019/11\n [10, 20, 30]] # 2019/12\n for month, day in itertools.product(\n range(1, 13),\n (None, *range(1, 32))):\n expected = None\n for x in expected_table[month - 1]:\n if day is None or x > day:\n expected = x\n break\n with self.subTest(year=year, month=month, day=day):\n self.assertEqual(field.next(year, month, day), expected)\n\n def test_next(self):\n field = DayOfMonthField('*/5,11W,21W,L', non_standard=True)\n year = 2019\n expected_table = [\n [1, 6, 11, 16, 21, 26, 31], # 2019/01\n [1, 6, 11, 16, 21, 26, 28], # 2019/02\n [1, 6, 11, 16, 21, 26, 31], # 2019/03\n [1, 6, 11, 16, 21, 22, 26, 30], # 2019/04\n [1, 6, 10, 11, 16, 21, 26, 31], # 2019/05\n [1, 6, 11, 16, 21, 26, 30], # 2019/06\n [1, 6, 11, 16, 21, 22, 26, 31], # 2019/07\n [1, 6, 11, 12, 16, 21, 26, 31], # 2019/08\n [1, 6, 11, 16, 20, 21, 26, 30], # 2019/09\n [1, 6, 11, 16, 21, 26, 31], # 2019/10\n [1, 6, 11, 16, 21, 26, 30], # 2019/11\n [1, 6, 11, 16, 20, 21, 26, 31]] # 2019/12\n for month, day in itertools.product(\n range(1, 13),\n (None, *range(1, 32))):\n expected = None\n for x in expected_table[month - 1]:\n if day is None or x > day:\n expected = x\n break\n with self.subTest(year=year, month=month, day=day):\n self.assertEqual(field.next(year, month, day), expected)\n","repo_name":"085astatine/cronexp","sub_path":"test/test_day_field.py","file_name":"test_day_field.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30715718886","text":"\"\"\"\nBasis Set Expansion \n--------------------\n\nThe BAsis Set Expansion (BASEX) method is a way of approximating an unknown\nfunction using a fixed number of known functions. The method determines\nthe basis set coefficients that approximate the unknown function best. Using\nknown functions may provide an easy way to perform analysis and transformations. \nIt was shown that the method is very useful for inverse abel transformations\nhttp://link.aip.org/link/?RSINAK/73/2634/1 .\n\nTypically a simple function with varying parameter is used to build the basis\nset, but the method does not limit the choice of the functions in any way.\nAlso the number of functions may be varied, although it is fixed to the number\nof points to approximate in most applications. Another parameter is the\nregulatization parameter 'q' that affects the approximation. You may want\nto play around with it for optimal results, but q=1e-3 seems to be a good\ninitial choice.\n\nA key feature of the BASEX is the way the basis coefficients are calculated.\nYou can analyze multiple datasets without recalculating the basis if the size is\nfixed, which makes this method very fast.\n\"\"\"\n\nimport numpy as np\n\nclass RadialGaussBasex:\n \"\"\"\n Create a BASEX analyzer based on gaussian functions for\n radial function analysis.\n \n This class implements the BASEX method by using 1d gauss functions\n with varying width as basis set. All functions are centered at zero,\n so it works best for functions with high amplitude at zero and that\n are vanishing for large distances.\n \n An inverse abel transofmation is also implemented by using the\n BASEX coefficients from abel integrated data.\n \n :param nr: (int) Number of points to analyze.\n :param dr: (float) Distance between points to analyze\n :param q: (float) Regularization parameter.\n \n Example::\n \n # some measured abel transformed data\n data = ...\n \n # try to reconstruct function from data \n basex = RadialGaussBasex(nr=data.size, q=1e-3)\n coeffs = basex.analyze(data)\n data_basex = basex.synthesize(coeffs)\n data_basex_inv = basex.synthesizeInvAbel(coeffs)\n \n For another example see the :func:`test_basex` method in :mod:`qao.analysis.basex`.\n \"\"\"\n \n def __init__(self, nr, dr=1.0, q = 1e-3):\n # array for radial position values\n self.r = np.arange(nr, dtype=float) * dr\n r = self.r.reshape([nr, 1])\n \n # array for basis function indices\n nk = r.size-1\n k = np.arange(1, nk+1).reshape([1, nk])\n # calculate basis functions\n sig_step = 1./r.size * np.max(r)\n sig = sig_step * k\n self.sig = sig\n self.basis = np.exp(-r**2 / (2*(sig)**2))\n \n # calculate the basis expansion matrix\n B = self.basis\n A = np.dot(B, B.transpose()) + q*np.eye(nr)\n A = np.dot(B.transpose(), np.linalg.inv(A))\n \n self.expansionMatrix = A\n self.nk = nk\n self.nr = nr\n \n def analyze(self, data):\n \"\"\"\n Determine the BASEX coefficients for `data`.\n \n The data is assumed to be a linear spaced unknown function f(x),\n with the first point being at r=0. The number of points and\n the spacing is given by the parameters when instancing the class.\n \n The approximation of the unknown function is calculated by\n :func:`synthesize`.\n \n :param data: (ndarray) Data to be approximated.\n :returns: (ndarray) BASEX coefficients.\n \"\"\"\n f = data.reshape([self.nr, 1])\n C = np.dot(self.expansionMatrix, f)\n return C.ravel()\n \n def synthesize(self, coeffs):\n \"\"\"\n Reconstruct an approximated function from coefficients.\n \n Calculate and return the approximated function from coefficients\n determined by the :func:`analyze` method.\n \n :param coeffs: (ndarray) Array of coefficients for this basis.\n :returns: (ndarray) Reconstructed function.\n \"\"\"\n B = self.basis\n f = np.dot(B, coeffs.reshape([self.nk, 1]))\n return f.ravel()\n\n def synthesizeInvAbel(self, coeffs):\n \"\"\"\n Reconstruct the inverse abel transformation from coefficients.\n \n For an BASEX approximated unknown function, calculate the inverse\n abel transformation from coefficients.\n \n :param coeffs: (ndarray) Array of coefficients for this basis.\n :returns: (ndarray) Reconstructed inverse abel function.\n \"\"\"\n # for inverse gaussian abel, we just have to change\n # the weights of the coefficients\n coeffs = coeffs * 1./np.sqrt(2*np.pi)/self.sig\n return self.synthesize(coeffs)\n\n def sythesizeDeriv(self, coeffs):\n \"\"\"\n Reconstruct the derivative df/dr from coefficients\n \"\"\"\n coeffs = - coeffs / self.sig**2\n deriv = self.r * self.synthesize(coeffs)\n\n return deriv\n \n\ndef test_basex():\n import pylab as p\n from matplotlib.gridspec import GridSpec\n \n # generate a radial test function\n n = 300\n Y, X = np.ogrid[-1.:1.:1j*n, 0.:1.:1j*n/2]\n dx, dy = X[0,1]-X[0,0], Y[1,0]-Y[0,0]\n R = np.sqrt(X**2 + Y**2)\n normal = lambda x, sig, amp: amp*np.exp(-.5*x**2/sig**2)\n radial_func = lambda r: normal(r, .25, 4.0) - normal(r, .1, 1.0)*(4*np.sin(r*30))\n \n # generate data from function\n data_2d = radial_func(R) + (np.random.random(R.shape)-.5)*1.0\n data_r = (radial_func(X)).ravel()\n data_abel = data_2d.sum(axis=0) * dy\n \n # try to guess data_r from data_abel\n basex = RadialGaussBasex(nr=data_abel.size, dr=dx, q=1e-3)\n coeffs = basex.analyze(data_abel)\n data_abel_s = basex.synthesize(coeffs)\n data_r_s = basex.synthesizeInvAbel(coeffs)\n data_abel_ds = basex.sythesizeDeriv(coeffs)\n \n #p.imshow(function_2d)\n x = X.ravel()\n p.figure(figsize=(10,7))\n gs = GridSpec(3, 2)\n gs.update(hspace=.4)\n ax = p.subplot(gs[0,0])\n ax.set_axis_off()\n ax.set_title(\"2d data from radial-func\")\n ax.imshow(np.hstack((data_2d[:,::-1], data_2d)))\n \n ax = p.subplot(gs[0,1])\n ax.set_title(\"y-integrated data\")\n ax.plot(x, data_abel, \"k-\", label=\"data\")\n ax.plot(x, data_abel_s, \"r-\", label=\"basex\")\n ax.set_xlabel(\"x position\")\n ax.set_ylabel(\"line density\")\n ax.set_ylim(ymin=0)\n ax.legend()\n \n ax = p.subplot(gs[1,0:2])\n ax.set_title(\"inverse abel transformation from basex coefficients\")\n ax.plot(x, data_r, \"b-\", label=\"original function\")\n ax.plot(x, data_r_s, \"r-\", label=\"inverse abel\")\n ax.set_xlabel(\"radius\")\n ax.set_ylabel(\"density\")\n ax.legend()\n\n ax = p.subplot(gs[2,0:2])\n ax.set_title(\"derivative from basex coefficients\")\n ax.plot(x, data_abel_s, \"b-\", label=\"original function\")\n ax = p.twinx()\n ax.plot(x, data_abel_ds, \"r-\", label=\"derivative\")\n ax.set_xlabel(\"radius\")\n ax.set_ylabel(\"density\")\n ax.legend()\n\n p.show()\n\nif __name__ == '__main__':\n test_basex()\n \n \n \n ","repo_name":"pwuertz/qao","sub_path":"src/qao/analysis/basex.py","file_name":"basex.py","file_ext":"py","file_size_in_byte":7110,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"20174047192","text":"#%% Conexion\n\"\"\"\nXAMPP\ninit $sudo /opt/lampp/lampp start\n\ninit GUI $cd /opt/lampp\n $sudo ./manager-linux.run \n $sudo ./manager-linux-x64.run\n\nstop $sudo /opt/lampp/lampp stop\n\"\"\"\n\nimport mysql.connector\nDatabase = mysql.connector.connect(host = \"localhost\",\n user = \"root\",\n password = \"\",\n database=\"master_python\")\n\n#config = {\"host\":\"localhost\",\"user\":\"root\",\"passwd\":''}\n#Database = mysql.connector.connect(**config)\n#La conexion ha sido correcta \nprint(Database)\n\ncursor = Database.cursor(buffered=True) #-->Consultas ilimitadass\n#%% Crear base de datos\ncursor.execute(\"CREATE DATABASE IF NOT EXISTS master_python\")\ncursor.execute(\"SHOW DATABASES\")\n\nfor bd in cursor:\n print(bd)\n\n#%% CREAR TABLA\ncursor .execute(\"\"\"\nCREATE TABLE IF NOT EXISTS vehiculos(\n id int(10) auto_increment not null,\n marca varchar(40) not null,\n modelo varchar(40) not null,\n precio float(10,2) not null,\n CONSTRAINT pk_vihiculo PRIMARY KEY(id)\n)\n\"\"\")\ncursor.execute(\"SHOW TABLES\")\nfor tabla in cursor:\n print(tabla)\n\n#%% INSERTAR DATOS\ncursor.execute(\"INSERT INTO vehiculos VALUES(null,'Opel','Astra',18500)\")\nDatabase.commit()\n#Database.close()\n\n#%% INSERTAR DATOS MASIVOS\ncoches = [\n ('Seat','Ibiza',5000),\n ('Renault','Clio',1500),\n ('Citroen','Saxo',20000),\n ('Mercedes','Clase C',35000)\n ]\ncursor.executemany(\"INSERT INTO vehiculos VALUES(null,%s,%s,%s)\",coches)\nDatabase.commit()\n# %% CONSULTA\ncursor.execute(\"SELECT * FROM vehiculos\")\nresult = cursor.fetchall() #--> Devuelve un tuple\n\nprint(\"---------COCHES-----------\")\nfor coche in result:\n print(coche)\n\n\n# %% BORRAR Y ACTUALIZAR REGISTROS\ncursor.execute(\"DELETE FROM vehiculos WHERE marca = 'Mercedes' \")\nDatabase.commit()\n\nprint(cursor.rowcount,\"Borrados!!\") # rowcount --> Muestra numero de borrados\n\n# %% ACTUALIZAR\ncursor.execute(\"UPDATE vehiculos SET modelo='Leon' WHERE marca='Seat'\")\nDatabase.commit()\n\nprint(cursor.rowcount,\"Actualizados!\")\n# %%\n","repo_name":"larj3852/Curso_Python","sub_path":"19 - DB_SQL/MySQL.py","file_name":"MySQL.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"25224476534","text":"import pandas as pd\r\nfrom math import exp, factorial\r\nfrom datetime import datetime, timedelta\r\n\r\nclass Player:\r\n latest = 2018\r\n season_length = 38\r\n assistPoints = 3\r\n yellowPoints = -1\r\n redPoints = -3\r\n owngoalPoints = -2\r\n plus60Points = 2\r\n sub60Points = 1\r\n\r\n def __init__(self, data, overview, fixtures):\r\n self.latest = Player.latest\r\n self.gameweeks = Player.season_length\r\n self._convert_data_to_attr(data)\r\n self.matches = self._extract_matches(fixtures)\r\n self.overview = self._extract_overview(overview)\r\n self.games_played = self._get_games_played()\r\n self.goalsPerMatch = self.actual_goals_per_match()\r\n self.assistsPerMatch = self.assists_per_match()\r\n self.Position = self.actual_position()\r\n self.probability_of_appearance()\r\n self.cards()\r\n self.calc_own_goals()\r\n self.assistPoints = Player.assistPoints\r\n self.yellowPoints = Player.yellowPoints\r\n self.redPoints = Player.redPoints\r\n self.owngoalPoints = Player.owngoalPoints\r\n self.plus60Points = Player.plus60Points\r\n self.sub60Points = Player.sub60Points\r\n\r\n def _convert_data_to_attr(self, data):\r\n \"\"\"Converts data (dict) to object attributes\"\"\"\r\n for k, v in data.items():\r\n setattr(self, k, v)\r\n\r\n def _extract_overview(self, df):\r\n \"\"\"extracts apps, subs and goals per season and\r\n saves as dictionary, in YM# (Year Minus) format\"\"\"\r\n dct = {}\r\n try:\r\n for season in df.Season.unique():\r\n season_int = int(season[:4])\r\n ym = 'ym{}'.format(self.latest - season_int)\r\n Season = df[df.Season == season]\r\n apps = sum(Season.Apps)\r\n subs = sum(Season.Subs)\r\n goals = sum(Season.Goals)\r\n dct[ym] = (apps, subs, goals)\r\n except AttributeError:\r\n season = df.Season\r\n season_int = int(season[:4])\r\n ym = 'ym{}'.format(self.latest - season_int)\r\n apps = df.Apps\r\n subs = df.Subs\r\n goals = df.Goals\r\n dct[ym] = (apps, subs, goals)\r\n return dct\r\n \r\n\r\n def _extract_matches(self, df):\r\n # df.set_index('id', inplace=True)\r\n mask = (df['team_h'] == self.team) | (df['team_a'] == self.team)\r\n return df[mask].to_dict('index')\r\n\r\n def _get_games_played(self):\r\n count = 0\r\n for k, v in self.matches.items():\r\n if v['finished'] == 'true':\r\n count += 1\r\n return count\r\n \r\n\r\n def aggregate_overview_stats(self, seasons=['ym0','ym1']):\r\n \"\"\"\r\n Input: \r\n - seasons -- seasons to aggregate (list)\r\n - self.overview -- all season data (dict)\r\n \r\n Returns dict containing:\r\n - sum of appearances (apps)\r\n - sum of substitutions (subs)\r\n - sum of goals (goals)\r\n - calculated sum of missed appearances (missed)\r\n \"\"\"\r\n dct = {'apps': 0, 'subs': 0, 'missed': 0, 'goals': 0}\r\n for ym in self.overview.keys(): \r\n if ym in seasons:\r\n apps, subs, goals = self.overview[ym]\r\n if ym == 'ym0':\r\n missed = self.games_played - apps\r\n else:\r\n missed = self.season_length - apps\r\n if dct['apps'] + apps > 38:\r\n continue\r\n dct['apps'] += apps\r\n dct['subs'] += subs\r\n dct['missed'] += missed\r\n dct['goals'] += goals\r\n \r\n return dct\r\n\r\n def probAppearance(self, match_id):\r\n return self.matches[match_id]['probAppearance']\r\n\r\n def probability_of_appearance(self):\r\n agg = self.aggregate_overview_stats()\r\n apps = agg['apps']\r\n subs = agg['subs']\r\n missed = agg['missed']\r\n total = apps + missed\r\n chance, return_date = self.check_news()\r\n app_rate = apps / total if total != 0 else 0\r\n self.appRate = app_rate\r\n sub_rate = subs / total if total != 0 else 0\r\n start_rate = (apps - subs) / total if total != 0 else 0\r\n for k,v in self.matches.items(): \r\n kickoff_time = self.matches[k]['kickoff_time']\r\n kickoff_date = kickoff_time.split('T')[0]\r\n kickoff = datetime.strptime(kickoff_date, '%Y-%m-%d')\r\n prob = chance if kickoff < return_date else 1\r\n self.matches[k]['probAppearance'] = prob * app_rate\r\n self.matches[k]['probSub'] = prob * sub_rate\r\n self.matches[k]['probStart'] = prob * start_rate\r\n\r\n def check_news(self):\r\n today = datetime.today()\r\n chance = self.chance_of_playing_next_round / 100\r\n status = self.status\r\n return_date = lambda weeks: today + timedelta(weeks=weeks)\r\n if status == 'i': # injury with unknown return date\r\n return (chance, return_date(4))\r\n elif status == 'u': # transferred or on loan (0%)\r\n return (chance, return_date(52))\r\n elif status == 'd': # chance of playing\r\n return (chance, return_date(2))\r\n elif status == 'n':\r\n return (chance, return_date(15))\r\n elif status == 's':\r\n return (chance, return_date(3))\r\n else:\r\n return (100, today)\r\n\r\n \r\n @staticmethod\r\n def poisson(l, x, eq='eq'):\r\n \"\"\"\r\n Maps probability to poisson distribution\r\n\r\n Input:\r\n - l -- lambda representing rate\r\n - x -- target value from which to determine probability\r\n - eq -- equality in relation to x ('eq','gte','lte')\r\n\r\n Returns probability (float from 0 to 1)\r\n \"\"\"\r\n f = lambda x,l: exp(-l) * l**x / factorial(x)\r\n if eq == 'eq':\r\n return f(x,l)\r\n elif eq == 'lte':\r\n return sum([f(X,l) for X in range(x+1)])\r\n elif eq == 'gte':\r\n return 1 - sum([f(X,l) for X in range(x)])\r\n \r\n\r\n def cards(self):\r\n \"\"\"\r\n Determines probabilities for getting red/yellow cards\r\n\r\n Lumps all yellow and red cards together, then uses Poisson\r\n Distribution to determine probability of getting 1 or 2 cards.\r\n 2 cards can be assumed to be the equivilent of a Red card.\r\n \"\"\"\r\n yellows = getattr(self, 'Yellow Cards')\r\n reds = getattr(self, 'Red Cards')\r\n total = yellows + reds\r\n\r\n try:\r\n l = total / self.Appearances\r\n except ZeroDivisionError:\r\n l = 0\r\n self.P_red = self.poisson(l, 2)\r\n self.P_yellow = self.poisson(l, 1)\r\n\r\n def calc_own_goals(self):\r\n \"\"\"\r\n Determines probability for scoring an own goal\r\n \"\"\"\r\n own = getattr(self, 'Own Goals')\r\n try:\r\n P_ownGoal = own / self.Appearances\r\n except ZeroDivisionError:\r\n P_ownGoal = 0\r\n self.P_ownGoal = P_ownGoal\r\n \r\n def actual_goals_per_match(self):\r\n delattr(self, 'Goals Per Match')\r\n try:\r\n return self.Goals / self.Appearances\r\n except ZeroDivisionError:\r\n return 0\r\n\r\n def assists_per_match(self):\r\n try:\r\n return self.Assists / self.Appearances\r\n except ZeroDivisionError:\r\n return 0\r\n\r\n def actual_position(self):\r\n positions = {1: 'GoalKeeper',\r\n 2: 'Defender',\r\n 3: 'Midfielder',\r\n 4: 'Forward'}\r\n return positions[self.element_type]\r\n \r\n\r\n def probability_of_goals(self, match_id, weight, X=3):\r\n l = self.goalsPerMatch * weight\r\n f = self.poisson\r\n probGoalScored = [(x, f(l,x)) for x in range(X+1)]\r\n return probGoalScored\r\n\r\n def add_match_data(self, match_id, key, data):\r\n self.matches[match_id][key] = data\r\n\r\n def get_match_data(self, match_id, key):\r\n return self.matches[match_id][key]\r\n\r\n def _resolve(self, *funcs):\r\n for match_id, match in self.matches.items():\r\n if match['finished'] == True:\r\n continue\r\n points = sum([f(match) for f in funcs])\r\n points *= match['probAppearance']\r\n self.matches[match_id]['initialPoints'] = points\r\n\r\n def time_played(self, match):\r\n \"\"\"estimate over/under 60mins based on whether started match \r\n or was a sub\"\"\"\r\n start = match['probStart'] * self.plus60Points\r\n sub = match['probSub'] * self.sub60Points\r\n return start + sub\r\n\r\n def goal_assists(self, match):\r\n return match['assistRate'] * self.assistPoints\r\n\r\n def card_points(self, _):\r\n reds = self.P_red * self.redPoints\r\n yellows = self.P_yellow * self.yellowPoints\r\n return reds + yellows \r\n \r\n def own_goal_points(self, _):\r\n return self.P_ownGoal * self.owngoalPoints\r\n\r\n def goal_points(self, match):\r\n P = lambda x: self.poisson(match['goalRate'], x)\r\n return self.goalPoints * sum([P(x)*x for x in [1,2,3,4,5]])\r\n \r\n def clean_sheet(self, match):\r\n return self.poisson(match['probConcede'], 0) * self.cleanPoints\r\n\r\n def conceded(self, match):\r\n return self.poisson(match['probConcede'], 2, eq='gte') \\\r\n * self.concededPoints \r\n\r\n def resolve_BPS(self, match_id):\r\n match = self.matches[match_id]\r\n initial = match['initialPoints']\r\n rank = match['BPSrank']\r\n bps = 0 if rank > 3 else 4 - rank\r\n # improved by spreading BPS across players\r\n bps *= self.probAppearance(match_id)\r\n match['finalPoints'] = initial + bps\r\n\r\n def _calculate_BPS(self, *funcs):\r\n for match_id, match in self.matches.items():\r\n if match['finished'] == True:\r\n continue\r\n points = sum([f(match) for f in funcs])\r\n points *= match['probAppearance']\r\n self.matches[match_id]['bonusPoints'] = points\r\n\r\n def BPS_goal_points(self, match):\r\n P = lambda x: self.poisson(match['goalRate'], x)\r\n return self.BPSgoalPoints * sum([P(x)*x for x in [1,2,3,4,5]])\r\n\r\n def BPS_clean_sheet(self, match):\r\n return self.poisson(match['probConcede'], 0) * self.BPScleanPoints\r\n\r\n\r\nclass GoalKeeper(Player):\r\n goalPoints = 6\r\n cleanPoints = 4\r\n concededPoints = -1\r\n \r\n def __init__(self, data, overview, fixtures):\r\n super().__init__(data, overview, fixtures)\r\n self.concededPerMatch = self._calculate_concede_rate()\r\n self.goalPoints = GoalKeeper.goalPoints\r\n self.cleanPoints = GoalKeeper.cleanPoints\r\n self.concededPoints = GoalKeeper.concededPoints\r\n self.BPSgoalPoints = 12\r\n self.BPScleanPoints = 12\r\n \r\n def _calculate_concede_rate(self):\r\n conceded = getattr(self, 'Goals Conceded')\r\n appearances = getattr(self, 'Appearances')\r\n try:\r\n return conceded / appearances\r\n except ZeroDivisionError:\r\n return 0\r\n \r\n def resolve(self):\r\n self._resolve(self.time_played, \r\n self.goal_assists, \r\n self.card_points,\r\n self.own_goal_points,\r\n self.goal_points,\r\n self.clean_sheet,\r\n self.conceded)\r\n\r\n def calculate_BPS(self):\r\n self._calculate_BPS(self.BPS_goal_points,\r\n self.BPS_clean_sheet)\r\n\r\n def __eq__(self, compare):\r\n if compare == 'GoalKeeper':\r\n return True\r\n else:\r\n return False\r\n \r\nclass Forward(Player):\r\n goalPoints = 4\r\n \r\n def __init__(self, data, overview, fixtures):\r\n super().__init__(data, overview, fixtures)\r\n self.goalPoints = Forward.goalPoints\r\n self.BPSgoalPoints = 24\r\n\r\n def resolve(self):\r\n self._resolve(self.time_played, \r\n self.goal_assists, \r\n self.card_points,\r\n self.own_goal_points,\r\n self.goal_points)\r\n\r\n def calculate_BPS(self):\r\n self._calculate_BPS(self.BPS_goal_points)\r\n\r\n def __eq__(self, compare):\r\n if compare == 'Forward':\r\n return True\r\n else:\r\n return False\r\n\r\nclass Midfielder(Player):\r\n goalPoints = 5\r\n cleanPoints = 1\r\n \r\n def __init__(self, data, overview, fixtures):\r\n super().__init__(data, overview, fixtures)\r\n self.goalPoints = Midfielder.goalPoints\r\n self.cleanPoints = Midfielder.cleanPoints\r\n self.BPSgoalPoints = 18\r\n\r\n def resolve(self):\r\n self._resolve(self.time_played, \r\n self.goal_assists, \r\n self.card_points,\r\n self.own_goal_points,\r\n self.goal_points,\r\n self.clean_sheet)\r\n \r\n def calculate_BPS(self):\r\n self._calculate_BPS(self.BPS_goal_points)\r\n\r\n def __eq__(self, compare):\r\n if compare == 'Midfielder':\r\n return True\r\n else:\r\n return False\r\n \r\n\r\nclass Defender(Player):\r\n goalPoints = 6\r\n cleanPoints = 4\r\n concededPoints = -1\r\n \r\n def __init__(self, data, overview, fixtures):\r\n super().__init__(data, overview, fixtures)\r\n self.concededPerMatch = self._calculate_concede_rate()\r\n self.goalPoints = Defender.goalPoints\r\n self.cleanPoints = Defender.cleanPoints\r\n self.concededPoints = Defender.concededPoints\r\n self.BPSgoalPoints = 12\r\n self.BPScleanPoints = 12\r\n\r\n def _calculate_concede_rate(self):\r\n conceded = getattr(self, 'Goals Conceded')\r\n appearances = getattr(self, 'Appearances')\r\n try:\r\n return conceded / appearances\r\n except ZeroDivisionError:\r\n return 0\r\n \r\n\r\n def resolve(self):\r\n self._resolve(self.time_played, \r\n self.goal_assists, \r\n self.card_points,\r\n self.own_goal_points,\r\n self.goal_points,\r\n self.clean_sheet,\r\n self.conceded)\r\n\r\n def calculate_BPS(self):\r\n self._calculate_BPS(self.BPS_goal_points,\r\n self.BPS_clean_sheet)\r\n\r\n def __eq__(self, compare):\r\n if compare == 'Defender':\r\n return True\r\n else:\r\n return False","repo_name":"rick-62/FPL","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":14672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42256305614","text":"import random\nimport torch\nimport networkx as nx\n\nfrom graphxai.datasets.feature import make_structured_feature\n\ndef net_stats_generator(G):\n '''\n Args:\n G (nx.Graph): \n '''\n deg_cent = nx.degree_centrality(G)\n def get_feature(node_idx):\n return torch.tensor([G.degree[node_idx], \n nx.clustering(G, node_idx), \n deg_cent[node_idx]]).float()\n\n return get_feature\n\ndef random_continuous_generator(len_vector = 3):\n '''\n Generate random continuous vectors of length given\n Args:\n len_vector (int): Length of vectors to generate\n\n :rtype: Callable[[int], torch.Tensor]\n - Return is a function that takes integer and outputs vector\n '''\n def get_feature(node_idx):\n # Random random Gaussian feature vector:\n return torch.normal(mean=0, std=1.0, size = (len_vector,))\n return get_feature\n\ndef random_onehot_generator(len_vector):\n '''\n Generate random onehot vectors of length given\n Args:\n len_vector (int): Length of vectors to generate\n\n :rtype: Callable[[int], torch.Tensor]\n - Return is a function that takes integer and outputs vector\n '''\n def get_feature(node_idx):\n # Random one-hot feature vector:\n feature = torch.zeros(3)\n feature[random.choice(range(3))] = 1\n return feature\n return get_feature\n\ndef gaussian_lv_generator(\n G: nx.Graph, \n yvals: torch.Tensor, \n n_features: int = 10, \n flip_y: float = 0.01,\n class_sep: float = 1.0,\n n_informative: int = 4,\n n_clusters_per_class: int = 2,\n seed = None):\n '''\n Args:\n G (nx.Graph): \n yvals (torch.Tensor): \n seed (seed): (:default: :obj:`None`)\n '''\n\n x, feature_imp_true = make_structured_feature(\n yvals, \n n_features = n_features,\n n_informative = n_informative, \n flip_y = flip_y,\n class_sep=class_sep,\n n_clusters_per_class=n_clusters_per_class,\n seed = seed)\n\n Gitems = list(G.nodes.items())\n node_map = {Gitems[i][0]:i for i in range(G.number_of_nodes())}\n\n def get_feature(node_idx):\n return x[node_map[node_idx],:]\n\n return get_feature, feature_imp_true\n","repo_name":"mims-harvard/GraphXAI","sub_path":"graphxai/datasets/utils/feature_generators.py","file_name":"feature_generators.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"85"} +{"seq_id":"36439877391","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\nimport datetime\nfrom djangocore.apps.exemplo.models import ExemploModel\n\n\n\n\nclass ExemploForm(forms.ModelForm):\n\n class Meta:\n model = ExemploModel\n fields = ('nome', 'apelido')\n widgets = {\n 'nome': forms.TextInput(attrs={'class': 'form-control', 'size': '50'}),\n 'apelido': forms.TextInput(attrs={'class': 'form-control', 'size': '50'}),\n\n\n\n }\n labels = {\n 'nome': _('Nome'),\n 'apelido': _('Apelido'),\n }\n","repo_name":"tfs4/ifg_start","sub_path":"djangocore/apps/exemplo/forms/FormExemplo.py","file_name":"FormExemplo.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31777343438","text":"from collections import defaultdict\nimport math\n\n\ndef k_diff_pairs(nums,k):\n k_diff_pair = []\n nums = sorted(nums)\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if nums[i]+k==nums[j]:\n k_diff_pair.append((nums[i],nums[j]))\n elif nums[i]+k < nums[j]:\n break\n\n \n return len(set(k_diff_pair))\n\n\n\nif __name__ == '__main__':\n nums=[1,2,3,4,5]\n k=1\n \n print(k_diff_pairs(nums,k))\n\n","repo_name":"aditigupta16/Algorithms-DataStructures","sub_path":"array/k_diff_pairs.py","file_name":"k_diff_pairs.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"32864334867","text":"from django.urls import path, include\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\nurlpatterns = [\n path('', views.news, name='news'),\n path('', include('django.contrib.auth.urls')),\n path('register/', views.register, name='register'),\n path('edit/', views.edit, name='edit'),\n path('users/', views.user_list, name='user_list'),\n path('users/follow/', views.user_follow, name='user_follow'),\n path('users//', views.user_detail, name='user_detail'),\n path('i_follow/', views.i_follow, name='i_follow'),\n path('edit_mypage/', views.edit_mypage, name='edit_mypage'),\n path('delete_profile/', views.delete_profile, name='delete_profile'),\n path('confirm_delete_profile/', views.confirm_delete_profile, name='confirm_delete_profile'),\n]\n\n","repo_name":"hlmats/artnet","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1551091280","text":"import datetime\nimport requests\nimport json\nimport logging\n\nfrom django.conf import settings\n\n\nQUERY_URL = \"https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=%s&near=%s&query=%s\"\n\n\ndef make_request(query, location):\n\n url = build_url(query, location)\n\n r = requests.get(url)\n\n try:\n return json.loads(r.text)[\"response\"][\"venues\"]\n except Exception as e:\n logging.error(\"json exception: \" + str(e))\n return []\n\n\ndef build_url(query, location):\n\n date = datetime.datetime.now().strftime('%Y%m%d')\n\n return QUERY_URL % (\n settings.FOURSQUARE[\"client_id\"], \n settings.FOURSQUARE[\"client_secret\"],\n date,\n location,\n query\n )\n","repo_name":"luterien/FoursquareClient","sub_path":"client/foursquare.py","file_name":"foursquare.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"11106815937","text":"from django import views\nfrom django.urls import path\nfrom . import views \n\napp_name = 'test_app'\n\nurlpatterns = [\n path('', views.Index.as_view(), name = 'index'),\n path('add', views.Add.as_view(), name = 'add'),\n path('person', views.People.as_view(), name = 'person'),\n path('all_person', views.All_Person.as_view(), name = 'all_person')\n]","repo_name":"raffay2001/A-Simple-Django-CRUD-Application","sub_path":"test_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23897607058","text":"#!/usr/bin/python3\n\nimport cgi \nimport cgitb \n \nf = open(\"index.shtml\", \"r\")\nuser_input = open(\"user_input\", 'w')\npage = f.read()\nform = cgi.FieldStorage()\n\nv = form.getvalue(\"guess\")\nif(v):\n user_input.write(v)\n user_input.close()\n print(\"Content-type: text/html\\n\\n\")\n print(page)\n print(\"You typed:\\n\")\n print()\n print(v)\n","repo_name":"janeclange/codenames","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"43843389474","text":"from collections import deque\n\ndef solution(tickets):\n tickets.sort(key=lambda x: x[1])\n start_indexes = [start_index for start_index in range(len(tickets)) if tickets[start_index][0] == \"ICN\"]\n answer = 0\n for start_index in start_indexes:\n if answer:\n continue\n dq = deque([[start_index]])\n while dq:\n cur_idxs = dq.popleft()\n if len(cur_idxs) == len(tickets):\n answer = [tickets[x][0] for x in cur_idxs] + [tickets[cur_idxs[-1]][1]]\n break\n cur_idx = cur_idxs[-1]\n for idx in range(len(tickets)):\n if idx not in cur_idxs and tickets[cur_idx][1] == tickets[idx][0]:\n dq.append(cur_idxs+[idx])\n return answer","repo_name":"sungchan1/CodingTest-solve","sub_path":"여행경로.py","file_name":"여행경로.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32692599796","text":"from pathlib import Path\nimport re\nfrom datasets import load_dataset\nimport torch.utils.data\nfrom transformers import TrainingArguments\nfrom segue.configuration_segue import SegueConfig\nfrom segue.modeling_segue import SegueModel\nfrom segue.processing_segue import SegueProcessor\nfrom custom_trainer import CustomTrainer\n\nclass LibriSpeechDatasetAdapter(torch.utils.data.Dataset):\n def __init__(self, hf_librispeech, processor: SegueProcessor, compute_loss: bool):\n self.hf_librispeech = hf_librispeech\n self.processor = processor\n self.compute_loss = compute_loss\n\n def __getitem__(self, index):\n hf_data = self.hf_librispeech[index]\n inputs = self.processor(\n text = hf_data['text'],\n audio = hf_data['audio']['array'],\n sampling_rate = hf_data['audio']['sampling_rate'],\n )\n inputs['compute_loss'] = self.compute_loss\n return inputs\n \n def __len__(self):\n return len(self.hf_librispeech)\n\ndef main():\n hf_dev_set = torch.utils.data.ConcatDataset([\n load_dataset('librispeech_asr', split='validation.clean', cache_dir='data/hf_datasets'),\n load_dataset('librispeech_asr', split='validation.other', cache_dir='data/hf_datasets'),\n ])\n\n checkpoints_dir = Path(\"output/2023-02-08-final\")\n checkpoint_range = range(120_000, 145_000)\n pattern = re.compile('checkpoint-(\\d*)')\n # model = SegueModel.from_pretrained(checkpoints_dir / 'averaged')\n config = SegueConfig()\n avg_model = SegueModel(config)\n avg_model.requires_grad_(False)\n for param in avg_model.parameters():\n param.zero_()\n n_checkpoints = 0\n for checkpoint_path in checkpoints_dir.iterdir():\n match = pattern.match(checkpoint_path.name)\n if match is None or int(match.group(1)) not in checkpoint_range:\n continue\n print(\"Using checkpoint:\", checkpoint_path.name)\n model = SegueModel.from_pretrained(checkpoint_path)\n for (param_sum, param) in zip(avg_model.parameters(), model.parameters()):\n param_sum += param\n n_checkpoints += 1\n del model\n for param in avg_model.parameters():\n param /= n_checkpoints\n avg_model.save_pretrained(checkpoints_dir / 'averaged')\n model = avg_model\n\n dev_set = LibriSpeechDatasetAdapter(hf_dev_set, model.processor, True)\n\n training_args = TrainingArguments(\n output_dir='output/2023-02-08-final',\n learning_rate=3e-5,\n num_train_epochs=10,\n evaluation_strategy='steps',\n per_device_train_batch_size=8,\n per_device_eval_batch_size=1,\n logging_dir='output/2023-02-08-final',\n warmup_steps=5000,\n save_steps=5000,\n logging_steps=100,\n eval_steps=5000,\n load_best_model_at_end=True,\n )\n trainer = CustomTrainer(\n model=model,\n args=training_args,\n eval_dataset=dev_set,\n tokenizer=model.processor,\n )\n metrics = trainer.evaluate()\n print(metrics)\n\nif __name__ == '__main__':\n main()\n","repo_name":"declare-lab/segue","sub_path":"pretrain_avg.py","file_name":"pretrain_avg.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"7367818163","text":"import shutil\nimport os \nimport datetime\nimport glob\n\nclass FileManager:\n\n def archive_desktop_files(self, base_path):\n files = self._get_desktop_files_list()\n base_path = os.path.expanduser(base_path)\n for fil in files:\n self._move_to_appropriate_folder(fil, base_path)\n\n def _get_desktop_files_list(self):\n desktop_path = os.path.expanduser(\"~/Desktop/*\")\n files = [f for f in glob.glob(desktop_path) if os.path.isfile(f) or os.path.isdir(f)]\n return files\n \n def _move_to_appropriate_folder(self, source, base_path):\n path = self._assemble_destination_name(base_path)\n if not os.path.isdir(path):\n os.makedirs(path)\n shutil.move(source, path)\n\n def _assemble_destination_name(self, base_path):\n date = str(datetime.datetime.today().strftime('%Y-%m-%d'))\n path = os.path.join(base_path, date)\n return path","repo_name":"eryktr/desktop-archiver","sub_path":"file_manager/file_manager.py","file_name":"file_manager.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28038273023","text":"from app.models import db, Comment, environment, SCHEMA\nfrom sqlalchemy.sql import text\n\ndef seed_comments():\n comment1 = Comment(\n content=\"Seashells are beautiful\", userId=1, postId=3\n )\n comment2 = Comment(\n content=\"wow this is fantastic\", userId=1, postId=10,\n )\n comment3 = Comment(\n content=\"Japan is just so cool\", userId=2, postId=1\n )\n comment4 = Comment(\n content=\"Fall weather is my favorite\", userId=2, postId=5\n )\n comment5 = Comment(\n content=\"frankenstein, my favorite book!\", userId=1, postId=7\n )\n comment6 = Comment(\n content=\"The colors in this image are simply stunning\", userId=3, postId=6\n )\n comment7 = Comment(\n content=\"Stars always amazed me тнР\", userId=1, postId=4\n )\n\n db.session.add(comment1)\n db.session.add(comment2)\n db.session.add(comment3)\n db.session.add(comment4)\n db.session.add(comment5)\n db.session.add(comment6)\n db.session.add(comment7)\n db.session.commit()\n\ndef undo_comments():\n if environment == \"production\":\n db.session.execute(f\"TRUNCATE table {SCHEMA}.comments RESTART IDENTITY CASCADE;\")\n else:\n db.session.execute(text(\"DELETE FROM comments\"))\n \n db.session.commit()","repo_name":"jennlangley/tumblr-clone","sub_path":"app/seeds/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73942789397","text":"##!/usr/bin/env python\r\n\r\n\r\nfrom __future__ import absolute_import\r\nfrom setuptools import setup, find_packages\r\n\r\nVERSION = '0.0.1'\r\n\r\nrequirements = [\r\n 'tensorflow>=2.0.0',\r\n 'numpy>=1.17.0'\r\n]\r\n\r\n\r\nsetup(\r\n # Metadata\r\n name='sparsenet',\r\n version=VERSION,\r\n author='Weijun Luo',\r\n author_email='luo_weijun@yahoo.com',\r\n url='https://github.com/datapplab/sparsenet',\r\n description='Implementation of sparse neural networks',\r\n # long_description=readme,\r\n # long_description_content_type='text/markdown',\r\n license='GPLv3',\r\n\r\n # Package info\r\n packages=find_packages(),\r\n\r\n #\r\n zip_safe=True,\r\n install_requires=requirements,\r\n python_requires='>=3.6',\r\n\r\n # Classifiers\r\n classifiers=[\r\n 'Programming Language :: Python :: 3',\r\n 'Operating System :: OS Independent', \r\n ]\r\n)","repo_name":"datapplab/sparsenet","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"73034438678","text":"from pico2d import *\nimport random\n\n\n# Game object class here\nclass Grass:\n def __init__(self):\n self.image = load_image('grass.png')\n\n def draw(self):\n self.image.draw(400, 30)\n\n def update(self):\n pass\n\n\nclass Boy:\n def __init__(self):\n self.x, self.y = random.randint(100, 700), 90\n self.frame = random.randint(0, 7)\n self.image = load_image('run_animation.png')\n\n def draw(self):\n self.image.clip_draw(self.frame * 100, 0, 100, 100, self.x, self.y)\n\n def update(self):\n self.frame = (self.frame + 1) % 8\n self.x += 5\n\n\nclass SmallBall:\n def __init__(self):\n self.x, self.y = random.randint(0, 800), 599\n self.frame = random.randint(0, 7)\n self.image = load_image('ball21x21.png')\n\n def draw(self):\n self.image.draw(self.x, self.y)\n\n def update(self):\n if self.y > 50:\n self.y -= random.randint(1, 10)\n\n\nclass BigBall:\n def __init__(self):\n self.x, self.y = random.randint(0, 800), 599\n self.frame = random.randint(0, 7)\n self.image = load_image('ball41x41.png')\n\n def draw(self):\n self.image.draw(self.x, self.y)\n\n def update(self):\n if self.y > 60:\n self.y -= random.randint(1, 10)\n\n\ndef handle_events():\n global running\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n running = False\n elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:\n running = False\n\n\ndef reset_world():\n global running\n global grass\n global team\n global smallball\n global bigball\n global world\n\n running = True\n world = []\n\n grass = Grass()\n world.append(grass)\n\n team = [Boy() for i in range(10)]\n world += team\n\n smallball_num = random.randint(0, 20)\n bigball_num = 20 - smallball_num\n\n smallball = [SmallBall() for i in range(smallball_num)]\n world += smallball\n\n bigball = [BigBall() for i in range(bigball_num)]\n world += bigball\n\n\ndef update_world():\n for o in world:\n o.update()\n\n\ndef render_world():\n clear_canvas()\n for o in world:\n o.draw()\n update_canvas()\n\n\nopen_canvas()\n\n# initialization code\nreset_world()\n\n# game main loop code\nwhile running:\n handle_events()\n update_world()\n render_world()\n delay(0.05)\n\n# finalization code\nclose_canvas()\n","repo_name":"sojoonghan2/2DGameProgramming","sub_path":"Drill08/boy_grass_object.py","file_name":"boy_grass_object.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31557581116","text":"# [0. 날짜]\n# 2021.07.17(토요일)\n# 문제 유형: 위상정렬\n# 걸린 시간:\n# [1. 문제의 간단한 해법과 함께 어떤 방식으로 접근했는지]\n# 1. 주어진 비교를 통해 graph 생성\n# 2. DFS를 통해 탐색 후 끝에서부터 돌아오면서\n# [2. 문제의 해법을 찾는데 결정적이었던 깨달음은 무엇이었는지]\n#\n# [3. +개선 사항]\n#\n# [4. +한번에 맞추지 못한 경우 오답 원인 적기]\n\nfrom collections import defaultdict\nimport sys\n\nsys.setrecursionlimit(100000)\n\n\ndef dfs(start_node, visited):\n if len(graph[start_node]) == 0:\n res.append(start_node)\n return\n for con_node in graph[start_node]:\n if visited[con_node]:\n continue\n visited[con_node] = True\n dfs(con_node, visited)\n res.append(start_node)\n\n\ndef solution():\n visited = [False for v in range(N + 1)]\n for start_node in range(1, N + 1):\n if in_degree[start_node] == 0:\n dfs(start_node, visited)\n\n\nN, M = map(int, input().split())\ngraph = defaultdict(list)\nin_degree = [0 for t in range(N + 1)]\nfor _ in range(M):\n a, b = map(int, input().split())\n graph[a].append(b)\n in_degree[b] += 1\n\nres = []\nsolution()\nfor i in range(N - 1, -1, -1):\n print(res[i], end=\" \")\n","repo_name":"hyunjune-lee/python_algorithm_interview","sub_path":"코딩테스트 대비를 위한 백준 문제 추천/BOJ_2252 - 줄 세우기.py","file_name":"BOJ_2252 - 줄 세우기.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"1782700109","text":"import os\nimport numpy as np\nimport pandas as pd\nimport argparse\nfrom schrodinger import structure\n\n# ## Define input variables\nparser = argparse.ArgumentParser()\nparser.add_argument('docking_data', default=None, help='CSV file containing docking data.')\nparser.add_argument('docking_folder', default=None, help='Docking output folder')\nparser.add_argument('--separator', default=None, help='Separator used to write PDB files')\nparser.add_argument('--ligand_chain', default='L', help='Chain used for the ligand residue')\nparser.add_argument('--ligand_resnum', default=1, help='REsidue index used for the ligand residue')\n\nargs=parser.parse_args()\ndocking_data = args.docking_data\ndocking_folder = args.docking_folder\nseparator = args.separator\nligand_chain = args.ligand_chain\nligand_resnum = int(args.ligand_resnum)\n\n# Read dockign data to pandas\ndocking_data = pd.read_csv(docking_data)\ndocking_data.set_index(['Protein', 'Ligand', 'Pose'], inplace=True)\n\n# Get models list\nposes = {}\nfor i in docking_data.index:\n model, ligand, pose = i\n if model not in poses:\n poses[model] = {}\n if ligand not in poses[model]:\n poses[model][ligand] = []\n poses[model][ligand].append(pose)\n\n# Get path to output files\nsubjobs = {}\nmae_output = {}\nfor model in os.listdir(docking_folder+'/output_models'):\n if os.path.isdir(docking_folder+'/output_models/'+model):\n subjobs[model] = {}\n mae_output[model] = {}\n for f in os.listdir(docking_folder+'/output_models/'+model):\n if 'subjobs.log' in f:\n ligand = f.replace(model+'_','').replace('_subjobs.log','')\n subjobs[model][ligand] = docking_folder+'/output_models/'+model+'/'+f\n elif f.endswith('.maegz'):\n ligand = f.replace(model+'_','').replace('_pv.maegz','')\n mae_output[model][ligand] = docking_folder+'/output_models/'+model+'/'+f\n\n# Get and save selected docking poses to PDB\nfor model in poses:\n if not os.path.exists(str(model)):\n os.mkdir(str(model))\n for ligand in poses[model]:\n for pose,st in enumerate(structure.StructureReader(mae_output[str(model)][ligand])):\n if 'r_i_glide_gscore' in st.property:\n if pose in poses[model][ligand]:\n for residue in st.residue:\n residue.chain = ligand_chain\n residue.resnum = ligand_resnum\n\n complex = protein.merge(st)\n output_pdb = str(model)+separator+ligand+separator+str(pose)+'.pdb'\n PDBWriter = structure.PDBWriter(str(model)+'/'+output_pdb)\n PDBWriter.write(complex)\n else:\n protein = st\n","repo_name":"Martin-Floor/prepare_proteins","sub_path":"prepare_proteins/scripts/extract_docking.py","file_name":"extract_docking.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"34740569429","text":"import matplotlib.pyplot as plt\r\nimport cv2\r\n\r\n\r\nsource = r\"D:\\ML\\Mini Project\\Test3\\1\\2.jpg\"\r\n\r\nimage = cv2.imread(source)\r\nimage = cv2.resize(image, (30, 30), interpolation=cv2.INTER_LINEAR)\r\n#cv2.imshow(\"image\", image)\r\n#cv2.waitKey(0)\r\n\r\n\r\nax = plt.axes(projection='3d')\r\nax.scatter3D(image[:, 0], image[:, 1], image[:, 2], 'gray')\r\nplt.show()\r\n\r\n\"\"\"\r\nresize to 10x10 rgb\r\nfind the images with anomaly from data by looking at the indices of anomalous pixel examples in the map\r\n\"\"\"\r\n","repo_name":"tejalgupta05/Anomaly-Detection","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26644242323","text":"\nfrom tkinter import font\nfrom AssignmentMethod import AssignmentMethod\nfrom PatientAnticipativeMethod_Bulk import PatientAnticipativeMethod_Bulk\nfrom PatientAnticipativeMethod_Soft import PatientAnticipativeMethod_Soft\nfrom itertools import count\nfrom tabnanny import check\nimport time\nimport random\nfrom typing import Counter, Dict\nimport numpy as np\nfrom utils import dotdict\nfrom datetime import datetime, timedelta\nfrom Order import Order\nfrom Restaurant import Restaurant\nfrom Customer import Customer\nfrom Rider import Rider\nfrom OriginalAssignment import assign_order_to_rider\nfrom config import args\nimport pickle\nimport pandas as pd\nfrom EventQueue import EventQueue\nfrom Event import Event\nfrom DefaultMethod_1b import DefaultMethod_1b\nimport matplotlib.pyplot as plt\n\nclass Simulation():\n def __init__(self, method: AssignmentMethod,restaurant_list, rider_list, order_list, customer_list, order_time, args) -> None:\n self.args = args\n self.restaurant_list = restaurant_list\n self.rider_list = rider_list\n self.order_list = order_list\n self.customer_list = customer_list\n self.order_time = order_time\n self.method = method\n # Analysis: orders\n self.numDelivered = 0 # total number of orders delivered within this simulation\n # Analysis: ridrs\n self.rider_status_check_dict = {} # %of busy riders, checked at regular intervals\n # Analysis: waiting time\n self.wt_ls = [] # a list of waiting time, each element is the waiting time of an order\n \n # end of simulation\n self.t_termination = -1\n\n \n def simulate(self):\n\n '''\n This funtion performs 1 simulation, using 1 set of data\n consisting of rider list, restaurant list, customer list \n and order list.\n '''\n # Patient Anticipative Methods(Stalling Time involved)\n if self.method.__class__.__name__ == PatientAnticipativeMethod_Bulk.__name__:\n self.method.addRiderList(self.rider_list)\n '''Initialize regular check point'''\n checkpoint = EventQueue() \n initial_check = Event(0, 4, None)\n checkpoint.put(initial_check)\n \n '''Put in new orders event'''\n order_time_dict = {}\n self.order_list.sort()\n for o in self.order_list:\n order_time_dict[o.t] = o\n e = Event(o.t, 1, o)\n checkpoint.put(e)\n \n \n counter = 0\n \n stallingTime = args[\"stallingTime\"] # the first cutoff time for orders to be assigned\n # assign_pending_orders = Event(cutoff_time, 5, None)\n # checkpoint.put(assign_pending_orders)\n\n '''Start the Simulation'''\n while not checkpoint.empty():\n # see event type, update status\n currEvent = checkpoint.get()\n currEvent.addAssignmentMethod(self.method)\n\n # currEvent.print()\n currTime = currEvent.time\n \n if self.args[\"printCheckPt\"] and currEvent.cat != 4: pass\n # print(\"\\n 💥 checkpoint\", counter, \" time \", round(currTime,2), \"Event cat:\", currEvent.getCategory() ,\"\\n\")\n\n # check Event category, if it's a new order, tell it how to assign rider\n if currEvent.getCategory() == 'New Order':\n '''Start the stalling time window when a new order comes in '''\n \n if len(self.method.pending_order_dict) == 0:\n cutoff_time = currEvent.order.t + stallingTime\n\n assign_pending_orders = Event(cutoff_time, 5, None)\n checkpoint.put(assign_pending_orders)\n\n self.method.addPendingOrder(currEvent.order)\n #### debug\n # print(\"New order added, pending orders:\", len(self.method.pending_order_dict), \"at time\", currTime)\n\n elif currEvent.getCategory() == 'Match Pending Orders':\n # print(\"Match Pending Orders at time \", currTime)\n \n self.method.addCurrTime(currTime)\n # matching\n matched_res_dict = self.method.matchPendingOrders() # key: order, value: best rider\n #### debug\n # print(\"matched_res_dict:\")\n # for o, r in matched_res_dict.items():\n # print(o.index, r.index)\n\n # assign\n self.method.assignPendingOrders(matched_res_dict) # update status for rider and order\n # create new events for rider arrival and order delivered\n currEvent.addMatchedOrderRiderDict(matched_res_dict) # when exicute, update status for rider and order\n # clear pending orders\n self.method.clearPendingOrders()\n\n \n elif currEvent.getCategory() == 'Regular Check':\n currEvent.addRiderList(self.rider_list) \n currEvent.addStatusCheckDict(self.rider_status_check_dict)\n currEvent.passCurrQSize(checkpoint.qsize())\n currEvent.addProgramEndTime(self.t_termination)\n # print(\"Status check at\", currTime, \":\", self.status_check_dict.keys())\n \n elif currEvent.getCategory() == 'Order Delivered':\n \n self.numDelivered += 1\n # get total waiting time\n currOrder = currEvent.order\n wt = currOrder.wt\n self.wt_ls.append(wt)\n\n # execute current event:\n triggedEvent = currEvent.executeEvent(currTime)\n\n # if there is/are new events triggered, add to checkpoint\n if triggedEvent: \n for e in triggedEvent:\n checkpoint.put(e)\n\n counter += 1\n\n # # \n # elif self.method.__class__.__name__ == PatientAnticipativeMethod_Soft.__name__:\n # self.method.addRiderList(self.rider_list)\n # '''Initialize regular check point'''\n # checkpoint = EventQueue() \n # initial_check = Event(0, 4, None)\n # checkpoint.put(initial_check)\n\n # '''Put in new orders event'''\n # order_time_dict = {}\n # self.order_list.sort()\n # for o in self.order_list:\n # order_time_dict[o.t] = o\n # e = Event(o.t, 1, o)\n # checkpoint.put(e)\n\n # stallingTime = args[\"stallingTime\"] # the first cutoff time for orders to be assigned\n\n\n # '''Start the Simulation'''\n # while not checkpoint.empty():\n # # see event type, update status\n # currEvent = checkpoint.get()\n # currEvent.addAssignmentMethod(self.method)\n\n # # currEvent.print()\n # currTime = currEvent.time\n \n # if self.args[\"printCheckPt\"] and currEvent.cat != 4: pass\n # # print(\"\\n 💥 checkpoint\", counter, \" time \", round(currTime,2), \"Event cat:\", currEvent.getCategory() ,\"\\n\")\n\n # # check Event category, if it's a new order, tell it how to assign rider\n # if currEvent.getCategory() == 'New Order':\n # '''each order is assigned after the stalling time window'''\n \n # # for every new order, add a checkpoint event in the future\n # cutoff_time = currEvent.order.t + stallingTime\n\n # assign_pending_orders = Event(cutoff_time, 5, None)\n # checkpoint.put(assign_pending_orders)\n \n\n # self.method.addPendingOrder(currEvent.order)\n # #### debug\n # # print(\"New order added, pending orders:\", len(self.method.pending_order_dict), \"at time\", currTime)\n\n # elif currEvent.getCategory() == 'Match Pending Orders':\n # # print(\"Match Pending Orders at time \", currTime)\n \n # self.method.addCurrTime(currTime)\n # # matching\n # matched_res_dict = self.method.matchPendingOrders() # key: order, value: best rider\n # #### debug\n # # print(\"matched_res_dict:\")\n # # for o, r in matched_res_dict.items():\n # # print(o.index, r.index)\n\n # # assign\n # self.method.assignPendingOrders(matched_res_dict) # update status for rider and order\n # # create new events for rider arrival and order delivered\n # currEvent.addMatchedOrderRiderDict(matched_res_dict) # when exicute, update status for rider and order\n # # clear pending orders\n # self.method.clearPendingOrders()\n\n \n # elif currEvent.getCategory() == 'Regular Check':\n # currEvent.addRiderList(self.rider_list) \n # currEvent.addStatusCheckDict(self.rider_status_check_dict)\n # currEvent.passCurrQSize(checkpoint.qsize())\n # currEvent.addProgramEndTime(self.t_termination)\n # # print(\"Status check at\", currTime, \":\", self.status_check_dict.keys())\n \n # elif currEvent.getCategory() == 'Order Delivered':\n \n # self.numDelivered += 1\n # # get total waiting time\n # currOrder = currEvent.order\n # wt = currOrder.wt\n # self.wt_ls.append(wt)\n\n # # execute current event:\n # triggedEvent = currEvent.executeEvent(currTime)\n\n # # if there is/are new events triggered, add to checkpoint\n # if triggedEvent: \n # for e in triggedEvent:\n # checkpoint.put(e)\n\n # counter += 1\n\n \n # Immediate Assignment Methods\n else:\n\n self.method.addRiderList(self.rider_list)\n self.method.addRestList(self.restaurant_list)\n \n # create event checkpoints\n checkpoint = EventQueue() \n \n '''Initialize regular check point'''\n initial_check = Event(0, 4, None)\n checkpoint.put(initial_check)\n \n '''Put in new orders event'''\n order_time_dict = {}\n self.order_list.sort()\n for o in self.order_list:\n order_time_dict[o.t] = o\n e = Event(o.t, 1, o)\n checkpoint.put(e)\n # get program end time. \n # Note: self.end < actual ending time of the program, \n # since it ends at \"order appear time\" of the last order, instaed\n # of \"delivered time\" of the last order. \n # but it desent matter if we wish to know % riders occupied\n \n # self.end = max(order_time_dict.keys())\n \n \n\n #initialize status for all\n \n counter = 0\n \n #simulation starts\n while not checkpoint.empty():\n # see event type, update status\n currEvent = checkpoint.get()\n\n # currEvent.print()\n currTime = currEvent.time\n \n if self.args[\"printCheckPt\"] and currEvent.cat != 4: pass\n # print(\"\\n 💥 checkpoint\", counter, \" time \", round(currTime,2), \"Event cat:\", currEvent.getCategory() ,\"\\n\")\n\n # check Event category, if it's a new order, tell it how to assign rider\n if currEvent.getCategory() == 'New Order':\n # print(\"New order === Order Index \", currEvent.order.index, \" at \",currTime)\n currEvent.addAssignmentMethod(self.method)\n \n elif currEvent.getCategory() == 'Regular Check':\n currEvent.addRiderList(self.rider_list) \n currEvent.addStatusCheckDict(self.rider_status_check_dict)\n currEvent.passCurrQSize(checkpoint.qsize())\n currEvent.addProgramEndTime(self.t_termination)\n # print(\"Status check at\", currTime, \":\", self.status_check_dict.keys())\n\n elif currEvent.getCategory() == 'Order Delivered':\n currEvent.addAssignmentMethod(self.method) # to provide self.walking_rule\n self.numDelivered += 1\n # get total waiting time\n currOrder = currEvent.order\n wt = currOrder.wt\n self.wt_ls.append(wt)\n\n elif currEvent.getCategory() == \"Re-Assignment\": \n # print(\"Reassigning Order \" + str(currEvent.order.index) + \" at t = \" + str(currTime))\n currEvent.addAssignmentMethod(self.method)\n \n # execute current event:\n triggedEvent = currEvent.executeEvent(currTime)\n\n # if there is/are new events triggered, add to checkpoint\n if triggedEvent: \n for e in triggedEvent:\n checkpoint.put(e)\n\n counter += 1\n \n if self.args[\"showEventPlot\"]:\n self.plotTimeHorizon()\n \n # # reset all order status\n # for o in self.order_list:\n # o.reset()\n\n return self\n\n\n\n\n# debug functions for visulization\n def printResult(self):\n \n print(\"\\n ****************** \\n \", self.method.__class__.__name__, \"\\n ****************** \\n \")\n def print_all_order_status(orders):\n dict = {}\n for o in orders:\n dict[o.index] = []\n dict[o.index].append(\"Delivered\" if o.getOrderStatus() == \"DELIVERED\" else \"NOT Delivered\")\n dict[o.index].append( \"Rider #\"+str(o.rider.index) if o.rider is not None else \"NA\")\n # print \n df = pd.DataFrame.from_dict(dict, orient='index',\n columns=[ 'Status', 'Delivered by'])\n print(df)\n\n def print_all_rider_waiting_time(rider_list):\n dict = {}\n for r in rider_list:\n dict[r.index] = []\n dict[r.index].append(r.totalOrderDelivered)\n dict[r.index].append(round(r.totalWaitingTime,2))\n dict[r.index].append(0 if r.totalOrderDelivered ==0 else round(r.totalWaitingTime/r.totalOrderDelivered,2))\n \n # print \n df = pd.DataFrame.from_dict(dict, orient='index',\n columns=[ '# orders delivered', 'total waiting time', 'waiting time per order'])\n print(df)\n print_all_order_status(self.order_list)\n print_all_rider_waiting_time(self.rider_list)\n \n def plotTimeHorizon(self):\n plot = False\n if plot:\n events = [(o.t, o.t_delivered) for o in self.order_list]\n plt.eventplot(events,linelengths = 1, \n colors=['C{}'.format(i) for i in range(len(events))],\n )\n plt.ylabel(\"OrderNumber\")\n plt.xlabel(\"Time\")\n plt.title(\"Events acorss time \\n Method:\" + self.method.name +\n \"\\n #Orders\" + str(args[\"numOrders\"]) +\n \" #Riders:\" + str(args[\"numRiders\"]) +\n \" Gridsize:\" + str(args[\"gridSize\"]) +\n \" lambda:\" + str(args[\"orderArrivalRate\"]), fontsize = 10)\n \n plt.show()\n ","repo_name":"alexaDYZ/food-delivery","sub_path":"Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":16128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5454278590","text":"import os\nimport math\n\n\ndef calc_num_padding_zeros(collection):\n return math.floor(math.log10(len(collection))) + 1\n\n\ndef split_keep_prefix(base_string, split_string, clear_empty=True):\n return [split_string + split\n for split in base_string.split(split_string)\n if split != '' or not clear_empty\n ]\n\n\ndef save_text_list(text_list, prefix, save_dir, limit=None):\n \"\"\"\n Saves list of text strings into files. The filenames are generated by enumerating the list of strings\n and prepending 'prefix'. The number of files saved can be limited by 'limit'.\n :param text_list: list of strings\n :param prefix: a string to be prepended to file names\n :param save_dir: directory to save file\n :param limit: save at most this many files\n :return: list of filenames of all files created\n \"\"\"\n\n if limit is not None:\n text_list = text_list[:limit]\n\n padding_zeros = calc_num_padding_zeros(text_list)\n\n filenames = []\n\n for i, pgn_str in enumerate(text_list):\n filename = prefix + str(i).zfill(padding_zeros)\n filenames.append(filename)\n path = os.path.join(save_dir, filename)\n with open(path, 'w', encoding='utf-8') as f:\n try:\n f.write(pgn_str)\n except Exception as inst:\n print(inst)\n print(pgn_str)\n\n return filenames\n\nif __name__ == \"__main__\":\n user_pgn_path = 'C:\\\\Users\\\\tamiq\\\\Downloads\\\\ChessCom_erik_200910.pgn'\n save_dir = 'C:\\\\Users\\\\tamiq\\\\PycharmProjects\\\\ChessStyles\\\\game_data'\n with open(user_pgn_path, 'r') as f:\n text_data = f.read()\n\n save_text_list(text_data, '[Event', 'erik' + '_', save_dir, limit=5)\n","repo_name":"tamique-debrito/ChessStyles","sub_path":"Dataset/DownloadAndSaveData/Utils/split_text_to_files.py","file_name":"split_text_to_files.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"24937988771","text":"import numpy as np\nfrom functools import partial\n\nimport torch as ch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Sequential, Linear, ReLU\nfrom torch.nn.init import xavier_uniform_, constant_\n\n\nzeros_initializer = partial(constant_, val=0.0)\n\n\nclass Dense(nn.Linear):\n \"\"\"Applies a dense layer with activation: :math:`y = activation(Wx + b)`\n\n Args:\n in_features (int): number of input feature\n out_features (int): number of output features\n bias (bool): If set to False, the layer will not adapt the bias. (default: True)\n activation (callable): activation function (default: None)\n weight_init (callable): function that takes weight tensor and initializes (default: xavier)\n bias_init (callable): function that takes bias tensor and initializes (default: zeros initializer)\n \"\"\"\n\n def __init__(\n self,\n in_features,\n out_features,\n bias=True,\n activation=None,\n dropout_rate=0.0,\n weight_init=xavier_uniform_,\n bias_init=zeros_initializer,\n ):\n self.weight_init = weight_init\n self.bias_init = bias_init\n\n super().__init__(in_features, out_features, bias)\n\n self.activation = activation\n\n if dropout_rate > 0 and dropout_rate < 1:\n self.dropout = nn.Dropout(p=dropout_rate)\n\n def reset_parameters(self):\n \"\"\"\n Reinitialize model parameters.\n \"\"\"\n self.weight_init(self.weight)\n if self.bias is not None:\n self.bias_init(self.bias)\n\n def forward(self, inputs):\n \"\"\"\n Args:\n\n\n Returns:\n ch.Tensor: Output of the dense layer.\n \"\"\"\n y = super().forward(inputs)\n\n if hasattr(self, \"dropout\"):\n y = self.dropout(y)\n\n if self.activation:\n y = self.activation(y)\n\n return y\n\n\nclass Softplus(nn.Module):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def forward(self, inp):\n return F.softplus(inp) - np.log(2.0)\n","repo_name":"learningmatter-mit/Atomistic-Adversarial-Attacks","sub_path":"robust/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"85"} +{"seq_id":"19694726927","text":"#!/usr/bin/env python3\nfrom collections import Counter\n\n\ndef build_decoder(patterns: list[tuple[int]]) -> dict[str, str]:\n one = next(d for d in patterns if len(d) == 2)\n four = next(d for d in patterns if len(d) == 4)\n return dict((seg,\n 'e' if cnt == 4 else\n 'b' if cnt == 6 else\n ('d' if seg in four else 'g') if cnt == 7 else\n ('c' if seg in one else 'a') if cnt == 8 else\n 'f' if cnt == 9 else None)\n for (seg, cnt) in Counter(c for digit in patterns for c in digit).items())\n\n\ndef decode(decoder: dict[str, str], code: tuple[str]) -> int:\n decoded = (''.join(sorted(decoder[segment] for segment in digit)) for digit in code)\n return int(''.join(str(digits.index(digit)) for digit in decoded))\n\n\ndigits = [\"abcefg\", \"cf\", \"acdeg\", \"acdfg\", \"bcdf\", \"abdfg\", \"abdefg\", \"acf\", \"abcdefg\", \"abcdfg\"]\nwith open('../../../aoc-21-inputs/year-2021/day-08/example.txt') as f:\n inputs = [[part.split(' ') for part in line.strip().split(\" | \")] for line in f.readlines()]\n print(sum(1 for (_, code) in inputs for digit in code if len(digit) in (2, 3, 4, 7)))\n print(sum(decode(build_decoder(patterns), code) for (patterns, code) in inputs))\n","repo_name":"tKe/aoc-21","sub_path":"python/year-2021/day-08.py","file_name":"day-08.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5109008855","text":"\nfrom flask import Flask, render_template, request\nimport web_crawler\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef signin():\n error = None\n print( 1)\n if request.method == 'POST':\n query = request.form['search']\n print(query)\n result = web_crawler.main(query)\n print(result)\n if result is None:\n error = 'Invalid Credentials. Please try again.'\n else:\n return render_template('first.html', error=error , result = result) \n\n return render_template('first.html', error=error)\n\nif __name__ == '__main__':\n app.run(debug = True)\n","repo_name":"modifiededition/Price-Scraping-Site","sub_path":"adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38029425223","text":"l1=[1,3,4,5,7]\r\nl2=[2,3,4,6,8,9]\r\nif len(l1)==len(l2):\r\n print('equal length')\r\nelse:\r\n print('not equal length')\r\nif sum(l1)==sum(l2):\r\n print('The sums are equal =',c)\r\nelse:\r\n print('the sums are not equal')\r\nl3=[elem for elem in l1 if elem in l2]\r\nif len(l3)>0:\r\n print('the common elements are ',l3)\r\nelse:\r\n print('there are no common elements')\r\n ","repo_name":"naveen-vs/MCA-python","sub_path":"CO1/c1p7.py","file_name":"c1p7.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71549967319","text":"import pandas as pd\r\nimport bs4 as bs\r\nimport urllib.request\r\n\r\nurl = \"http://www.foxsports.com/ufc/odds\"\r\ndfs = pd.read_html(url) #reads the html tables into a list of dataframe objects\r\nsauce = urllib.request.urlopen(url).read()\r\nsoup = bs.BeautifulSoup(sauce, 'lxml')\r\n\r\neventName = soup.find_all(\"option\", {\"selected\":\"selected\"})[0].text\r\nprint(eventName)\r\n\r\ndate = soup.find_all(\"span\", {\"class\":\"wisbb_fightDate\"})[0].text\r\nprint(date)\r\n\r\nfight = dict()\r\nfor x in range(0, len(dfs)):\r\n fight[x] = dfs[x][['Fighters', 'Opening Moneyline', 'Current Moneyline']][0:1] #fight is the dictionary that contains the fighters and the odds\r\n\r\n\r\n\r\nodds = dict()\r\nfor x in range(0, len(dfs)): #loops through each fight\r\n for i in range(0,2): #loops twice, once for fighter A and once for fighter B\r\n s = fight[x]['Fighters'][0] #creates a string of the fighters\r\n names = s.split() #splits the string into an array of strings\r\n if i == 1:\r\n name = names[2][len(names[1])-1:] + \" \" + names[4]\r\n odds[name] = fight[x]['Opening Moneyline'][0][4:] #assigns fighter B to the dictionary with his odds\r\n else:\r\n name = names[0] + \" \" + names[1][0:-1]\r\n odds[name] = fight[x]['Opening Moneyline'][0][0:4] #assigns fighter A to the dictionary with his odds\r\n\r\n\r\nfor x in odds: #Will print out each fighter with their respective odds underneath\r\n print(x)\r\n print(odds[x])\r\n\r\nfighters = []\r\nfor n in range(0, len(dfs)): #creates a list of all the fighters in order\r\n s = fight[n]['Fighters'][0]\r\n x = 0\r\n names = s.split()\r\n fighter1 = names[0] + \" \" + names[1][0:-1] #fighter A\r\n fighter2 = names[2][len(names[1])-1:] + \" \" + names[4] #fighter B\r\n fighters.append(fighter1)\r\n fighters.append(fighter2)\r\n\r\nodds2 = [] #creates a list of all the odds in order\r\nfor x in range(0, len(dfs)):\r\n for i in range(0,2):\r\n if i == 0:\r\n odds2.append(fight[x]['Opening Moneyline'][0][0:4])\r\n else:\r\n odds2.append(fight[x]['Opening Moneyline'][0][4:])\r\n\r\n\r\ndef fighters(n): #gives the fighters of fight n\r\n s = fight[n]['Fighters'][0]\r\n x = 0\r\n names = s.split()\r\n fighter1 = names[0] + \" \" + names[1][0:-1]\r\n fighter2 = names[2][len(names[1])-1:] + \" \" + names[4]\r\n print(fighter1)\r\n print(fighter2)\r\n return(fighter1 + \" vs. \" + fighter2)\r\n\r\n\r\ndef odds(n):\r\n print(\"The odds for the \" + fighters(n) + \" fight is \" + fight[n]['Opening Moneyline'][0])\r\n","repo_name":"ikillawich/Projects","sub_path":"ufc_odds.py","file_name":"ufc_odds.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9579751265","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 6 19:20:43 2020\n\n@author: Robab\n\"\"\"\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot\nimport framework\nimport tkinter\n\n\nelevation = []\nin_raster = 1\ngradient = []\n\n\n\ndef test():\n print(\"dog, cat, fish, goat\")\n\n\ndef calculate():\n\n #external scripts directly run from tkinter run before tkinter.mainloop()\n #set matplotlib window\n #run gradient calculation\n #show calculated gradients in matplotlib window\n fig = matplotlib.pyplot.figure(figsize=(7, 7))\n framework.gradient.angle(elevation, cell_distance, gradient)\n matplotlib.pyplot.title(\"Gradient\")\n matplotlib.pyplot.imshow(gradient)\n\n\ndef txtWriter():\n #external scripts directly run from tkinter run before tkinter.mainloop()\n #pass gradient dataset to .txt file writer\n framework.fileHandler.txtWriter(gradient) \n\n \ndef csvWriter():\n #external scripts directly run from tkinter run before tkinter.mainloop()\n #pass gradient dataset to .csv file writer \n framework.fileHandler.csvWriter(gradient)\n\n\ndef jsonWriter():\n #external scripts directly run from tkinter run before tkinter.mainloop()\n #pass gradient dataset to .json file writer \n framework.fileHandler.jsonWriter(gradient)\n\n\ndef fileImport():\n \n def enter_resolution():\n #assign popup window entry to cell_distance global variable\n global cell_distance\n cd = v1.get()\n cell_distance = int(cd)\n print(cell_distance)\n v1.quit()\n #create matplotlib window and display imported elevation data\n framework.fileHandler.tkFileAdd(in_raster, elevation)\n fig = matplotlib.pyplot.figure(figsize=(7, 7))\n matplotlib.pyplot.title(\"Elevation\")\n matplotlib.pyplot.imshow(elevation) \n \n #external scripts directly run from tkinter run before tkinter.mainloop()\n #create pop up window for user input of data resolution\n root = tkinter.Tk()\n tkinter.Label(root, text=\"input resolution (m)\").grid(row=0)\n v1 = tkinter.Entry(root)\n v1.grid(row=0, column=1)\n tkinter.Button(root, \n text='Enter', \n command=enter_resolution).grid(row=0, column=2)\n tkinter.mainloop()\n\n\n#tkinter GUI setup\nroot = tkinter.Tk()\n\n#set tkinter canvas extent\ncanvas = tkinter.Canvas(root, bg=\"blue\", height=300, width=500)\ncanvas.pack()\n\n#add menu bar\nmenu_bar = tkinter.Menu(root)\nroot.config(menu=menu_bar)\n\n#assign canvas menus options\nfile_menu = tkinter.Menu(menu_bar)\nfile_import_menu = tkinter.Menu(menu_bar)\nfile_export_menu = tkinter.Menu(menu_bar)\nanalysis_menu = tkinter.Menu(menu_bar)\n\n#file >> import cascade options and commands\nmenu_bar.add_cascade(label=\"File\", menu=file_menu)\nfile_menu.add_cascade(label=\"Import\", menu=file_import_menu)\nfile_import_menu.add_command(label=\"Import from file\", command=fileImport)\n\n#file >> export cascade options and commands\nfile_menu.add_cascade(label=\"Export\", menu=file_export_menu)\nfile_export_menu.add_command(label=\"Export as TXT\", command=txtWriter)\nfile_export_menu.add_command(label=\"Export as CSV\", command=csvWriter)\nfile_export_menu.add_command(label=\"Export as JSON\", command=jsonWriter)\n\n#analysis cascade options and commands\nmenu_bar.add_cascade(label=\"Analysis\", menu=analysis_menu)\nanalysis_menu.add_command(label=\"Elevation to gradients\", command=calculate)\n\ntkinter.mainloop()\n\n \n","repo_name":"robGy19Ra/model_A2","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"40347411748","text":"import copy\nimport multiprocessing\nimport os\nimport sys\nimport time\n\nfrom astropy.table import Table\nfrom matplotlib.patches import Patch\nfrom scipy.optimize import curve_fit\nfrom scipy.signal import convolve\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport hdfutils\nfrom SimAndVis.C3_2 import multiprocessing_functions\nfrom SimAndVis.C3_2.fast_electrorelax import electrofield_nonnormal\nfrom SimAndVis.C3_2.fast_relax import potential_stagger, potential, meshgrid, fast_gs, converged, fast_sor, \\\n fast_sor_inplace\nfrom SimAndVis.C3_2.fast_electrorelax import electrofield\n\n\nclass charge_generator(object):\n def __init__(self, shape):\n self.shape = shape\n self.charges = None\n self.charges_coords = None\n\n # Generate a point charge at the centre of charge q (we assume discretization is unity thus this equals density.)\n def point_charge(self, q):\n rho = np.zeros(self.shape)\n rho_mid = [int(d/2) for d in self.shape]\n rho[rho_mid[0], rho_mid[1], rho_mid[2]] = q\n self.charges = np.array([q])\n self.charges_coords = np.array([rho_mid])\n return rho\n\n # Generate one instead at some point elsewhere\n def point_charge_point(self, q, coordinate):\n rho = np.zeros(self.shape)\n rho[coordinate[0], coordinate[1], coordinate[2]] = q\n self.charges = np.array([q])\n self.charges_coords = np.array(coordinate)\n return rho\n\n # Random spread of point charges\n def charge_spread(self, max_q, num, pad):\n rho = np.zeros(self.shape)\n coords_x, coords_y, coords_z = np.random.randint(pad, self.shape[0] - pad, num), \\\n np.random.randint(pad, self.shape[1] - pad, num), \\\n np.random.randint(pad, self.shape[2] - pad, num)\n coords = np.array([coords_x, coords_y, coords_z]).T\n chargs = np.random.normal(0, max_q, num)\n self.charges = chargs\n self.charges_coords = coords\n for coord, charg in zip(coords, chargs):\n rho[coord[0],coord[1],coord[2]] = charg\n\n return rho\n\nclass relaxed_poisson(object):\n # Generic Poisson solver for static charge distributions (inside cuboids- not necessarily cubes.)\n def __init__(self, boundary, rho, converge_frac, converge_rate, max_n):\n self.boundary, self.converge_frac = boundary, converge_frac # dirichlet condition & converge frac\n self.converge_rate = converge_rate # every X steps to check for convergence\n self.rho = rho # initial charge distribution, held static\n self.shape = np.shape(rho) # grid size\n self.pot_dist = np.zeros_like(rho) # potential grid.\n self.has_converged = False\n self.n = 1\n self.max_n = max_n\n\n \"\"\"\n I have set potgrid to zero...\n Evaluating potgrid from rho would solve the problem in this case (the point is to solve this numerically)\n The way I understand it, we're trying to get the steady state potgrid- no analytic solution to it. \n \"\"\"\n\n # Analytical potential generator. Kernel width should be at least double the padding (to conserve charge.)\n def gen_analypot(self, gauss_kernel_width, zmid, sqr_dist_relax, stagger, nonnorm=False):\n\n if gauss_kernel_width == 0:\n\n analy_rho = self.rho\n\n else:\n\n # Specify empty gaussian. Make sure it's bigger than the largest binsize.\n kernel_width = gauss_kernel_width # in number of cells\n gauss_array = np.zeros_like(self.rho)\n gaussi, gaussj, gaussk = np.shape(gauss_array)\n midi, midj, midk = int((gaussi + 1) / 2), int((gaussj + 1) / 2), int((gaussk + 1) / 2)\n # Craft the gaussian! Unnormalized.\n gauss = lambda ii, jj, kk: np.exp(\n (-1 / (2 * (kernel_width ** 2))) * ((ii - midi) ** 2 + (jj - midj) ** 2 + (kk - midk) ** 2))\n for i in range(gaussi):\n for j in range(gaussj):\n for k in range(gaussk):\n gauss_array[i, j, k] = gauss(i, j, k)\n gauss_array /= np.sum(gauss_array)\n gaussian = gauss_array\n\n # Convolve our density matrix with the Gaussian (with the gauss kernel width appropriate.)\n analy_rho = convolve(self.rho, gaussian, mode='same')\n\n if stagger != None:\n analytical = potential_stagger(analy_rho, stagger)\n if nonnorm == False:\n ana_field_vecs = electrofield(analytical, zmid, self.boundary)\n else:\n ana_field_vecs = electrofield_nonnormal(analytical, zmid, self.boundary)\n\n else:\n if sqr_dist_relax != None:\n analytical = potential(analy_rho, sqr_dist_relax)\n if nonnorm == False:\n ana_field_vecs = electrofield(analytical, zmid, self.boundary)\n else:\n ana_field_vecs = electrofield_nonnormal(analytical, zmid, self.boundary)\n\n # Return\n return analytical, ana_field_vecs\n\n # Plot x,y slice over time (ideal for point potential.)\n def run_sim_plot_point(self, binrate, gauss_kernel_width, sqr_dist_relax, stagger):\n\n\n # Interactive on\n plt.ion()\n\n # Midpoint\n zmid = int(self.shape[2]/2)\n\n # Get meshgrid for quiver\n shape = np.shape(self.rho)\n coord_slice = meshgrid(shape[0], shape[1])\n\n # Evaluate the analytical solution.\n analytical, ana_field_vecs = self.gen_analypot(gauss_kernel_width, zmid, sqr_dist_relax, stagger)\n\n # Set up figure, axes, etc\n fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(8,4))\n\n # Plot the electric field, also\n field_vecs = np.ones((2, shape[0], shape[1]))/np.sqrt(2)\n # Plot the potential start\n quiver = axs[0].quiver(coord_slice[0], coord_slice[1], field_vecs[0], field_vecs[1], color='black')\n im = axs[0].imshow(self.pot_dist[:,:,zmid], animated=True, cmap=\"bwr\", aspect='equal', vmin=-0.1, vmax=0.1,\n origin='lower')\n t1 = axs[0].text(0, 0, str(self.n), color=\"black\", fontsize=20)\n\n plt.savefig(str(self.n) + \".png\", dpi=150)\n\n # Also add in for the analytical solution\n # noinspection PyUnboundLocalVariable\n quiver_analytic = axs[1].quiver(coord_slice[0], coord_slice[1], ana_field_vecs[0], ana_field_vecs[1],\n color='black')\n im_analytic = axs[1].imshow(analytical[:,:,zmid], animated=True, cmap=\"bwr\", aspect='equal', vmin=-0.1,\n vmax=0.1, origin='lower')\n axs[1].text(0,0,\"Analytic\",color='black',fontsize=20)\n\n # Also plot some residuals\n im_residual = axs[2].imshow(self.pot_dist[:,:,zmid]-analytical[:,:,zmid], animated=True,\n cmap=\"bwr\", origin='lower',\n aspect='equal', vmin=-0.1, vmax=0.1)\n axs[2].text(0,0,\"Residual\",color='black',fontsize=20)\n\n # Until it's converged. Keep track of the \"last converge set\" to check\n last_converge_pot = copy.copy(self.pot_dist)\n\n # Iterate over. Terminate when new_converge_set near match to last, by fraction converge_frac\n while self.n < self.max_n:\n\n # If in a \"converge set\" run and check for convergence, too\n if self.n % self.converge_rate == 0:\n\n # Get the current converge pot\n current_converge_pot, n = fast_gs(self.rho, self.pot_dist, self.shape, self.boundary, self.n)\n self.has_converged = converged(last_converge_pot, current_converge_pot, self.converge_frac)\n if self.has_converged == True:\n print(\"Converged on \", self.n)\n plt.close()\n break\n else:\n self.pot_dist = current_converge_pot\n last_converge_pot = copy.copy(current_converge_pot)\n self.n = n\n\n # Not in a \"converge set\" so run normally\n else:\n self.pot_dist, self.n = fast_gs(self.rho, self.pot_dist, self.shape, self.boundary, self.n)\n\n # Binrate check, too\n if self.n % binrate == 0:\n field_vecs = electrofield(self.pot_dist, zmid, self.boundary)\n quiver.set_UVC(field_vecs[0], field_vecs[1])\n im.set_array(self.pot_dist[:,:,zmid])\n t1.set_text(str(self.n))\n im_residual.set_array(self.pot_dist[:,:,zmid]-analytical[:,:,zmid])\n fig.canvas.draw()\n fig.canvas.flush_events()\n plt.savefig(str(self.n) + \".png\", dpi=150)\n\n if self.n > (self.max_n - 3):\n print(\"Failed to converge, sorry!\")\n plt.close()\n\n # Run the sim without plotting (with/without SOR) just to produce a final slice\n def runsim(self, gauss_kernel_width, sqr_dist_relax, stagger, SOR_value, nonnorm=True):\n\n \"\"\"\n The analytical potential is the same shape as the density field. The field vectors are a slice through the\n midplane of the potential grid, calculated appropriately. Set the SOR_value to unity for standard Gauss-Seidel.\n SOR update rule is in-place: too high will cause divergence/instability in simulation. Not-inplace exists-\n see fast_relax.\n\n :return: analytical, ana_field_vecs, self.pot_dist, field_vecs, self.n\n \"\"\"\n\n # Midpoint\n zmid = int(self.shape[2] / 2)\n\n # Evaluate the analytical solution.\n analytical, ana_field_vecs = self.gen_analypot(gauss_kernel_width, zmid, sqr_dist_relax, stagger, nonnorm)\n\n # Until it's converged. Keep track of the \"last converge set\" to check\n last_converge_pot = copy.copy(self.pot_dist)\n\n # Iterate over. Terminate when new_converge_set near match to last, by fraction converge_frac\n while self.n < self.max_n:\n\n # If in a \"converge set\" run and check for convergence, too\n if self.n % self.converge_rate == 0:\n\n # Get the current converge pot\n current_converge_pot, n = fast_sor_inplace(self.rho, self.pot_dist, self.shape, self.boundary, self.n, SOR_value)\n self.has_converged = converged(last_converge_pot, current_converge_pot, self.converge_frac)\n if self.has_converged == True:\n print(\"Converged on \", self.n)\n plt.close()\n break\n else:\n self.pot_dist = current_converge_pot\n last_converge_pot = copy.copy(current_converge_pot)\n self.n = n\n\n # Not in a \"converge set\" so run normally\n else:\n self.pot_dist, self.n = fast_sor_inplace(self.rho, self.pot_dist, self.shape, self.boundary, self.n, SOR_value)\n\n if self.n > (self.max_n - 3):\n print(\"Failed to converge, sorry!\")\n plt.close()\n\n # Get the final field vectors for the final potential\n field_vecs = electrofield_nonnormal(self.pot_dist, zmid, self.boundary)\n\n # Returns\n return analytical, ana_field_vecs, self.pot_dist, field_vecs, self.n\n\n # Create plots radially from a point charge (assumed single charge) using charge_generator\n def radiplot(self, gauss_kernel_width, sqr_dist_relax, stagger, SOR_value, charge_object):\n\n # Generate\n analytical, ana_field_vecs, pot_dist, field_vecs, n = self.runsim(gauss_kernel_width,\n sqr_dist_relax,\n stagger, SOR_value)\n\n # Grab coord/charge\n charge, coord = charge_object.charges[0], charge_object.charges_coords[0]\n centre = coord[0]\n\n # Shape\n shape = np.shape(analytical)\n yy = np.arange(0, shape[0], 1)\n\n # Get the magnitude of the field vectors (this is an XY plane slice through the midplane, i.e. no z component.)\n ana_field_vecs, field_vecs = np.sqrt(ana_field_vecs[0]**2 + ana_field_vecs[1]**2), \\\n np.sqrt(field_vecs[0]**2 + field_vecs[1]**2)\n\n\n # Get a radial slice for the charge along the i-axis for the potential\n anay, poty = analytical[:,coord[1],coord[2]], pot_dist[:,coord[1],coord[2]]\n\n # Get a radial slice for the charge along the i-axis for the electric field strength (direction skipped.)\n anafy, fieldy = ana_field_vecs[:,coord[1]], field_vecs[:,coord[1]]\n\n # Set up figure\n fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(16,8))\n\n fig.subplots_adjust(hspace=0.3)\n\n axs[0,0].scatter(yy, anay, color='green', marker='x')\n axs[0,0].scatter(yy, poty, color='red', marker='x')\n axs[0,1].scatter(yy, anafy, color='green', marker='x')\n axs[0,1].scatter(yy, fieldy, color='red', marker='x')\n axs[0,0].grid(which='major', color='pink')\n axs[0,1].grid(which='major', color='pink')\n axs[0,0].set(ylim=[0,0.6])\n axs[0,1].set(ylim=[0,0.6])\n axs[0,0].set(xlim=[2, shape[0]-2])\n axs[0,1].set(xlim=[2, shape[0]-2])\n\n # Also evaluate potential/etc analytically from a functional form\n def inverse_analytic(x, Q, power):\n return (Q/4)*(1/np.pi)*(1/np.abs((x - centre))**power)\n\n i_range = np.linspace(0, shape[0]-1, 1000)\n axs[0,0].plot(i_range, inverse_analytic(i_range, charge, 1), color='lime', lw=0.5)\n axs[0,1].plot(i_range, inverse_analytic(i_range, charge, 2), color='lime', lw=0.5)\n\n # Set up legend elements\n legend_elements = [Patch(edgecolor='black', facecolor='red', label='Sim'),\n Patch(edgecolor='black', facecolor='green', label='Analytic (Numerical)'),\n Patch(edgecolor='black', facecolor='lime', label='Analytic (Functional)')]\n axs[0,0].legend(handles=legend_elements, loc='upper right')\n axs[0,1].legend(handles=legend_elements, loc='upper right')\n axs[0,0].set(xlabel=r'$i$', ylabel=r'$\\phi$')\n axs[0,1].set(xlabel=r'$i$', ylabel=r'$|\\vec{E}|$')\n\n # Also set up a plot to try and see if the data follows square laws/etc as hoped for...\n yy_distances = yy[centre + 2:] - centre\n distance_ratios = yy_distances/yy_distances[0]\n distance_logs = np.log(distance_ratios)\n pot_edge = poty[centre + 2:]\n pot_ratios = pot_edge/pot_edge[0]\n potlogs = np.log(pot_ratios)\n field_edge = fieldy[centre + 2:]\n field_ratios = field_edge/field_edge[0]\n fieldlogs = np.log(field_ratios)\n\n # Standard polynomial fit\n def poly(r, mag, power):\n return mag*(r**power)\n\n # Test fit\n potfit = curve_fit(poly, distance_logs, potlogs)[0]\n fieldfit = curve_fit(poly, distance_logs, fieldlogs)[0]\n\n # Produce a plot of the logs/etc\n axs[1,0].scatter(distance_logs, potlogs, color='blue')\n axs[1,0].plot(distance_logs, -distance_logs, color='lime')\n axs[1,0].plot(distance_logs, poly(distance_logs, *potfit), color='red')\n axs[1,1].scatter(distance_logs, fieldlogs, color='blue')\n axs[1,1].plot(distance_logs, -2*distance_logs, color='lime')\n axs[1,1].plot(distance_logs, poly(distance_logs, *fieldfit))\n # Set up legend elements\n legend_elements = [Patch(edgecolor='black', facecolor='blue', label='Sim'),\n Patch(edgecolor='black', facecolor='lime', label='Analytic (Functional)'),\n Patch(edgecolor='black', facecolor='red', label='Polynomial Fit')]\n axs[1,0].legend(handles=legend_elements, loc='upper right')\n axs[1,1].legend(handles=legend_elements, loc='upper right')\n axs[1,0].set(xlabel=r'$\\log(\\frac{\\Delta{x}}{\\Delta{x}_0})$', ylabel=r'$\\log(\\frac{\\phi}{\\phi_0})$')\n axs[1,1].set(xlabel=r'$\\log(\\frac{\\Delta{x}}{\\Delta{x}_0})$', ylabel=r'$\\log(\\frac{|\\vec{E}|}{|\\vec{E_0}|})$')\n axs[1,0].grid(which='major', color='pink')\n axs[1,1].grid(which='major', color='pink')\n axs[1,0].set_title(\"Polynomial Fit of \" + r'$m{r}^{a}$' + \" where m,a \" + r'$=$' + str(potfit))\n axs[1,1].set_title(\"Polynomial Fit of \" + r'$m{r}^{a}$' + \" where m,a \" + r'$=$' + str(fieldfit))\n\n\n plt.savefig(\"example_fieldplot.png\", dpi=300)\n plt.show()\n\n # Dump all the data\n writer = hdfutils.hdf5_writer(os.getcwd(), \"electric_monopole.hdf5\")\n columns = [\"distance\", \"potential\", \"field\"]\n data = np.array([yy_distances, pot_edge, field_edge]).T\n table = Table(data=data, names=columns)\n writer.write_table(\"CHARGE_EQUALS_TWO\", \"data\", table)\n\n # Runsim but without any trimmings. Only returns the value of $n$\n def converge_runsim(self, SOR_value):\n\n # Midpoint\n zmid = int(self.shape[2] / 2)\n\n # Until it's converged. Keep track of the \"last converge set\" to check\n last_converge_pot = copy.copy(self.pot_dist)\n\n # Iterate over. Terminate when new_converge_set near match to last, by fraction converge_frac\n while self.n < self.max_n:\n\n # If in a \"converge set\" run and check for convergence, too\n if self.n % self.converge_rate == 0:\n\n # Get the current converge pot\n current_converge_pot, n = fast_sor_inplace(self.rho, self.pot_dist, self.shape, self.boundary,\n self.n, SOR_value)\n self.has_converged = converged(last_converge_pot, current_converge_pot, self.converge_frac)\n if self.has_converged == True:\n print(\"Converged on \", self.n)\n plt.close()\n break\n else:\n self.pot_dist = current_converge_pot\n last_converge_pot = copy.copy(current_converge_pot)\n self.n = n\n\n # Not in a \"converge set\" so run normally\n else:\n self.pot_dist, self.n = fast_sor_inplace(self.rho, self.pot_dist, self.shape, self.boundary, self.n,\n SOR_value)\n\n if self.n > (self.max_n - 3):\n print(\"Failed to converge, sorry!\")\n plt.close()\n\n # Returns\n return self.n\n\n# Class for handling user input (i.e. checkpoint.)\nclass checkpoint(object):\n def __init__(self):\n self.delay_max = 2e-3\n self.rng = np.random.default_rng()\n\n # Old bit of code to make text in the console appear slower and crisper (2nd year???)\n def time_delay(self, text):\n print()\n for c in text:\n sys.stdout.write(c)\n sys.stdout.flush()\n resttime = self.rng.uniform(0.0001, self.delay_max)\n time.sleep(resttime)\n print()\n\n\n # User Input Specification\n def user_input(self):\n self.time_delay(\"Yōkoso!!! Welcome to my Poisson Solving Thingy! \\n\" \n \"This particular model will let you do a bunch of point charges \\n\"\n \"Please give parameters as outlined in the documentation!\")\n print()\n self.time_delay(\"grid size x\")\n nx = int(input())\n print()\n self.time_delay(\"grid size y\")\n ny = int(input())\n print()\n self.time_delay(\"grid size z\")\n nz = int(input())\n print()\n self.time_delay(\"number of point charges\")\n ncharges = int(input())\n print()\n self.time_delay(\"magnitude of charges (recommended near unity.)\")\n magcharge = float(input())\n print()\n self.time_delay(\"boundary value\")\n boundary = float(input())\n print()\n self.time_delay(\"convergence fraction\")\n confrac = float(input())\n print()\n self.time_delay(\"convergence rate\")\n conrate = int(input())\n print()\n self.time_delay(\"max iterations\")\n maxiter = int(input())\n print()\n self.time_delay(\"binrate for imaging (i.e. every X frames)\")\n binrate = int(input())\n print()\n self.time_delay(\"You can get analytical solution either by a staggered grid, or by relaxation distance. s or r\")\n which = str(input())\n if which == \"s\":\n self.time_delay(\"grid stagger (recommended 0.01)\")\n stagger = float(input())\n relaxation = None\n print()\n elif which == \"r\":\n self.time_delay(\"relaxation distance for analytic solution (recommended 1e-12)\")\n relaxation = float(input())\n stagger = None\n print()\n else:\n print(\"You didn't select s or r ... will use a default relaxation of 1e-12\")\n relaxation = 1e-12\n stagger = None\n\n\n shape= [nx,ny,nz+2]\n charges = [magcharge,ncharges,0]\n relpars = [boundary, confrac, conrate, maxiter]\n simpars = [binrate, 1, relaxation, stagger]\n return shape, charges, relpars, simpars\n\n # Run\n def run(self):\n print(\"Do you just want to use some default settings? y/n\")\n he_says = str(input())\n if he_says == \"y\":\n rho = charge_generator([32,32,32]).charge_spread(1, 30, 0) # 2, 1)\n poisson = relaxed_poisson(0, rho, 1e-10, 10000000, int(10000e6))\n # noinspection PyTypeChecker\n poisson.run_sim_plot_point(1,0,None, 0.001)\n if he_says == \"n\":\n pars = self.user_input()\n rho = charge_generator(pars[0]).charge_spread(*pars[1])\n poisson = relaxed_poisson(pars[2][0], rho, *pars[2][1:])\n poisson.run_sim_plot_point(*pars[3])\n else:\n print(\"You said something wrong.\")\n\n# To replicate the radial plot in the PDF I gave\ndef do_radiplot():\n charge_dist = charge_generator([100, 100, 100])\n rho = charge_dist.point_charge(2) # 2, 1)\n poisson = relaxed_poisson(0, rho, 1e-3, 2000, int(1e6))\n poisson.radiplot(0, None, 0.001, 1, charge_dist)\n\n# Generate the convergence plot. We're doing it for a convergence percentage of 0.1%.\ndef do_sorplot():\n\n if __name__ == \"__main__\":\n\n # Charge distribution\n charge_dist = charge_generator([40, 40, 40])\n rho = charge_dist.point_charge(2) # 2, 1)\n\n # Set up sorrange\n sor_range = np.linspace(1, 3, 50)\n sorsets = []\n for i in sor_range:\n sorsets.append([i, rho])\n\n pool = multiprocessing.Pool(8)\n n_vals = pool.map(multiprocessing_functions.do_sor, sorsets)\n pool.close()\n\n # Make plot\n fig, ax = plt.subplots(nrows=1, ncols=1)\n ax.set(ylim=[0,1000])\n ax.grid(which='major', color='pink')\n ax.plot(sor_range, n_vals, color='red')\n ax.set(xlabel=r'$\\omega$',\n ylabel=\"convergence / n\")\n plt.savefig(\"sorvergence.png\", dpi=300)\n plt.show()\n\n\n# Run checkpoint\ncheckpoint().run()\n#do_radiplot()\n#do_sorplot()\n","repo_name":"callous4567/UoE-Projects","sub_path":"SimAndVis/C3_2/relax.py","file_name":"relax.py","file_ext":"py","file_size_in_byte":23250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"39444176992","text":"import random\nimport requests\nfrom tinydb import TinyDB\nfrom bs4 import BeautifulSoup\nimport urllib3\nimport certifi\nfrom time import strftime, strptime, localtime\nimport re\nfrom json.decoder import JSONDecodeError\n\nsubreddit_max_search = 5\n\n\ndef gelbooru_image_search(rating, trap=\"\", *args):\n args = [x.lower() for x in args]\n base_url = \"https://danbooru.donmai.us\"\n if trap == 'trap' and '-trap' in args:\n return \"What are you trying to pull here? The dick only makes it better!\"\n\n try:\n tags = f\"tags={trap}+{'+'.join(args)}\"\n rating = f\"rating%3A{rating}\"\n\n url = f\"{base_url}/posts.json?{tags}+{rating}\"\n r = requests.get(url)\n r = r.json()\n\n if 'success' in r:\n return r['message']\n\n return f\"{random.choice(r)['large_file_url']}\" if r else \"Nothing to see here\"\n\n except JSONDecodeError:\n fucked = r.text\n return fucked\n\n except ValueError:\n return \"Nice command.\"\n\n\ndef subreddit_search(subreddit_list):\n headers = {'User-agent': 'traps-bot (by Keisakyu)'}\n url = f\"https://www.reddit.com/r/{random.choice(subreddit_list)}.json\"\n for i in range(0, subreddit_max_search):\n try:\n r = requests.get(url, headers=headers)\n r = r.json()\n start = random.choice(r['data']['children'])\n post_type = start['data']['is_self']\n replacement = 'amp;'\n if not post_type:\n pic = start['data']['url']\n if replacement in pic:\n pic = pic.replace(replacement, \"\")\n return pic\n else:\n continue\n except:\n pass\n\ndef get_national_days():\n db = TinyDB('national_days.json')\n db.purge_tables()\n months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']\n\n http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(), maxsize=1, timeout=5)\n for month in months:\n url = f'https://nationaldaycalendar.com/{month}/'\n r = http.request('GET', url)\n soup = BeautifulSoup(r.data, 'html.parser')\n\n days_container = soup.find_all(\"div\", class_=\"et_pb_blurb_content\")\n current_year = strftime(\"%Y\", localtime())\n national_days_for_month = []\n\n for day_container in days_container:\n day_string = day_container.find(\"h4\").string\n day_string = re.sub(r'(\\d)(st|nd|rd|th)', r'\\1', day_string)\n day_string = strftime(f\"{current_year}-%m-%d\", strptime(day_string, \"%B %d\"))\n\n national_days = day_container.find_all(\"a\")\n national_days = \"\\n\".join(national_day.text.replace(\"\\n\", \" \") for national_day in national_days)\n\n national_days_for_month.append({\"date\": day_string, \"national_days\": national_days})\n\n db.insert_multiple(national_days_for_month)\n\n\nif __name__ == '__main__':\n get_national_days()\n","repo_name":"liggers/traps","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18684731383","text":"from cahoots.config import BaseConfig\nfrom cahoots.parser import ParserThread, CahootsParser\nfrom cahoots.parsers.base import BaseParser\nfrom cahoots.result import ParseResult\nfrom tests.config import TestConfig\nimport datetime\nimport mock\nimport unittest\n\n\nclass FakeModule(BaseParser):\n\n bootstrappingComplete = False\n\n def __init__(self, config):\n BaseParser.__init__(self, config, \"Fake\")\n\n def parse(self, data):\n yield self.result(\"Subtype\", 200, data)\n\n @staticmethod\n def bootstrap(config):\n FakeModule.bootstrappingComplete = True\n\n\nclass ParserTestConfig(BaseConfig):\n\n debug = True\n\n enabled_modules = [\n FakeModule,\n ]\n\n enabled_confidence_normalizers = [\n ]\n\n\nclass parserThreadTests(unittest.TestCase):\n\n parserThread = None\n\n def setUp(self):\n self.parserThread = ParserThread(TestConfig, FakeModule, 'data_string')\n\n def test_parserThreadYieldsResultAsExpected(self):\n self.parserThread.start()\n self.parserThread.join()\n\n for result in self.parserThread.results:\n self.assertIsInstance(result, ParseResult)\n self.assertEqual('Fake', result.type)\n self.assertEqual('Subtype', result.subtype)\n self.assertEqual(200, result.confidence)\n self.assertEqual('data_string', result.result_value)\n\n\nclass FakeDate(datetime.datetime):\n # pylint: disable=arguments-differ\n def __new__(cls):\n return datetime.datetime.__new__(datetime.datetime)\n\n\nclass CahootsParserTests(unittest.TestCase):\n\n def test_bootstrapSetsUpParserProperly(self):\n CahootsParser(ParserTestConfig, True)\n self.assertTrue(FakeModule.bootstrappingComplete)\n FakeModule.bootstrappingComplete = False\n\n def test_parserCreatesInstanceOfBaseConfig(self):\n parser = CahootsParser()\n self.assertIsInstance(parser.config, BaseConfig)\n\n def test_parserInstantiatesBaseConfig(self):\n parser = CahootsParser(BaseConfig())\n self.assertIsInstance(parser.config, BaseConfig)\n\n @mock.patch('datetime.datetime', FakeDate)\n def test_parserReturnsExpectedParserResult(self):\n FakeDate.now = classmethod(lambda cls: 'thetimeisnow')\n parser = CahootsParser(ParserTestConfig)\n result = parser.parse('data_string')\n\n self.assertEqual(5, len(result))\n self.assertEqual('data_string', result['query'])\n self.assertEqual('thetimeisnow', result['date'])\n self.assertIsInstance(result['top'], ParseResult)\n self.assertEqual(1, result['results']['count'])\n self.assertEqual(['Fake'], result['results']['types'])\n self.assertEqual(1, len(result['results']['matches']))\n self.assertIsInstance(result['results']['matches'][0], ParseResult)\n","repo_name":"SerenitySoftware/cahoots","sub_path":"tests/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"85"} +{"seq_id":"11695387846","text":"class Solution:\n def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n if not people:\n return []\n people.sort(key= lambda x:(-x[0],x[1]))\n # 因为个子高的人看不到个子矮的人\n # 这句话对于程序而言,就是当个子矮的人在个子高的人的前面的时候,个子高的人的k值不会增加\n # 所以个子高的人的k值是真k值,可以先排好\n # 然后个子矮的人再根据k值插队\n # 某个程度上可以理解成个子高的人的k值比个子矮的人的k值优先度更高\n # 即先根据个子高的人的k值排队\n # 再根据下一个身高的人的k值排队\n #result = [people[0]]\n result = []\n for i in range(len(people)):\n result.insert(people[i][1],people[i])\n return result\n\n# 参考答案讲解\n# https://leetcode-cn.com/problems/queue-reconstruction-by-height/solution/gen-ju-shen-gao-zhong-jian-dui-lie-by-leetcode/","repo_name":"johnzan0743/My_Leet_Code_Note","sub_path":"406-贪心-Queue Reconstruction by Height.py","file_name":"406-贪心-Queue Reconstruction by Height.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32660440940","text":"from emailParser import *\nfrom WailMail_common import *\n\nimport queue\nimport concurrent.futures\nimport logging\nimport threading\nimport time\n\n# import emailClientReader\n# import queue\n# import concurrent\n# import logging\n# import threading\n# import time\n\n\ndef condition_tests():\n condition_grades = Condition(\"(cms or gradescope) or piazza or some_school.edu\")\n result = condition_grades.eval()\n assert(result == False)\n \n condition_grades.set_true(\"fake\")\n result = condition_grades.eval()\n assert(result == False)\n\n condition_grades.set_true(\"gradescope\")\n result = condition_grades.eval()\n assert(result == True)\n\n condition_grades.set_true(\"some_school.edu\")\n result = condition_grades.eval()\n assert(result == True)\n\n condition_grades.reset_state()\n result = condition_grades.eval()\n assert(result == False)\n \n condition_workday = Condition(\"workday and not (timestamp and due)\")\n result = condition_workday.eval()\n assert(result == False)\n\n condition_workday.set_true(\"workday\")\n result = condition_workday.eval()\n assert(result == True)\n\n condition_workday.set_true(\"timestamp\")\n result = condition_workday.eval()\n assert(result == True)\n\n condition_workday.set_true(\"due\")\n result = condition_workday.eval()\n assert(result == False)\n\n condition_campus = Condition(\"not north and not northcampus\")\n result = condition_campus.eval()\n assert(result == True)\n\n condition_campus.set_true(\"north\")\n result = condition_campus.eval()\n assert(result == False)\n\n condition_some_school = Condition(\"some_school.edu\")\n result = condition_some_school.eval()\n assert(result == False)\n\n condition_some_school.set_true(\"some_school.edu\")\n result = condition_some_school.eval()\n assert(result == True)\n\n print(\"Condition class tests passed\")\n\ndef rule_tests():\n condition_grades = Condition(\"(cms or gradescope) or piazza or some_school.edu\")\n rule_yeet = Rule(1, condition_grades, \"yeet.mp3\")\n \n result = rule_yeet.check_condition()\n assert(result == False)\n\n rule_yeet.set_true_term(\"some_school.edu\")\n result = rule_yeet.check_condition()\n assert(result == True)\n\n terms = rule_yeet.terms_of_interest()\n assert(terms == [\"cms\", \"gradescope\", \"piazza\", \"some_school.edu\"])\n \n print(\"Rule class tests passed\")\n\ndef dummy_producer_email(email_queue, end_event, logging):\n i = 0\n logging.info(\"dummy e producer:: starting\")\n email_bodies = [\"your bill is due\", \"new assignment, have fun\", \"oh oops\", \"hey there, reminder to do X, Y, and Z\"]\n while(not end_event.is_set()):\n time.sleep(1)\n email_tuple = (\"somebody@some_school.edu\", \"Email #\" + str(i), email_bodies[ i%4 ], [])\n put_in_queue(email_queue, email_tuple, end_event)\n logging.info(\"dummy e producer:: email #\" +str(i) +\" inserted\")\n i += 1\n logging.info(\"dummy e producer:: exiting\")\n\ndef dummy_producer_rules(rule_queue, end_event, logging):\n rules = []\n logging.info(\"dummy r producer:: starting\")\n\n condition_some_school = Condition(\"somebody@some_school.edu\")\n rule_yeet = Rule(0, condition_some_school, \"screaming_sheep.mp3\")\n rules.append(rule_yeet)\n\n condition_assignment = Condition(\"new and assignment\")\n rule_uhoh = Rule(1, condition_assignment, \"siren.mp3\")\n rules.append(rule_uhoh)\n\n\n rule_count = 0\n\n logging.info(\"dummy r producer:: done setting up initial rules\")\n while(not end_event.is_set() and rule_count < len(rules)):\n logging.info(\"dummy r producer:: iteration\")\n time.sleep(5)\n put_in_queue(rule_queue, rules[rule_count], end_event)\n logging.info(\"dummy r producer:: rule #\" +str(rule_count) +\" inserted\")\n rule_count += 1\n\n logging.info(\"dummy r producer:: exiting\")\n\ndef dummy_consumer_audio(audio_queue, end_event, logging):\n logging.info(\"dummy a consumer:: starting\")\n while(not end_event.is_set()):\n time.sleep(1)\n if(not audio_queue.empty()):\n audio_request = get_from_queue(audio_queue, end_event)\n if(audio_request is not None):\n logging.info(\"dummy a consumer::\" + audio_request)\n logging.info(\"dummy a consumer:: exiting\")\n\ndef email_parser_util_tests():\n email_1_tuple = (\"somebody@some_school.edu\", \"Email #1\", \"hello world\", [])\n condition_some_school = Condition(\"somebody@some_school.edu\")\n rule_yeet = Rule(0, condition_some_school, \"screaming_sheep.mp3\")\n result = EmailParser.check_email_for_rule(rule_yeet, email_1_tuple)\n assert result == True\n\n condition_some_school = Condition(\"some_school.edu\")\n result = EmailParser.check_email_for_rule(rule_yeet, email_1_tuple)\n assert result == True\n\n print(\"all Email Parser util function tests pass\")\n\n\n \n\ndef emailparser_tests(test_duration):\n\n format = \"%(asctime)s: %(message)s\"\n logging.basicConfig(format=format, level=logging.INFO,\n datefmt=\"%H:%M:%S\")\n logging.basicConfig(format=format, level=logging.WARN,\n datefmt=\"%H:%M:%S\")\n logging.basicConfig(format=format, level=logging.DEBUG,\n datefmt=\"%H:%M:%S\")\n logging.getLogger().setLevel(logging.INFO)\n\n end_event = threading.Event()\n email_queue = queue.Queue()\n rule_queue = queue.Queue()\n audio_queue = queue.Queue()\n ep = EmailParser(email_queue, rule_queue, audio_queue, end_event, logging)\n seconds = 0\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n email_producer_future = executor.submit(dummy_producer_email, email_queue, end_event, logging)\n rule_producer_future = executor.submit(dummy_producer_rules, rule_queue, end_event, logging)\n ep_consumer_future = executor.submit(ep.parseQueues)\n audio_consumer_future = executor.submit(dummy_consumer_audio, audio_queue, end_event, logging)\n\n while(seconds < test_duration):\n logging.info(\"t=\" +str(seconds))\n logging.info(\"EPF::\" + str(email_producer_future))\n logging.info(\"RPF::\" + str(rule_producer_future))\n logging.info(\"EPCF::\" + str(ep_consumer_future))\n logging.info(\"ACF::\" + str(audio_consumer_future))\n\n time.sleep(1)\n seconds += 1\n \n end_event.set()\n time.sleep(10)\n logging.info(\"EPF::\" + str(email_producer_future))\n assert confirm_thread_finished(email_producer_future)\n logging.info(\"RPF::\" + str(rule_producer_future))\n assert confirm_thread_finished(rule_producer_future)\n logging.info(\"EPCF::\" + str(ep_consumer_future))\n assert confirm_thread_finished(ep_consumer_future)\n logging.info(\"ACF::\" + str(audio_consumer_future))\n assert confirm_thread_finished(audio_consumer_future)\n print(\"Email Parser class tests passed\")\n\n print(end_event.is_set())\n\n \n\ncondition_tests()\nrule_tests()\nemail_parser_util_tests()\nemailparser_tests(20)\n","repo_name":"saleh99er/WailMail","sub_path":"emailParser_test.py","file_name":"emailParser_test.py","file_ext":"py","file_size_in_byte":7011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"38387961949","text":"from nltk.tokenize import sent_tokenize\nfrom nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters\nfrom nltk.tokenize import word_tokenize\nfrom nltk.tokenize import wordpunct_tokenize\nimport string\nimport re\nfrom nltk.parse.stanford import StanfordDependencyParser\n\ncore_nlp_base = '/Users/schwenk/wrk/animation_gan/phrase_cues/deps/stanford_core_nlp/stanford-corenlp-full-2017-06-09/'\npath_to_jar = core_nlp_base + 'stanford-corenlp-3.8.0.jar'\npath_to_models_jar = core_nlp_base + 'stanford-corenlp-3.8.0-models.jar'\ndependency_parser = StanfordDependencyParser(path_to_jar=path_to_jar, path_to_models_jar=path_to_models_jar)\n\npunct_set = set(string.punctuation)\npunct_set.remove('.')\npunkt_param = PunktParameters()\npunkt_param.abbrev_types = {'dr', 'vs', 'mr', 'mrs', 'prof', 'inc', 'ms'}\nsentence_splitter = PunktSentenceTokenizer(punkt_param)\n\nmain_characters_lower = {\n \"fred\": 'Fred',\n \"wilma\": 'Wilma',\n \"mr slate\": \"Mr. Slate\",\n \"barney\": \"Barney\",\n \"betty\": \"Betty\",\n \"pebbles\": \"Pebbles\",\n \"dino\": \"Dino\",\n \"baby puss\": \"Baby Puss\",\n \"hoppy\": \"Hoppy\",\n \"bamm bamm\": \"Bamm Bamm\"\n}\n\n# def const_parse(doc, parser):\n# raw_sentences = sentence_splitter.tokenize(doc)\n# sentences = [' '.join([w for w in wordpunct_tokenize(s) if set(w) - punct_set]).replace(' .', '.') for s in raw_sentences]\n# sent_parses = [list(i)[0] for i in parser.raw_parse_sents(sentences)]\n# return sent_parses\n\n\ndef check_sub_subtrees(subtree):\n for tree in list(subtree.subtrees())[1:]:\n if tree.label() in ['NP']:\n return False\n return True\n\n\ndef apply_fixes(raw_str):\n raw_str = raw_str.replace(' \\'', '\\'')\n return raw_str\n\n\ndef extract_np(psent):\n for subtree in psent.subtrees():\n if subtree.label() == 'NP' and check_sub_subtrees(subtree):\n subprod = subtree.productions()[0].unicode_repr()\n if 'NN' in subprod or 'NNP' in subprod:\n if 'CC' not in subprod:\n yield ' '.join(word for word in subtree.leaves()).replace(' \\'', '\\'')\n else:\n for st in subtree.subtrees():\n if st.label() in ['NNP', 'NN']:\n yield st.leaves()[0]\n\n\ndef compute_token_spans(const_parse_sents, txt):\n offset = 0\n for const_parse_sent in const_parse_sents:\n tokens = const_parse_sent.leaves()\n for token in tokens:\n offset = txt.find(token, offset)\n yield token, offset, offset + len(token)\n offset += len(token)\n\n\ndef assign_word_spans(noun_phrases_w_spans, doc, token_spans):\n chunk_spans = []\n seen_chunks = []\n for np in noun_phrases_w_spans:\n # print(np)\n char_spans = [(m.start(), m.end() - 1) for m in re.finditer(np + '\\s|' + np + '\\.', doc)]\n # print(seen_chunks)\n occ_n = seen_chunks.count(np)\n # print(occ_n)\n # print(char_spans)\n start, end = char_spans[occ_n]\n start_w, end_w = None, None\n for w_idx, token_span in enumerate(token_spans):\n token, ts, te = token_span\n if ts == start:\n start_w = w_idx\n if te == end:\n end_w = w_idx + 1\n if type(start_w) == int and type(end_w) == int:\n chunk_spans.append([start_w, end_w])\n else:\n # print(np)\n # print('failed')\n raise IndexError\n np_pieces = np.split()\n seen_chunks += list(set(np_pieces).union(set([np])))\n return chunk_spans\n\n\ndef np_chunker(doc, parsed_sents):\n recovered_tokens = ' '.join([item for sublist in parsed_sents for item in sublist.leaves()]).replace(' .', '.')\n noun_phrases = [list(extract_np(sent)) for sent in parsed_sents]\n # print(noun_phrases)\n noun_phrases = [item for sublist in noun_phrases for item in sublist]\n # noun_phrase_spans = [list(extract_np_spans(doc, sent)) for sent in noun_phrases]\n token_spans = list(compute_token_spans(parsed_sents, recovered_tokens))\n # print(list(token_spans))\n noun_phrase_spans = assign_word_spans(noun_phrases, recovered_tokens, token_spans)\n return {'chunks': noun_phrase_spans, 'named_chunks': noun_phrases, 'token_spans': token_spans,\n 'aligned_description': recovered_tokens}\n\n\ndef sanitize_text(d_text):\n d_text = ' '.join(d_text.split())\n d_text = re.sub(r'([a-z])\\.([A-Z])', r'\\1. \\2', d_text)\n if d_text[-1] != '.':\n d_text += '.'\n for lc, uc in main_characters_lower.items():\n d_text = d_text.replace(lc, uc)\n return d_text\n\n\ndef parse_description(vid_text, nlp, parser):\n vid_text = sanitize_text(vid_text)\n raw_sentences = sentence_splitter.tokenize(vid_text)\n try:\n sentences = [' '.join([w for w in wordpunct_tokenize(s) if set(w) - punct_set]).replace(' .', '.') for s in raw_sentences]\n # sentences = raw_sentences\n # print('here', sentences)\n # docs = [nlp(sent) for sent in sentences]\n\n # noun_phrase_chunks = {\n # 'chunks': [[(np.start, np.end) for np in doc.noun_chunks] for doc in docs],\n # 'named_chunks': [[np.text for np in doc.noun_chunks] for doc in docs]\n # }\n # constituent_parse = const_parse(vid_text, parser)\n constituent_parse = [list(i)[0] for i in parser.raw_parse_sents(sentences)]\n # return constituent_parse\n # print([s.leaves() for s in constituent_parse])\n noun_phrase_chunks = np_chunker(vid_text, constituent_parse)\n except IndexError:\n # sentences = [' '.join([w for w in word_tokenize(s) if set(w) - punct_set]).replace(' .', '.') for s in raw_sentences]\n constituent_parse = [list(i)[0] for i in parser.raw_parse_sents(raw_sentences)]\n noun_phrase_chunks = np_chunker(vid_text, constituent_parse)\n pos_tags = [sent.pos() for sent in constituent_parse]\n # pos_tags = [(token.text, token.pos_, token.string) for token in doc]\n pos_tags = [item for sublist in pos_tags for item in sublist]\n parses = {\n 'noun_phrase_chunks': noun_phrase_chunks,\n 'pos_tags': pos_tags,\n }\n return parses\n\n\ndef parse_video(video, nlp, parser):\n vid_parse = parse_description(video.description(), nlp, parser)\n video._data['parse'] = vid_parse\n\n\ndef dep_parse_vid(video):\n try:\n vid_text = video.description()\n vid_text = sanitize_text(vid_text)\n raw_sentences = sentence_splitter.tokenize(vid_text)\n sentences = [' '.join([w for w in wordpunct_tokenize(s) if set(w) - punct_set]).replace(' .', '.') for s in raw_sentences]\n results = [dependency_parser.raw_parse(sent) for sent in sentences]\n deps = [r.__next__() for r in results]\n dep_parses = [t for d in deps for t in list(d.triples())]\n return {video.gid(): dep_parses}\n except:\n return {video.gid(): []}\n\n\n","repo_name":"drschwenk/anigen_tools","sub_path":"parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":6888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32067451794","text":"#%%\nimport os\nimport sys\nimport numpy as np\n\nimport torch\nimport signatory\n\nimport holoviews as hv\nfrom holoviews import opts\n\nhv.extension(\"bokeh\")\n\nsys.path.append(\"..\")\nfrom tensor_product import *\nfrom transforms import *\n\n# %%\nns = 400\nend = 1\ndepth = 5\n\n\ndef phi(t, pow=2):\n T = np.max(t) - np.min(t)\n return ((t - np.min(t)) / T) ** pow * T + np.min(t)\n\n\nt0 = np.linspace(0, end, ns)\n# t1 = np.linspace(0, end * 3, ns * 3)\n# t2 = np.concatenate([t0, end + phi(t0, 2), 2 * end + phi(t0, 3)])\n\n\ndef f(t):\n return np.stack(\n [\n np.sin(2 * np.pi * t)\n + 0.7 * np.cos(4 * np.pi * t)\n + 0.2 * np.cos(2 * np.pi * t),\n np.cos(2 * np.pi * t)\n + 0.7 * np.sin(4 * np.pi * t)\n + 0.2 * np.sin(2 * np.pi * t),\n ],\n axis=-1,\n )\n\n\nf0 = f(t0)\n# f1 = f(t1)\n# f2 = f(t2)\n\n# f0, f1, f2 = (\n# torch.tensor(f0).float(),\n# torch.tensor(f1).float(),\n# torch.tensor(f2).float(),\n# )\n\nf0 = torch.tensor(f0).float()\nf0 = rescale_path(f0, depth)\n\nhv.Curve(f0)\n# %%\nsig0 = signatory.signature(f0[None, ...], depth)\n# %%\nsig1 = signatory.signature_combine(sig0, sig0, 2, depth)\n# %%\nhv.Curve(sig0[0]) * hv.Curve(sig1[0])\n# %%\nsig_prod = tensor_product_torch(sig0, sig0, 2, depth)\n# %%\nhv.Curve(sig0[0]) * hv.Curve(sig1[0]) * hv.Curve(sig_prod[0])\n# %%\nlogsig0 = signatory.signature_to_logsignature(sig0, 2, depth, mode=\"expand\")\n#%%\n# log_res = tensor_log1p(sig0, 2, depth)\n#%%\n# print(logsig0)\n# print(log_res)\n# print(logsig0 / log_res)\n# %%\nexp_res = tensor_exp_impl(logsig0, 2, depth)\n# %%\nprint(exp_res)\nprint(sig0)\nprint(sig0 / exp_res)","repo_name":"Mithrillion/SPIDEC","sub_path":"sigtools/tests/toy_data.py","file_name":"toy_data.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27518040477","text":"#!/usr/bin/env python3\nimport i3ipc\n\n# Get i3 IPC connection\ni3 = i3ipc.Connection()\nparent = i3.get_tree().find_focused().parent\n\n# Print status\nif parent.layout == \"splitv\":\n print(\"V\")\nelif parent.layout == \"splith\":\n print(\"H\")\nelse:\n print(\"-\")\n\n","repo_name":"kenielf/dotfiles","sub_path":"insp3442-arch/.config/i3/scripts/get-layout.py","file_name":"get-layout.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"28287743719","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Created by tz301 on 2020/2/15\n\"\"\"共用模块.\"\"\"\nimport numpy as np\n\nLOGGER_FORMAT = '%(asctime)s %(name)s %(levelname)s %(message)s'\n\n\ndef load_txt(file_path):\n \"\"\"从txt文件中读取特征和标签.\n\n 文件每一行为一个样本, 每行以\",\"为分隔符, 最后一列为标签, 其余列为特征.\n\n Args:\n file_path: txt文件路径.\n\n Returns:\n 特征和标签, 特征维度(样本数, 特征数), 标签维度(样本数).\n \"\"\"\n data = np.loadtxt(file_path, delimiter=\",\")\n feat = data[:, :-1]\n label = data[:, -1]\n if len(feat.shape) == 1:\n feat = np.expand_dims(feat, 1)\n return feat, label\n","repo_name":"tz301/notes","sub_path":"base/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"74517249238","text":"import os\nimport sys\n\nfrom typing import Any\n\nfrom .__main__ import main as heat_desalination_main\nfrom .__utils__ import get_logger, HPCOptimisation, HPCSimulation\nfrom .argparser import parse_hpc_args_and_runs\nfrom .parallel_simulator import main as parallel_simulator_main\n\n\n__all__ = (\"main\",)\n\n# HPC Job Number:\n# Name of the environment variable for the HPC job number.\nHPC_JOB_NUMBER: str = \"PBS_ARRAY_INDEX\"\n\n\n# Logger name:\n# The name to use for the logger for this script.\nLOGGER_NAME: str = \"hpc_run_{}\"\n\n\ndef main(args: list[Any]) -> None:\n \"\"\"\n Wrapper around HEATDesalination when run on the HPC as an array job.\n\n \"\"\"\n\n # Determine the run that is to be carried out.\n try:\n hpc_job_number = int(os.getenv(HPC_JOB_NUMBER)) # type: ignore\n except ValueError:\n print(f\"HPC environmental variable {HPC_JOB_NUMBER} was not of type int.\")\n raise\n\n # Use a separate logger for each run accordingly.\n logger = get_logger(LOGGER_NAME.format(hpc_job_number), False)\n logger.info(\"HPC run script executed.\")\n logger.info(\"CLI arguments: %s\", \", \".join(args))\n\n # Call the utility module to parse the HPC run information.\n logger.info(\"Parsing HPC input file.\")\n _, runs, _ = parse_hpc_args_and_runs(args, logger)\n logger.info(\"HPC input file successfully parsed.\")\n\n # Sanitise the jobn number.\n run_number: int = hpc_job_number - 1\n\n # Fetch the appropriate run from the list of runs.\n try:\n hpc_run = runs[run_number]\n except IndexError:\n logger.error(\n \"Run number %s out of bounds. Only %s runs submitted. Exiting.\",\n hpc_job_number,\n len(runs),\n )\n raise\n logger.info(\"Run successfully determined: %s\", str(hpc_run))\n\n logger.info(\"Carrying out run.\")\n\n if isinstance(hpc_run, HPCSimulation):\n logger.info(\"Carrying out parallel simulation.\")\n parallel_simulator_main(\n hpc_run.location,\n logger,\n hpc_run.output,\n hpc_run.simulation,\n full_results=False,\n hpc=True,\n )\n\n if isinstance(hpc_run, HPCOptimisation):\n logger.info(\"Carrying out single-node optimisation.\")\n heat_desalination_main(\n hpc_run.location,\n hpc_run.profile_types,\n hpc_run.scenario,\n hpc_run.system_lifetime,\n optimisation=True,\n output=f\"hpc_{hpc_run.output}\",\n disable_tqdm=True,\n hpc=True,\n )\n\n logger.info(\"Run successfully exectued, exiting.\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"BenWinchester/HEATDesalination","sub_path":"src/heatdesalination/hpc_wrapper.py","file_name":"hpc_wrapper.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"85"} +{"seq_id":"36020907203","text":"#coding=utf-8\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport os,time\n\ndr = webdriver.Chrome()\nurl = 'http://www.baidu.com/'\ndr.get(url)\ndr.implicitly_wait(10)\n\n#找到搜索设置\ndr.find_element_by_link_text('搜索设置').click()\nWebDriverWait(dr,10).until(lambda dr:dr.find_element_by_id('nr').is_displayed())\n\n#定位到“每页显示50条”\ndr.find_element_by_id('nr').find_elements_by_tag_name('option')[2].click()\n\n#保存设置\nbuttons = dr.find_elements_by_css_selector('input[type=button]')\nfor button in buttons:\n\tif button.get_attribute('onclick') == 'go()':\n\t\tbutton.click()\n\t\tbreak\n#buttons[1].click()\ntime.sleep(5)\n\ntry:\n\talert = dr.switch_to_alert()\n\t#print alert.text\n\talert.accept()\nexcept:\n\t\"Error\"\n\ntime.sleep(5)\n\ndr.quit()","repo_name":"cff007/webdriver","sub_path":"baidu_set.py","file_name":"baidu_set.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21788405132","text":"# -*- coding: utf-8 -*-\n# author:Super.Shen\n\nimport pandas as pd\nfrom Func import gb, ri_y, nian, yue, df_cut, ri_y2\n\npd.set_option('expand_frame_repr', False)\npd.set_option('display.max_rows', 1000)\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\ntry:\n # 读取数据\n df = pd.read_excel('C:\\\\Users\\Administrator\\Desktop\\奇奇乐新用户充值\\\\充{}.xlsx'.format(ri_y2))\n df2 = pd.read_excel('C:\\\\Users\\Administrator\\Desktop\\奇奇乐新用户充值\\\\充{}.xlsx'.format(ri_y))\n df3 = pd.read_excel('C:\\\\Users\\Administrator\\Desktop\\奇奇乐新用户充值\\\\注{}.xlsx'.format(ri_y2))\n df_lei = pd.read_excel('D:\\MD_DATA\\奇奇乐新用户叠加\\\\data.xlsx')\nexcept FileNotFoundError:\n print('\\n缺少运行数据,请先下载……')\n exit()\n\n# 整理前2天当日的注册数据\ndf3['Flag'] = 'new'\ndf3.rename(columns={'用户ID': 'player_id'}, inplace=True)\ndf3 = df3[['player_id', 'Flag']]\n\ndf = pd.merge(left=df, right=df3, on='player_id', how='left')\ndf['Flag'].fillna('old', inplace=True)\n\ndf2 = pd.merge(left=df2, right=df3, on='player_id', how='left')\ndf2['Flag'].fillna('old', inplace=True)\n\n# df.to_excel('C:\\\\Users\\Administrator\\Desktop\\\\NEW_T.xlsx', index=False)\n\ni = 0\ndf_form = pd.DataFrame()\n\n\ndef df_f(df):\n df_form.loc[i, '平台'] = '奇奇乐'\n df_form.loc[i, '日期'] = '{}/{}/{}'.format(nian, yue, ri_y2)\n\n # 人数计算\n df_form.loc[i, '新用户量'] = len(df[df['Flag'] == 'new']['player_id'].unique())\n df_form.loc[i, '总用户量'] = len(df['player_id'].unique())\n df_form.loc[i, '新用户占比'] = '%.2f%%' % (df_form.loc[i, '新用户量'] / df_form.loc[i, '总用户量'] * 100)\n\n # 金额消费计算\n df_form.loc[i, '新用户消费'] = df[df['Flag'] == 'new']['amount'].sum()\n df_form.loc[i, '总消费'] = df['amount'].sum()\n df_form.loc[i, '新用户消费占比'] = '%.2f%%' % (df_form.loc[i, '新用户消费'] / df_form.loc[i, '总消费'] * 100)\n\n # 次日再消费人数\n df_form.loc[i, '次日再消费用户量'] = len(df2[df2['Flag'] == 'new']['player_id'].unique())\n df_form.loc[i, '次日再消费人数比'] = '%.2f%%' % (df_form.loc[i, '次日再消费用户量'] / df_form.loc[i, '新用户量'] * 100)\n\n # # 次日再消费金额计算\n # df_form.loc[i, '次日再消费金额'] = df2[df2['Flag'] == 'new']['amount'].sum()\n # df_form.loc[i, '次日再消费金额比'] = '%.2f%%' % (df_form.loc[i, '次日再消费金额'] / df_form.loc[i, '新用户消费'] * 100)\n\n return df_form\n\n\ndf_form = df_f(df)\n\n# 删除多余2列\ndel df_form['总用户量']\ndel df_form['总消费']\n\n# 调价到累加数据 / 去重\ndf_form = df_lei.append(df_form, ignore_index=True)\ndf_form.drop_duplicates(keep='last', inplace=True)\n\n# 导出到桌面\ndf_form.to_excel('C:\\\\Users\\Administrator\\Desktop\\\\奇奇乐{}号新用户统计情况.xlsx'.format(ri_y2), index=False)\nprint('\\n数据已导出到桌面……!')\n\n# 数据存放累加数据\ndf_form.to_excel('D:\\MD_DATA\\奇奇乐新用户叠加\\\\data.xlsx', index=False)\nprint('\\n数据已累加到 data ……\\n')\n\nprint('{}月{}号奇奇乐【新注册用户】充值情况'.format(yue, ri_y2))\n","repo_name":"SuperShen9/work_by_md","sub_path":"备用code文件/备用plus/myself_每日数据情况/奇奇乐每日新用户.py","file_name":"奇奇乐每日新用户.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71752968919","text":"import os.path\nimport cv2\nimport logging\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom datetime import datetime\nfrom collections import OrderedDict\nimport hdf5storage\n\nfrom utils import utils_model\nfrom utils import utils_logger\nfrom utils import utils_sisr as sr\nfrom utils import utils_image as util\nfrom utils.utils_resizer import Resizer\nfrom functools import partial\n\n# from guided_diffusion import dist_util\nfrom guided_diffusion.script_util import (\n NUM_CLASSES,\n model_and_diffusion_defaults,\n create_model_and_diffusion,\n args_to_dict,\n)\n\ndef main():\n\n # ----------------------------------------\n # Preparation\n # ----------------------------------------\n\n noise_level_img = 12.75/255.0 # set AWGN noise level for LR image, default: 0\n noise_level_model = noise_level_img # set noise level of model, default: 0\n model_name = 'diffusion_ffhq_10m' # diffusion_ffhq_10m, 256x256_diffusion_uncond; set diffusino model\n testset_name = 'demo_test' # set testing set, 'imagenet_val' | 'ffhq_val'\n num_train_timesteps = 1000\n iter_num = 100 # set number of sampling iterations\n iter_num_U = 1 # set number of inner iterations, default: 1\n skip = num_train_timesteps//iter_num # skip interval\n sr_mode = 'blur' # 'blur', 'cubic' mode of sr up/down sampling\n\n show_img = False # default: False\n save_L = True # save LR image\n save_E = False # save estimated image\n save_LEH = False # save zoomed LR, E and H images\n save_progressive = True # save generation process\n\n sigma = max(0.001,noise_level_img) # noise level associated with condition y\n lambda_ = 1. # key parameter lambda\n sub_1_analytic = True # use analytical solution\n\n log_process = False\n ddim_sample = False # sampling method\n model_output_type = 'pred_xstart' # model output type: pred_x_prev; pred_xstart; epsilon; score\n generate_mode = 'DiffPIR' # DiffPIR; DPS; vanilla\n skip_type = 'quad' # uniform, quad\n eta = 0. # eta for ddim sampling\n zeta = 0.1 \n guidance_scale = 1.0 \n\n test_sf = [4] # set scale factor, default: [2, 3, 4], [2], [3], [4]\n inIter = 1 # iter num for sr solution: 4-6\n gamma = 1/100 # coef for iterative sr solver 20steps: 0.05-0.10 for zeta=1, 0.09-0.13 for zeta=0 \n classical_degradation = False # set classical degradation or bicubic degradation\n task_current = 'sr' # 'sr' for super resolution\n n_channels = 3 # fixed\n cwd = '' \n model_zoo = os.path.join(cwd, 'model_zoo') # fixed\n testsets = os.path.join(cwd, 'testsets') # fixed\n results = os.path.join(cwd, 'results') # fixed\n result_name = f'{testset_name}_{task_current}_{generate_mode}_{sr_mode}{str(test_sf)}_{model_name}_sigma{noise_level_img}_NFE{iter_num}_eta{eta}_zeta{zeta}_lambda{lambda_}'\n model_path = os.path.join(model_zoo, model_name+'.pt')\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n torch.cuda.empty_cache()\n\n calc_LPIPS = True\n\n # noise schedule \n beta_start = 0.1 / 1000\n beta_end = 20 / 1000\n betas = np.linspace(beta_start, beta_end, num_train_timesteps, dtype=np.float32)\n betas = torch.from_numpy(betas).to(device)\n alphas = 1.0 - betas\n alphas_cumprod = np.cumprod(alphas.cpu(), axis=0)\n sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod)\n sqrt_1m_alphas_cumprod = torch.sqrt(1. - alphas_cumprod)\n reduced_alpha_cumprod = torch.div(sqrt_1m_alphas_cumprod, sqrt_alphas_cumprod) # equivalent noise sigma on image\n\n noise_model_t = utils_model.find_nearest(reduced_alpha_cumprod, 2 * noise_level_model)\n noise_model_t = 0\n\n noise_inti_img = 50 / 255\n t_start = utils_model.find_nearest(reduced_alpha_cumprod, 2 * noise_inti_img) # start timestep of the diffusion process\n t_start = num_train_timesteps - 1 \n\n # ----------------------------------------\n # L_path, E_path, H_path\n # ----------------------------------------\n\n L_path = os.path.join(testsets, testset_name) # L_path, for Low-quality images\n E_path = os.path.join(results, result_name) # E_path, for Estimated images\n util.mkdir(E_path)\n\n logger_name = result_name\n utils_logger.logger_info(logger_name, log_path=os.path.join(E_path, logger_name+'.log'))\n logger = logging.getLogger(logger_name)\n\n # ----------------------------------------\n # load model\n # ----------------------------------------\n\n model_config = dict(\n model_path=model_path,\n num_channels=128,\n num_res_blocks=1,\n attention_resolutions=\"16\",\n ) if model_name == 'diffusion_ffhq_10m' \\\n else dict(\n model_path=model_path,\n num_channels=256,\n num_res_blocks=2,\n attention_resolutions=\"8,16,32\",\n )\n args = utils_model.create_argparser(model_config).parse_args([])\n model, diffusion = create_model_and_diffusion(\n **args_to_dict(args, model_and_diffusion_defaults().keys()))\n # model.load_state_dict(\n # dist_util.load_state_dict(args.model_path, map_location=\"cpu\")\n # )\n model.load_state_dict(torch.load(args.model_path, map_location=\"cpu\"))\n model.eval()\n if generate_mode != 'DPS_y0':\n # for DPS_yt, we can avoid backward through the model\n for k, v in model.named_parameters():\n v.requires_grad = False\n model = model.to(device)\n\n logger.info('model_name:{}, sr_mode:{}, image sigma:{:.3f}, model sigma:{:.3f}'.format(model_name, sr_mode, noise_level_img, noise_level_model))\n logger.info('eta:{:.3f}, zeta:{:.3f}, lambda:{:.3f}, guidance_scale:{:.2f} '.format(eta, zeta, lambda_, guidance_scale))\n logger.info('start step:{}, skip_type:{}, skip interval:{}, skipstep analytic steps:{}'.format(t_start, skip_type, skip, noise_model_t))\n logger.info('analytic iter num:{}, gamma:{}'.format(inIter, gamma))\n logger.info('Model path: {:s}'.format(model_path))\n logger.info(L_path)\n L_paths = util.get_image_paths(L_path)\n\n # --------------------------------\n # load kernel\n # --------------------------------\n\n # kernels = hdf5storage.loadmat(os.path.join('kernels', 'Levin09.mat'))['kernels']\n if classical_degradation:\n kernels = hdf5storage.loadmat(os.path.join(cwd, 'kernels', 'kernels_12.mat'))['kernels']\n else:\n kernels = hdf5storage.loadmat(os.path.join(cwd, 'kernels', 'kernels_bicubicx234.mat'))['kernels']\n\n test_results_ave = OrderedDict()\n test_results_ave['psnr_sf_k'] = []\n test_results_ave['psnr_y_sf_k'] = []\n if calc_LPIPS:\n import lpips\n loss_fn_vgg = lpips.LPIPS(net='vgg').to(device)\n test_results_ave['lpips'] = []\n\n for sf in test_sf:\n border = sf\n k_num = 8 if classical_degradation else 1\n\n for k_index in range(k_num):\n logger.info('--------- sf:{:>1d} --k:{:>2d} ---------'.format(sf, k_index))\n\n if not classical_degradation: # for bicubic degradation\n k_index = sf-2 if sf < 5 else 2\n k = kernels[0, k_index].astype(np.float64)\n\n util.surf(k) if show_img else None\n\n def test_rho(lambda_=lambda_, zeta=zeta, model_output_type=model_output_type): \n logger.info('eta:{:.3f}, zeta:{:.3f}, lambda:{:.3f}, inIter:{:.3f}, gamma:{:.3f}, guidance_scale:{:.2f}'.format(eta, zeta, lambda_, inIter, gamma, guidance_scale))\n test_results = OrderedDict()\n test_results['psnr'] = []\n test_results['psnr_y'] = []\n if calc_LPIPS:\n test_results['lpips'] = []\n for idx, img in enumerate(L_paths):\n model_out_type = model_output_type\n\n # --------------------------------\n # (1) get img_L\n # --------------------------------\n\n img_name, ext = os.path.splitext(os.path.basename(img))\n img_H = util.imread_uint(img, n_channels=n_channels)\n img_H = util.modcrop(img_H, sf) # modcrop\n\n if sr_mode == 'blur':\n if classical_degradation:\n img_L = sr.classical_degradation(img_H, k, sf)\n util.imshow(img_L) if show_img else None\n img_L = util.uint2single(img_L)\n else:\n img_L = util.imresize_np(util.uint2single(img_H), 1/sf)\n elif sr_mode == 'cubic':\n img_H_tensor = np.transpose(img_H, (2, 0, 1))\n img_H_tensor = torch.from_numpy(img_H_tensor)[None,:,:,:].to(device)\n img_H_tensor = img_H_tensor / 255\n # set up resizers\n up_sample = partial(F.interpolate, scale_factor=sf)\n down_sample = Resizer(img_H_tensor.shape, 1/sf).to(device)\n img_L = down_sample(img_H_tensor)\n img_L = img_L.cpu().numpy() #[0,1]\n img_L = np.squeeze(img_L)\n if img_L.ndim == 3:\n img_L = np.transpose(img_L, (1, 2, 0))\n\n np.random.seed(seed=0) # for reproducibility\n img_L = img_L * 2 - 1\n img_L += np.random.normal(0, noise_level_img * 2, img_L.shape) # add AWGN\n img_L = img_L / 2 + 0.5\n\n # --------------------------------\n # (2) get rhos and sigmas\n # -------------------------------- \n\n sigmas = []\n sigma_ks = []\n rhos = []\n for i in range(num_train_timesteps):\n sigmas.append(reduced_alpha_cumprod[num_train_timesteps-1-i])\n if model_out_type == 'pred_xstart' and generate_mode == 'DiffPIR':\n sigma_ks.append((sqrt_1m_alphas_cumprod[i]/sqrt_alphas_cumprod[i]))\n #elif model_out_type == 'pred_x_prev':\n else:\n sigma_ks.append(torch.sqrt(betas[i]/alphas[i]))\n rhos.append(lambda_*(sigma**2)/(sigma_ks[i]**2))\n \n rhos, sigmas, sigma_ks = torch.tensor(rhos).to(device), torch.tensor(sigmas).to(device), torch.tensor(sigma_ks).to(device)\n \n # --------------------------------\n # (3) initialize x, and pre-calculation\n # --------------------------------\n\n x = cv2.resize(img_L, (img_L.shape[1]*sf, img_L.shape[0]*sf), interpolation=cv2.INTER_CUBIC)\n if np.ndim(x)==2:\n x = x[..., None]\n\n if classical_degradation:\n x = sr.shift_pixel(x, sf)\n x = util.single2tensor4(x).to(device)\n\n y = util.single2tensor4(img_L).to(device) #(1,3,256,256) [0,1]\n\n # x = torch.randn_like(x)\n x = sqrt_alphas_cumprod[t_start] * (2*x-1) + sqrt_1m_alphas_cumprod[t_start] * torch.randn_like(x)\n\n k_tensor = util.single2tensor4(np.expand_dims(k, 2)).to(device) \n\n FB, FBC, F2B, FBFy = sr.pre_calculate(y, k_tensor, sf)\n\n # --------------------------------\n # (4) main iterations\n # --------------------------------\n\n progress_img = []\n # create sequence of timestep for sampling\n skip = num_train_timesteps//iter_num\n if skip_type == 'uniform':\n seq = [i*skip for i in range(iter_num)]\n if skip > 1:\n seq.append(num_train_timesteps-1)\n elif skip_type == \"quad\":\n seq = np.sqrt(np.linspace(0, num_train_timesteps**2, iter_num))\n seq = [int(s) for s in list(seq)]\n seq[-1] = seq[-1] - 1\n progress_seq = seq[::max(len(seq)//10,1)]\n if progress_seq[-1] != seq[-1]:\n progress_seq.append(seq[-1])\n \n # reverse diffusion for one image from random noise\n for i in range(len(seq)):\n curr_sigma = sigmas[seq[i]].cpu().numpy()\n # time step associated with the noise level sigmas[i]\n t_i = utils_model.find_nearest(reduced_alpha_cumprod,curr_sigma)\n # skip iters\n if t_i > t_start:\n continue\n # repeat for semantic consistence: from repaint\n for u in range(iter_num_U):\n # --------------------------------\n # step 1, reverse diffsuion step\n # --------------------------------\n\n ### solve equation 6b with one reverse diffusion step\n if 'DPS' in generate_mode:\n x = x.requires_grad_()\n xt, x0 = utils_model.model_fn(x, noise_level=curr_sigma*255, model_out_type='pred_x_prev_and_start', \\\n model_diffusion=model, diffusion=diffusion, ddim_sample=ddim_sample, alphas_cumprod=alphas_cumprod)\n else:\n x0 = utils_model.model_fn(x, noise_level=curr_sigma*255, model_out_type=model_out_type, \\\n model_diffusion=model, diffusion=diffusion, ddim_sample=ddim_sample, alphas_cumprod=alphas_cumprod)\n # x0 = utils_model.test_mode(utils_model.model_fn, model, x, mode=2, refield=32, min_size=256, modulo=16, noise_level=curr_sigma*255, \\\n # model_out_type=model_out_type, diffusion=diffusion, ddim_sample=ddim_sample, alphas_cumprod=alphas_cumprod)\n\n # --------------------------------\n # step 2, FFT\n # --------------------------------\n\n if seq[i] != seq[-1]:\n if generate_mode == 'DiffPIR':\n if sub_1_analytic:\n if model_out_type == 'pred_xstart':\n # when noise level less than given image noise, skip\n if i < num_train_timesteps-noise_model_t: \n if sr_mode == 'blur':\n tau = rhos[t_i].float().repeat(1, 1, 1, 1)\n x0_p = x0 / 2 + 0.5\n x0_p = sr.data_solution(x0_p.float(), FB, FBC, F2B, FBFy, tau, sf)\n x0_p = x0_p * 2 - 1\n # effective x0\n x0 = x0 + guidance_scale * (x0_p-x0)\n elif sr_mode == 'cubic': \n # iterative back-projection (IBP) solution\n for _ in range(inIter):\n x0 = x0 / 2 + 0.5\n x0 = x0 + gamma * up_sample((y - down_sample(x0))) / (1+rhos[t_i])\n x0 = x0 * 2 - 1\n else:\n model_out_type = 'pred_x_prev'\n x0 = utils_model.model_fn(x, noise_level=curr_sigma*255,model_out_type=model_out_type, \\\n model_diffusion=model, diffusion=diffusion, ddim_sample=ddim_sample, alphas_cumprod=alphas_cumprod)\n # x0 = utils_model.test_mode(utils_model.model_fn, model, x, mode=2, refield=32, min_size=256, modulo=16, noise_level=curr_sigma*255, \\\n # model_out_type=model_out_type, diffusion=diffusion, ddim_sample=ddim_sample, alphas_cumprod=alphas_cumprod)\n pass\n else:\n # zeta=0.25; lambda_=15: FFHQ\n # zeta=0.35; lambda_=35: ImageNet\n x0 = x0.requires_grad_()\n # first order solver\n down_sample = Resizer(x.shape, 1/sf).to(device)\n #norm_grad, norm = utils_model.grad_and_value(operator=down_sample,x=x0/2+0.5, x_hat=x0, measurement=y)\n norm_grad, norm = utils_model.grad_and_value(operator=down_sample,x=x0, x_hat=x0, measurement=2*y-1)\n \n x0 = x0 - norm_grad * norm / (rhos[t_i]) \n x0 = x0.detach_()\n pass \n elif 'DPS' in generate_mode:\n down_sample = Resizer(x.shape, 1/sf).to(device) \n if generate_mode == 'DPS_y0':\n norm_grad, norm = utils_model.grad_and_value(operator=down_sample,x=x, x_hat=x0, measurement=2*y-1)\n #norm_grad, norm = utils_model.grad_and_value(operator=down_sample,x=xt, x_hat=x0, measurement=2*y-1) # does not work\n x = xt - norm_grad * 1. #norm / (2*rhos[t_i]) \n x = x.detach_()\n pass\n elif generate_mode == 'DPS_yt':\n y_t = sqrt_alphas_cumprod[t_i] * (2*y-1) + sqrt_1m_alphas_cumprod[t_i] * torch.randn_like(y) # add AWGN\n #y_t = y_t/2 + 0.5\n #norm_grad, norm = utils_model.grad_and_value(operator=down_sample,x=x, x_hat=xt, measurement=y_t) # no need to use\n norm_grad, norm = utils_model.grad_and_value(operator=down_sample,x=xt, x_hat=xt, measurement=y_t)\n x = xt - norm_grad * lambda_ * norm / (rhos[t_i]) * 0.35\n x = x.detach_()\n pass\n \n # add noise back to t=i-1\n if (generate_mode == 'DiffPIR' and model_out_type == 'pred_xstart') and not (seq[i] == seq[-1] and u == iter_num_U-1):\n #x = sqrt_alphas_cumprod[t_i] * (x0) + (sqrt_1m_alphas_cumprod[t_i]) * torch.randn_like(x)\n \n t_im1 = utils_model.find_nearest(reduced_alpha_cumprod,sigmas[seq[i+1]].cpu().numpy())\n eps = (x - sqrt_alphas_cumprod[t_i] * x0) / sqrt_1m_alphas_cumprod[t_i]\n # calculate \\hat{\\eposilon}\n eta_sigma = eta * sqrt_1m_alphas_cumprod[t_im1] / sqrt_1m_alphas_cumprod[t_i] * torch.sqrt(betas[t_i])\n x = sqrt_alphas_cumprod[t_im1] * x0 + np.sqrt(1-zeta) * (torch.sqrt(sqrt_1m_alphas_cumprod[t_im1]**2 - eta_sigma**2) * eps \\\n + eta_sigma * torch.randn_like(x)) + np.sqrt(zeta) * sqrt_1m_alphas_cumprod[t_im1] * torch.randn_like(x)\n else:\n #x = x0\n pass\n \n # set back to x_t from x_{t-1}\n if u < iter_num_U-1 and seq[i] != seq[-1]:\n ### it's equivalent to use x & xt (?), but with xt the computation is faster.\n # x = torch.sqrt(alphas[t_i]) * x + torch.sqrt(betas[t_i]) * torch.randn_like(x)\n sqrt_alpha_effective = sqrt_alphas_cumprod[t_i] / sqrt_alphas_cumprod[t_im1]\n x = sqrt_alpha_effective * x + torch.sqrt(sqrt_1m_alphas_cumprod[t_i]**2 - \\\n sqrt_alpha_effective**2 * sqrt_1m_alphas_cumprod[t_im1]**2) * torch.randn_like(x)\n \n\n # save the process\n x_0 = (x/2+0.5)\n if save_progressive and (seq[i] in progress_seq):\n x_show = x_0.clone().detach().cpu().numpy() #[0,1]\n x_show = np.squeeze(x_show)\n if x_show.ndim == 3:\n x_show = np.transpose(x_show, (1, 2, 0))\n progress_img.append(x_show)\n if log_process:\n logger.info('{:>4d}, steps: {:>4d}, np.max(x_show): {:.4f}, np.min(x_show): {:.4f}'.format(seq[i], t_i, np.max(x_show), np.min(x_show)))\n \n if show_img:\n util.imshow(x_show)\n\n # --------------------------------\n # (3) img_E\n # --------------------------------\n\n img_E = util.tensor2uint(x_0)\n\n psnr = util.calculate_psnr(img_E, img_H, border=border)\n test_results['psnr'].append(psnr)\n \n if calc_LPIPS:\n img_H_tensor = np.transpose(img_H, (2, 0, 1))\n img_H_tensor = torch.from_numpy(img_H_tensor)[None,:,:,:].to(device)\n img_H_tensor = img_H_tensor / 255 * 2 -1\n lpips_score = loss_fn_vgg(x_0.detach()*2-1, img_H_tensor)\n lpips_score = lpips_score.cpu().detach().numpy()[0][0][0][0]\n test_results['lpips'].append(lpips_score)\n logger.info('{:->4d}--> {:>10s} -- sf:{:>1d} --k:{:>2d} PSNR: {:.4f}dB LPIPS: {:.4f} ave LPIPS: {:.4f}'.format(idx+1, img_name+ext, sf, k_index, psnr, lpips_score, sum(test_results['lpips']) / len(test_results['lpips'])))\n else:\n logger.info('{:->4d}--> {:>10s} -- sf:{:>1d} --k:{:>2d} PSNR: {:.4f}dB'.format(idx+1, img_name+ext, sf, k_index, psnr))\n\n if save_E:\n util.imsave(img_E, os.path.join(E_path, img_name+'_x'+str(sf)+'_k'+str(k_index)+'_'+model_name+ext))\n\n if n_channels == 1:\n img_H = img_H.squeeze()\n\n if save_progressive:\n now = datetime.now()\n current_time = now.strftime(\"%Y_%m_%d_%H_%M_%S\")\n img_total = cv2.hconcat(progress_img)\n if show_img:\n util.imshow(img_total,figsize=(80,4))\n util.imsave(img_total*255., os.path.join(E_path, img_name+'_sigma_{:.3f}_process_lambda_{:.3f}_{}_psnr_{:.4f}{}'.format(noise_level_img,lambda_,current_time,psnr,ext)))\n \n # --------------------------------\n # (4) img_LEH\n # --------------------------------\n\n img_L = util.single2uint(img_L).squeeze()\n\n if save_LEH:\n k_v = k/np.max(k)*1.0\n if n_channels==1:\n k_v = util.single2uint(k_v)\n else:\n k_v = util.single2uint(np.tile(k_v[..., np.newaxis], [1, 1, n_channels]))\n k_v = cv2.resize(k_v, (3*k_v.shape[1], 3*k_v.shape[0]), interpolation=cv2.INTER_NEAREST)\n img_I = cv2.resize(img_L, (sf*img_L.shape[1], sf*img_L.shape[0]), interpolation=cv2.INTER_NEAREST)\n img_I[:k_v.shape[0], -k_v.shape[1]:, ...] = k_v\n img_I[:img_L.shape[0], :img_L.shape[1], ...] = img_L\n util.imshow(np.concatenate([img_I, img_E, img_H], axis=1), title='LR / Recovered / Ground-truth') if show_img else None\n util.imsave(np.concatenate([img_I, img_E, img_H], axis=1), os.path.join(E_path, img_name+'_x'+str(sf)+'_k'+str(k_index)+'_LEH'+ext))\n\n if save_L:\n util.imsave(img_L, os.path.join(E_path, img_name+'_x'+str(sf)+'_k'+str(k_index)+'_LR'+ext))\n\n if n_channels == 3:\n img_E_y = util.rgb2ycbcr(img_E, only_y=True)\n img_H_y = util.rgb2ycbcr(img_H, only_y=True)\n psnr_y = util.calculate_psnr(img_E_y, img_H_y, border=border)\n test_results['psnr_y'].append(psnr_y)\n \n # --------------------------------\n # Average PSNR and LPIPS for all images\n # --------------------------------\n\n ave_psnr_k = sum(test_results['psnr']) / len(test_results['psnr'])\n logger.info('------> Average PSNR(RGB) of ({}) scale factor: ({}), kernel: ({}) sigma: ({:.3f}): {:.4f} dB'.format(testset_name, sf, k_index, noise_level_model, ave_psnr_k))\n test_results_ave['psnr_sf_k'].append(ave_psnr_k)\n\n if n_channels == 3: # RGB image\n ave_psnr_y_k = sum(test_results['psnr_y']) / len(test_results['psnr_y'])\n logger.info('------> Average PSNR(Y) of ({}) scale factor: ({}), kernel: ({}) sigma: ({:.3f}): {:.4f} dB'.format(testset_name, sf, k_index, noise_level_model, ave_psnr_y_k))\n test_results_ave['psnr_y_sf_k'].append(ave_psnr_y_k)\n\n if calc_LPIPS:\n ave_lpips_k = sum(test_results['lpips']) / len(test_results['lpips'])\n logger.info('------> Average LPIPS of ({}) scale factor: ({}), kernel: ({}) sigma: ({:.3f}): {:.4f}'.format(testset_name, sf, k_index, noise_level_model, ave_lpips_k))\n test_results_ave['lpips'].append(ave_lpips_k) \n return test_results_ave\n\n # experiments\n lambdas = [lambda_*i for i in range(2,13)]\n for lambda_ in lambdas:\n #for zeta_i in [zeta*i for i in range(2,4)]:\n for zeta_i in [0.25]:\n test_results_ave = test_rho(lambda_, zeta=zeta_i, model_output_type=model_output_type)\n\n # ---------------------------------------\n # Average PSNR and LPIPS for all sf and kernels\n # ---------------------------------------\n\n ave_psnr_sf_k = sum(test_results_ave['psnr_sf_k']) / len(test_results_ave['psnr_sf_k'])\n logger.info('------> Average PSNR of ({}) {:.4f} dB'.format(testset_name, ave_psnr_sf_k))\n if n_channels == 3:\n ave_psnr_y_sf_k = sum(test_results_ave['psnr_y_sf_k']) / len(test_results_ave['psnr_y_sf_k'])\n logger.info('------> Average PSNR-Y of ({}) {:.4f} dB'.format(testset_name, ave_psnr_y_sf_k))\n if calc_LPIPS:\n ave_lpips_sf_k = sum(test_results_ave['lpips']) / len(test_results_ave['lpips'])\n logger.info('------> Average LPIPS of ({}) {:.4f}'.format(testset_name, ave_lpips_sf_k))\n\nif __name__ == '__main__':\n\n main()\n","repo_name":"yuanzhi-zhu/DiffPIR","sub_path":"main_ddpir_sisr.py","file_name":"main_ddpir_sisr.py","file_ext":"py","file_size_in_byte":29193,"program_lang":"python","lang":"en","doc_type":"code","stars":213,"dataset":"github-code","pt":"85"} +{"seq_id":"72335471318","text":"\nimport numpy as np\nimport pandas as pd\n\nimport streamlit as st\n\nimport altair as alt\n\n\ndata = pd.read_csv(\"data/Barcelona_rent_price.csv\")\n\n#df_year = data.groupby(['Year'])['Price'].mean().reset_index(name='average price')\n\nrent_metrics = ['average rent (euro/month)','average rent per surface (euro/m2)']\n\nrent_metric = st.sidebar.selectbox(\n 'Choose the average rent metric',\n rent_metrics)\n\ndataframe1 = data[data['Average _rent']== 'average rent (euro/month)']\ndataframe2 = data[data['Average _rent']== 'average rent per surface (euro/m2)']\n\nif rent_metric == 'average rent (euro/month)':\n data = dataframe1\nelse:\n data = dataframe2 \n#to be asked by Chase\nst.header(f'Rent prices based on {rent_metric} are shown in the below tabs' )\n\ntab1,tab2,tab3 = st.tabs(['Year Data', 'Trimester Data' , 'Districts and Neighbourhood Data'])\n\nwith tab1:\n years_list = [2014,2015,2016,2017,2018,2019,2020,2021,2022]\n years = st.multiselect(\n 'Choose years',\n years_list)\n\n if not years:\n st.write('please select a year/years to view the yearly data')\n else:\n df_years = data.loc[data['Year'].isin(years)]\n st.write(df_years.head())\n\n district_data = df_years.groupby(['District'])['Price'].max().reset_index(name='district_max_price').sort_values(['district_max_price'],ascending = False)\n neighbours_data = df_years.groupby(['Neighbourhood'])['Price'].max().reset_index(name='neighbourhood_max_price').sort_values(['neighbourhood_max_price'],ascending = False)\n costliest_districts = district_data.head(3)\n cheapest_districts = district_data.tail(3)\n \n costliest_neighbourhood = neighbours_data.head(3)\n cheapest_neighbourhood = neighbours_data.tail(3)\n \n \n\n st.subheader('Costliest and Cheapest Districts over the years %s are shown below' % years)\n \n bar = alt.Chart(district_data,title = \"Districts Bar Graph - Costliest to Cheapest\").mark_bar().encode(\n alt.Y(\"district_max_price:Q\"),\n x=alt.X('District',sort='-y')\n )\n\n st.altair_chart(bar, use_container_width=True)\n\n col1,col2 = st.columns(2)\n col1.subheader('Top 3 Costliest Districts')\n col1.write(costliest_districts)\n col2.subheader('Bottom 3 Cheapest Districts')\n col2.write(cheapest_districts)\n \n st.subheader('Costliest and Cheapest Neighbourhoods over the years %s are shown below' % years)\n \n random = st.slider(\"Neighbourhood Limit\",5,len(neighbours_data['Neighbourhood']),10,1)\n neighbours_data = neighbours_data[0:random]\n\n bar = alt.Chart(neighbours_data,title = \"Districts Bar Graph - Costliest to Cheapest\").mark_bar().encode(\n alt.X(\"neighbourhood_max_price:Q\"),\n y=alt.Y('Neighbourhood',sort='-x')\n )\n\n st.altair_chart(bar, use_container_width=True)\n\n col1,col2 = st.columns(2)\n col1.subheader('Top 3 Costliest Neighbourhood')\n col1.write(costliest_neighbourhood)\n col2.subheader('Bottom 3 Cheapest Neighbourhood')\n col2.write(cheapest_neighbourhood)\n st.write('Note : Costliest/Cheapest neighbourhood may or may be in the respective costliest/cheapest district')\nwith tab2:\n st.write('Note : Housing Prices are usually measured with trimester, which means each trimester = 4 months. ')\n trimester_list = [1,2,3]\n trimester = st.multiselect(\n 'Select the trimesters',\n trimester_list)\n if not trimester:\n st.write('please select a trimester')\n else:\n df_trimester = data.loc[data['Trimester'].isin(trimester)]\n st.write(df_trimester.head())\n df_trimester = df_trimester.groupby(['Year','Trimester'])['Price'].mean().reset_index(name='Average_Rent')\n trimester_line_plot = alt.Chart(df_trimester,title = f\"Rent over the years based on selected trimesters\").mark_line().encode(\n x='Year:N',\n y=alt.Y('Average_Rent',\n scale =alt.Scale(zero=False)),\n color='Trimester',\n strokeDash='Trimester',\n )\n st.altair_chart(trimester_line_plot.interactive(), use_container_width=True)\n \nwith tab3:\n col1,col2 = st.columns(2)\n\n with col1:\n \n district_list = data['District'].unique()\n districts = st.multiselect(\n 'Choose a district',\n district_list)\n\n if not districts:\n st.write('please select a District to view its data')\n else:\n with col2:\n df_district = data.loc[data['District'].isin(districts)]\n neighbourhood = st.multiselect(\n 'Choose a Neighbourhood',\n df_district['Neighbourhood'])\n if not neighbourhood : \n st.write('please select a District to view its data')\n\n df_Neighbourhood = df_district.groupby(['Year','Neighbourhood'])['Price'].mean().reset_index(name='neighbourhood_avg_price')\n\n df_Neighbourhood = df_Neighbourhood.loc[df_Neighbourhood['Neighbourhood'].isin(neighbourhood)]\n\n st.write(df_district.head(3))\n\n df_district = df_district.groupby(['Year','District'])['Price'].mean().reset_index(name='district_avg_price')\n\n ml = alt.Chart(df_district,title = f\"Rent over the years based on selected districts\").mark_line().encode(\n x='Year:N',\n y=alt.Y('district_avg_price',\n scale =alt.Scale(zero=False)),\n color='District',\n strokeDash='District',\n )\n\n st.altair_chart(ml.interactive(), use_container_width=True)\n\n ml1 = alt.Chart(df_Neighbourhood,title = f\"Rent over the years based on selected Neighbourhoods\").mark_line().encode(\n x='Year:N',\n y=alt.Y('neighbourhood_avg_price',\n scale =alt.Scale(zero=False)),\n color='Neighbourhood',\n strokeDash='Neighbourhood',\n )\n if neighbourhood :\n st.altair_chart(ml1.interactive(), use_container_width=True)\n","repo_name":"aravindchinnu/Mid2_Streamlit","sub_path":"pages/Rent_Prices_Across_the_districts.py","file_name":"Rent_Prices_Across_the_districts.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"14499895768","text":"carList = [\r\n {\"carID\" : \"001\", \"plateNum\" : \"B 3456 KTM\", \"carType\" : \"SUV\", \"carName\" : \"Fortuner\", \"price\" : 550000, \"status\" : \"Available\"},\r\n {\"carID\" : \"002\", \"plateNum\" : \"B 1267 STG\", \"carType\" : \"SEDAN\", \"carName\" : \"Civic\", \"price\" : 250000, \"status\" : \"Available\"},\r\n {\"carID\" : \"003\", \"plateNum\" : \"B 2890 TMH\", \"carType\" : \"MPV\", \"carName\" : \"Avanza\", \"price\" : 350000, \"status\" : \"Available\"},\r\n {\"carID\" : \"004\", \"plateNum\" : \"B 5834 TYO\", \"carType\" : \"MPV\", \"carName\" : \"Innova\", \"price\" : 320000, \"status\" : \"Available\"},\r\n {\"carID\" : \"005\", \"plateNum\" : \"B 0824 SHI\", \"carType\" : \"MPV\", \"carName\" : \"Sienta\", \"price\" : 300000, \"status\" : \"Available\"},\r\n {\"carID\" : \"006\", \"plateNum\" : \"B 0754 TGJ\", \"carType\" : \"SEDAN\", \"carName\" : \"Camry\", \"price\" : 350000, \"status\" : \"Available\"},\r\n {\"carID\" : \"007\", \"plateNum\" : \"B 2076 KUT\", \"carType\" : \"TRUCK\", \"carName\" : \"Hilux\", \"price\" : 700000, \"status\" : \"Available\"},\r\n {\"carID\" : \"008\", \"plateNum\" : \"B 1996 KYT\", \"carType\" : \"TRUCK\", \"carName\" : \"Triton\", \"price\" : 500000, \"status\" : \"Available\"},\r\n {\"carID\" : \"009\", \"plateNum\" : \"B 5367 KAR\", \"carType\" : \"SUV\", \"carName\" : \"Pajero\", \"price\" : 500000, \"status\" : \"Available\"},\r\n {\"carID\" : \"010\", \"plateNum\" : \"B 3786 TYS\", \"carType\" : \"SUV\", \"carName\" : \"Palisade\", \"price\" : 500000, \"status\" : \"Available\"},\r\n ]\r\nrentedCarReport = []\r\n\r\ndef fnSubMenu(fn, option):\r\n while True:\r\n subMenu = input(f'''\r\n 1. {option}\r\n 2. Back to Main Menu\r\n\r\n Enter your request: ''')\r\n if subMenu == \"1\":\r\n fn() \r\n elif subMenu == \"2\":\r\n break\r\n continue\r\n\r\ndef fnSubMenu1(fn, option1, option2):\r\n while True:\r\n subMenu = input(f'''\r\n 1. {option1}\r\n 2. {option2}\r\n 3. Back to Main Menu\r\n\r\n Enter your request: ''')\r\n if subMenu == \"1\":\r\n fn() \r\n elif subMenu == \"2\":\r\n uniqueInput = input(\" Enter Car Type: \").upper()\r\n fn(uniqueInput)\r\n elif subMenu == \"3\":\r\n break\r\n continue\r\n\r\ndef fnShowCar(unique = None):\r\n if unique == None:\r\n print(''' | carID | Plate Number | Car Type | Car Name | Price | Status |''')\r\n for i in range (len(carList)):\r\n print(f''' | {carList[i][\"carID\"]} | {carList[i][\"plateNum\"]} | {carList[i][\"carType\"]}\\t | {carList[i][\"carName\"]}\\t| {carList[i][\"price\"]} | {carList[i][\"status\"]}\\t |''')\r\n continue\r\n elif unique != None:\r\n print(''' | carID | Plate Number | Car Type | Car Name | Price | Status |''') \r\n for i in range (len(carList)):\r\n if carList[i]['carType'] == unique: \r\n print(f''' | {carList[i][\"carID\"]} | {carList[i][\"plateNum\"]} | {carList[i][\"carType\"]}\\t | {carList[i][\"carName\"]}\\t| {carList[i][\"price\"]} | {carList[i][\"status\"]}\\t |''')\r\n continue\r\n \r\n\r\ndef fnAddCar():\r\n newCarID = input(\" Enter New Car ID to : \").title()\r\n newPlateNum = input(f\" Enter Plate Number for {newCarID}: \").upper()\r\n newCarType = input(f\" Enter Car Type for {newCarID}: \").upper()\r\n newCarName = input(f\" Enter Car Name for {newCarID}: \").capitalize()\r\n newPrice = int(input(f\" Enter Price ID for {newCarID}: \"))\r\n for i in range (len(carList)):\r\n if newPlateNum == carList[i][\"plateNum\"]:\r\n print(\"\\n This car is already on the database\")\r\n break\r\n else:\r\n while True:\r\n confirmation = input(f\" Are you sure you want to add '{newCarID}' to the database? (Y/N): \").capitalize()\r\n if confirmation == \"Y\":\r\n carList.append({\"carID\" : newCarID, \"plateNum\" : newPlateNum, \"carType\" : newCarType, \"carName\" : newCarName, \"price\" : newPrice, \"status\" : \"Available\"})\r\n break\r\n elif confirmation == \"N\":\r\n print(\"\\n Data cancelled to be add\")\r\n break\r\n else:\r\n print(\"\\n Please try again \\n\")\r\n continue\r\n\r\n fnShowCar()\r\n\r\ndef fnDeleteCar():\r\n fnShowCar()\r\n deleteCar = input(\"\\n Enter Car ID delete: \").lower()\r\n for i in range (len(carList)):\r\n if deleteCar == carList[i][\"carID\"]:\r\n while True:\r\n confirmation = input(f\" Are you sure you want to delete '{carList[i]['carID']}'? (Y/N): \").capitalize()\r\n if confirmation == \"Y\":\r\n del(carList[i])\r\n print(f\"\\n Data have been deleted on database\")\r\n break\r\n elif confirmation == \"N\":\r\n print(\"\\n Data cancelled to be delete\\n\")\r\n break\r\n else:\r\n print(\"\\n Please try again \\n\")\r\n continue\r\n break\r\n else:\r\n print(\"\\n Data doesn't exist\")\r\n fnShowCar()\r\n\r\ndef fnUpdateCar():\r\n fnShowCar()\r\n updateCar = input(\"\\n Enter Car ID to Update: \").lower()\r\n for i in range (len(carList)):\r\n if updateCar == carList[i][\"carID\"]:\r\n while True:\r\n updatePlateNum = input(f\" Enter Plate Number for {updateCar}: \").upper()\r\n updatePrice = int(input(f\" Enter Price for {updateCar}: \")) \r\n confirmation = input(f\" Are you sure you want to update '{updateCar}' from your list? (Y/N): \").capitalize()\r\n if confirmation == \"Y\":\r\n carList[i][\"plateNum\"] = updatePlateNum\r\n carList[i][\"price\"] = updatePrice\r\n print(f\"\\n {updateCar} have been updated on database\")\r\n break\r\n elif confirmation == \"N\":\r\n print(\"\\n ok\")\r\n break\r\n else:\r\n print(\"\\n Please try again \\n\")\r\n continue\r\n break\r\n else:\r\n print(\"\\n Data doesn't exist\")\r\n fnShowCar()\r\n\r\ndef fnRentCar():\r\n fnShowCar()\r\n rentCar = input(\"\\n Enter Car ID to rent: \").lower()\r\n for i in range (len(carList)):\r\n if rentCar == carList[i][\"carID\"]:\r\n if carList[i][\"status\"] == \"Available\":\r\n rentTime = int(input(\"\\n Enter the number of day to rent: \"))\r\n rentName = input(\"\\n Enter customer name: \").title()\r\n rentNoHP = input(\"\\n Enter customer phone number: \").title()\r\n while True:\r\n confirmation = input(f\" Are you sure you want to borrow '{carList[i]['carName']} {carList[i]['plateNum']}' for {rentTime} day(s)? (Y/N): \").capitalize()\r\n if confirmation == \"Y\":\r\n carList[i][\"status\"] = \"Rented\"\r\n total = rentTime * carList[i][\"price\"]\r\n rentedCarReport.append(\r\n [rentName, rentNoHP, carList[i]['carID'],carList[i]['plateNum'],carList[i]['carType'], carList[i]['carName'], carList[i]['price'], rentTime, total]\r\n )\r\n print((f'''\r\n --------------------------------------------\r\n {rentName} rented {carList[i]['carName']} {carList[i]['plateNum']} for {rentTime} day(s)\r\n The data have been updated\r\n --------------------------------------------\r\n The total bill is IDR {total}'''))\r\n break\r\n elif confirmation == \"N\":\r\n print(\"\\n ok\")\r\n break\r\n else:\r\n print(\"\\n Please try again \\n\")\r\n continue\r\n break\r\n else:\r\n print(\"\\n This car is currently rented\")\r\n break\r\n else:\r\n print(\"\\n Data doesn't exist\")\r\n\r\ndef carReport():\r\n print(''' | Cust. Name | Telp. Number | carID | Plate Number | Car Type | Car Name | Price | Rent Time | Total |''')\r\n for i in range (len(rentedCarReport)):\r\n print(f''' | {rentedCarReport[i][0]}\\t | {rentedCarReport[i][1]} | {rentedCarReport[i][2]} | {rentedCarReport[i][3]} | {rentedCarReport[i][4]}\\t | {rentedCarReport[i][5]}\\t | {rentedCarReport[i][6]} | \\t{rentedCarReport[i][7]}\\t| {rentedCarReport[i][8]} |''')\r\n continue \r\n\r\ndef fnReturnCar():\r\n carReport()\r\n returnCar = input(\"\\n Enter Car ID to return: \").lower()\r\n for i in range (len(carList)):\r\n if returnCar == carList[i][\"carID\"]:\r\n if carList[i][\"status\"] != \"Available\":\r\n while True:\r\n confirmation = input(f\" Are you sure you want to return '{carList[i]['carName']} {carList[i]['plateNum']}'? (Y/N): \").capitalize()\r\n if confirmation == \"Y\":\r\n carList[i][\"status\"] = \"Available\"\r\n print(f\"\\n Thank you for returning '{carList[i]['carName']} {carList[i]['plateNum']}' \")\r\n for item in range(len(rentedCarReport)):\r\n if returnCar == rentedCarReport[item][2]:\r\n del rentedCarReport[item]\r\n break\r\n elif confirmation == \"N\":\r\n print(\"\\n ok\")\r\n break\r\n else:\r\n print(\"\\n Please try again \\n\")\r\n continue\r\n else:\r\n print(\"\\n This car doesn't need to be returned.\")\r\n break\r\n else:\r\n print(\"\\n Data doesn't exist\")\r\n\r\n\r\n# Loop\r\nwhile True:\r\n mainMenu = input('''\r\n --------------------------------\r\n Welcome to Tyodh Garage \r\n --------------------------------\r\n 1. Show Car on Database \r\n 2. Add New Car\r\n 3. Delete Data\r\n 4. Update Data\r\n 5. Rent Car\r\n 6. Return Car\r\n 7. Rented Car Report\r\n 8. Exit Garage\r\n\r\n Enter your request (1-8): ''')\r\n\r\n if mainMenu == \"1\":\r\n fnSubMenu1(fnShowCar, \"Show All Cars in the Garage\", \"Show Car with Specific Car Type\")\r\n\r\n elif mainMenu == \"2\":\r\n fnSubMenu(fnAddCar, \"Add New Car to The Garage\")\r\n\r\n elif mainMenu == \"3\":\r\n fnSubMenu(fnDeleteCar, \"Delete Existing Car from The Garage\") \r\n\r\n elif mainMenu == \"4\":\r\n fnSubMenu(fnUpdateCar, \"Update the Data from the list\")\r\n\r\n elif mainMenu == \"5\":\r\n fnSubMenu(fnRentCar, \"Rent Car from The Garage\")\r\n\r\n elif mainMenu == \"6\":\r\n fnSubMenu(fnReturnCar, \"Return Car from The Garage\")\r\n\r\n elif mainMenu == \"7\":\r\n fnSubMenu(carReport, \"Show Rented Car Report\")\r\n\r\n elif mainMenu == \"8\":\r\n print('''\\n Thank you for visiting Tyodh Garage!\r\n ''')\r\n break\r\n else:\r\n print('''\\n Please try again ''')","repo_name":"tyodwikip/Capstone_Project_Module1","sub_path":"capstoneproject1.py","file_name":"capstoneproject1.py","file_ext":"py","file_size_in_byte":10981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8956026440","text":"# The Data we need to retrieve.\n# 1. The total number of votes cast\n# 2. A complete list of candidates who received votes\n# 3. The percentage of votes each candidate won\n# 4. The total number of votes each candidate won\n# 5. The winner of the election based on popular vote. \n\n\n# Add our dependencies.\nimport csv\nimport os\n# Assign a variable to load a file from a path.\nfile_to_load = os.path.join(\"Resources/election_results.csv\")\n# Assign a variable to save the file to a path.\nfile_to_save = os.path.join(\"analysis\", \"election_analysis.txt\")\n# Initialize a total vote counter.\ntotal_votes = 0\n# Candidate options and candidate votes.\ncandidate_options = []\ncandidate_votes = {}\n# Create a list for counties.\ncounties_names = []\n# Create a dictionary \n# where the county is the key and the votes \n# cast for each county in the election are the values.\ncounties_votes = {}\n# Track the winning candidate, vote count, and percentage.\nwinning_candidate = \"\"\nwinning_count = 0\nwinning_percentage = 0\n#Create an empty string that will hold the county name that had the largest turnout.\nLargest_county_turnout = \"\"\nLargest_county_count = 0\nLargest_county_percentage = 0\n# Open the election results and read the file.\nwith open(file_to_load) as election_data:\n file_reader = csv.reader(election_data)\n # Read the header row.\n headers = next(file_reader)\n # Print each row in the CSV file.\n for row in file_reader:\n # Add to the total vote count.\n total_votes += 1\n # Get the candidate name from each row.\n candidate_name = row[2]\n # If the candidate does not match any existing candidate, add the\n # the candidate list.\n if candidate_name not in candidate_options:\n # Add the candidate name to the candidate list.\n candidate_options.append(candidate_name)\n # And begin tracking that candidate's voter count.\n candidate_votes[candidate_name] = 0\n # Add a vote to that candidate's count.\n candidate_votes[candidate_name] += 1\n # Challenge\n # Declare a variable that represents the number of votes that a county received. \n # Hint: Inside a for loop, add an if statement to check if the county name has already been recorded. \n # If not, add it to the list of county names.\n county_name = row[1]\n if county_name not in counties_names:\n # Add the county name to the county list.\n counties_names.append(county_name)\n # And begin tracking that county's voter count.\n counties_votes[county_name] = 0\n # Add a vote to that county's count.\n counties_votes[county_name] += 1\n\n# Save the results to our text file.\nwith open(file_to_save, \"w\") as txt_file:\n # Print the final vote count to the terminal + County Votes Summary.\n election_results = (\n f\"\\nElection Results\\n\"\n f\"-------------------------\\n\"\n f\"Total Votes: {total_votes:,}\\n\"\n f\"-------------------------\\n\"\n f\"\\nCounty Votes:\\n\")\n print(election_results, end=\"\")\n # Save the final vote count to the text file.\n txt_file.write(election_results)\n \n# Inside the with open() function where you are outputting the file, do the following:\n# Create three if statements to print out the voter turnout results similar to the results shown above.\n# Add the results to the output file.\n# Print the results to the command line.\n for county in counties_votes:\n # Retrieve vote count and percentage for each county.\n vote = counties_votes[county]\n votes_percentage = float(vote) / float(total_votes) * 100\n county_results = (f\"{county}: {votes_percentage:.1f}% ({vote:,})\\n\")\n\n\n # Print each county's voter count and percentage to the terminal.\n print(county_results)\n # Save the county results to our text file.\n txt_file.write(county_results)\n # Determine largest county vote count, largest county percentage, and largest county turnout.\n if (vote > Largest_county_count) and (votes_percentage >Largest_county_percentage):\n Largest_county_count = vote\n Largest_bounty_turnout = county\n Largest_county_percentage = votes_percentage\n # Print the largest county's results to the terminal.\n Largest_county_summary = (\n f\"\\n-------------------------\\n\"\n f\"Largest County Turnout: {Largest_bounty_turnout}\\n\"\n f\"-------------------------\\n\")\n print(Largest_county_summary)\n # Save the largest county's results to the text file.\n txt_file.write(Largest_county_summary)\n \n \n for candidate in candidate_votes:\n # Retrieve vote count and percentage.\n votes = candidate_votes[candidate]\n vote_percentage = float(votes) / float(total_votes) * 100\n candidate_results = (\n f\"{candidate}: {vote_percentage:.1f}% ({votes:,})\\n\")\n\n\n\n # Print each candidate's voter count and percentage to the terminal.\n print(candidate_results)\n # Save the candidate results to our text file.\n txt_file.write(candidate_results)\n # Determine winning vote count, winning percentage, and winning candidate.\n if (votes > winning_count) and (vote_percentage > winning_percentage):\n winning_count = votes\n winning_candidate = candidate\n winning_percentage = vote_percentage\n # Print the winning candidate's results to the terminal.\n winning_candidate_summary = (\n f\"-------------------------\\n\"\n f\"Winner: {winning_candidate}\\n\"\n f\"Winning Vote Count: {winning_count:,}\\n\"\n f\"Winning Percentage: {winning_percentage:.1f}%\\n\"\n f\"-------------------------\\n\")\n print(winning_candidate_summary)\n # Save the winning candidate's results to the text file.\n txt_file.write(winning_candidate_summary)\n\n\n\n\n\n\n \n\n\n","repo_name":"keyoumao/Election_Analysis","sub_path":"PyPoll_Challenge.py","file_name":"PyPoll_Challenge.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41306945601","text":"from Agents.RandomAgent import *\nfrom Agents.HumanAgent import *\nfrom Agents.Knuth import *\nfrom Agents.RandomEligibleAgent import *\nfrom Agents.Player import *\nfrom Agents.GeneticAlgorithmAgent import *\nimport time\n\n\n\ndef doKnuthTests(numberOfTrials, firstGuess = makeCode([1,1,2,2])):\n guessesNeeded = 0\n timeNeeded = 0\n print(\"Trial Number: \", end=\"\")\n for i in range(numberOfTrials):\n if i % 10 == 0:\n print(i+1, end=\" \")\n newGame = GameManager()\n newGame.generateCode()\n knuth = Knuth(newGame, firstGuess = firstGuess)\n start = time.time()\n guessesNeeded += knuth.play()\n timeNeeded += time.time()-start\n print()\n print(\"Average guesses needed:\", guessesNeeded/numberOfTrials)\n print(\"Average time needed:\", timeNeeded/numberOfTrials)\n\ndef doGeneticTests(numberOfTrials, verbose=False, seeCode=False, firstGuess = makeCode([1]*PIN_NUMBER), popSize = 150, maxGen = 100, maxSize = 60,\n onePointCrossoverProb = .5, colorChangeProb = .03, permutationProb = .03, inversionProb = .02, a = 1, b = 2, EHatChoiceMethod = \"min\",\n fitnessMethod = \"changed\"):\n guessesNeeded = 0\n timeNeeded = 0\n print(\"Trial Number: \", end=\"\")\n for i in range(numberOfTrials):\n if i % 1 == 0:\n print(i+1, end=\" \")\n newGame = GameManager()\n newGame.generateCode()\n genny = GeneticAlgorithmAgent(newGame, verbose, seeCode, firstGuess, popSize, maxGen, maxSize, onePointCrossoverProb, colorChangeProb, permutationProb, inversionProb, a, b, EHatChoiceMethod, fitnessMethod)\n start = time.time()\n guessesNeeded += genny.play()\n timeNeeded += time.time()-start\n print()\n print(\"Average guesses needed:\", guessesNeeded / numberOfTrials)\n print(\"Average time needed:\", timeNeeded / numberOfTrials)\n\n\n\nif __name__ == \"__main__\":\n \"\"\"\n This file is designed to test and compare the efficiency (i.e., runtime) and performance (i.e., average number of needed guesses)\n of the genetic algorithm and Knuth's algorithm.\n Note how subtle differences in the genetic algorithm's parameters can drastically change its effectiveness.\n \"\"\"\n print(\"Knuth algorithm:\")\n doKnuthTests(500)\n print(\"Genetic algorithm:\")\n doGeneticTests(100, firstGuess=makeCode([1,1,2,3]))\n print(\"Genetic algorithm (speedier):\")\n doGeneticTests(100, firstGuess=makeCode([1,1,2,3]), EHatChoiceMethod=\"random\")\n print(\"Genetic algorithm (with old fitness method):\")\n doGeneticTests(100, firstGuess=makeCode([1,1,2,3]), fitnessMethod=\"original\", EHatChoiceMethod=\"random\")\n","repo_name":"lprehn/MasterMind","sub_path":"findEfficiency.py","file_name":"findEfficiency.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"72419495957","text":"import cv2 as cv\nimport numpy as np\nfrom os.path import join\n\nIMAGE_DIR = r\"images\"\nIMAGE_NAME = r\"wiki_ind\"\nIMAGE_EXT = r\".jpg\"\nIMAGE_PATH = join(IMAGE_DIR, IMAGE_NAME+IMAGE_EXT)\nX_START = Y_START = -3\nX_STOP = Y_STOP = 3\nKERNEL_CENTRE_X = KERNEL_CENTRE_Y = X_STOP\n\n\ndef read_image(path):\n image = cv.imread(path)\n image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n return image_gray\n\ndef laplacian_of_gaussian_2d(x, y):\n # Exponent part of gaussain function mean=0, sd=1\n power_part = (np.power(x, 2.) + np.power(y, 2.)) / 2.\n exp_part = np.exp(-power_part)\n prod_part = (-1./np.pi) * (1. - power_part)\n return prod_part * exp_part\n\ndef get_log_kernel():\n kernel_shape = (X_STOP-X_START+1, Y_STOP-Y_START+1)\n log_sample = np.zeros(shape=kernel_shape, dtype=float)\n ker_x = ker_y = 0\n for x_idx in range(X_START, X_STOP+1):\n for y_idx in range(Y_START, Y_STOP+1):\n log_sample[ker_x][ker_y] = laplacian_of_gaussian_2d(x_idx, y_idx)\n ker_y = ker_y + 1 # updating index\n ker_x = ker_x + 1 # Updating index\n ker_y = 0\n return log_sample\n\ndef apply_kernel_repeat(src_image, kern2d, repetition=1):\n filtered_img = src_image\n for idx in range(repetition):\n filtered_img = cv.filter2D(filtered_img,ddepth=-1,kernel=kern2d)\n return filtered_img\n\n\nlog_ker = get_log_kernel()\n# Supressing scientific notation\nnp.set_printoptions(suppress=True)\nprint(log_ker)\n\nsum_kernel = np.sum(log_ker)\nprint(\"Kernel Sum\", sum_kernel)\n# Add sum to centre of kernel\nlog_ker[KERNEL_CENTRE_X][KERNEL_CENTRE_Y] = log_ker[KERNEL_CENTRE_X][KERNEL_CENTRE_Y] - sum_kernel\nsum_kernel = np.sum(log_ker)\nprint(\"Kernel Sum (after adjustment)\", sum_kernel)\n\n# Multiply kernel\nlog_ker = log_ker * 10.0\nprint(\"After Scaling:\", log_ker)\n\n# Image reading\nimage = read_image(IMAGE_PATH)\ncv.imshow(\"Input Image\", image)\n# Apply kernel\nimage_filtered = apply_kernel_repeat(image, log_ker, repetition=1)\ncv.imshow(\"Filtered Image\", image_filtered)\nfilt_img_name = join(IMAGE_DIR, IMAGE_NAME+\"_log_filt\"+IMAGE_EXT)\ncv.imwrite(filt_img_name, image_filtered)\n# Add to original image\nimage_add = image - image_filtered\ncv.imshow(\"Image LOG Add\", image_add)\nimg_add_name = join(IMAGE_DIR, IMAGE_NAME+\"_log_add\"+IMAGE_EXT)\ncv.imwrite(img_add_name, image_add)\n\ncv.waitKey()\ncv.destroyAllWindows()","repo_name":"bpbpublications/Practical-Mathematics-for-AI-and-Deep-Learning","sub_path":"Chapter 09/laplacian_of_gaussian.py","file_name":"laplacian_of_gaussian.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"9225661188","text":"from historical_sources.transformer_modules import *\r\nimport matplotlib.pyplot as plt\r\nfrom collections import defaultdict\r\nimport pandas as pd\r\nimport string, re, os\r\nimport math, random\r\nimport logging\r\nimport sysconfig\r\nimport argparse\r\n\r\nfrom pdb import set_trace as st\r\ncwd = str(sysconfig.get_paths()[\"purelib\"]) + '/historical_sources'\r\nconfig_file = cwd + '/predictor_configuration.json'\r\nlogging.basicConfig(\r\n level=logging.INFO,\r\n format='%(asctime)s %(message)s',\r\n datefmt='%m/%d/%Y %I:%M:%S %p')\r\n\r\ndef make_prediction(val_pair, n_demo, out_dir):\r\n if not (n_demo < 0 or isinstance(n_demo, str)):\r\n # Create duplicates of the same input query to make multiple predictions\r\n val_pairs = [val_pair] * n_demo\r\n save_predictions(pairs=val_pairs,\r\n to_file_path=out_dir + 'val_predictions.csv')\r\n\r\n logging.info(\"KBC FOR VALIDATION SET WRITTEN TO {}\".format(\r\n out_dir + 'val_predictions.csv'))\r\n return None\r\n else:\r\n # Get a unique prediction for the imput query, and \r\n inp = val_pair[0]\r\n return decode_sequence(inp)\r\n\r\n(dataset_name,\r\nn_epochs,\r\nstack_size,\r\nsequence_length,\r\nmax_features,\r\nbatch_size,\r\nkey_dim,\r\nmodel_dim,\r\nlatent_dim,\r\nnum_heads,\r\nout_dir) = get_config(config_file)\r\n\r\n#n_demo = 10\r\nn_demo = -1\r\n\r\nif os.path.isdir(out_dir):\r\n logging.info(\"Loading Vectorizers\")\r\nelse:\r\n logging.error(\"NO model trained and directory with specified parameters\"\r\n \" exists in: {}\".format(config_file))\r\n exit()\r\n\r\n\r\nes_callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss',\r\n patience=10,\r\n min_delta=0.005,\r\n mode='auto',\r\n restore_best_weights=True,\r\n verbose=1)\r\n#logging.info(\"OBTAINING PREDICTION FOR INPUT QUERY...\")\r\n\r\n\"\"\"\r\nThe inputs 'Subject_Predicate' and 'Object' should be provided by a function\r\nimplementing the Allen AI's Semantic Role Labeling method. I set their values\r\nfor testing purposes:\r\n\"\"\"\r\ndef predictor(val_pair):\r\n global n_demo, out_dir\r\n return make_prediction(val_pair, n_demo, out_dir)\r\n\r\ndef train(dataFile):\r\n testFile=cwd+ '/datasets/results200.tsv'\r\n with open(dataFile) as f:\r\n train_text = f.readlines()\r\n with open(testFile) as f:\r\n test_text = f.readlines()\r\n\r\n train_pairs = list(\r\n map(functools.partial(\r\n prepare_data), train_text))\r\n test_pairs= list(\r\n map(functools.partial(\r\n prepare_data), test_text))\r\n train_in_texts = [pair[0] for pair in train_pairs]\r\n train_out_texts = [pair[1] for pair in train_pairs]\r\n\r\n input_vectorizer = layers.experimental.preprocessing.TextVectorization(\r\n output_mode=\"int\", max_tokens=max_features,\r\n # ragged=False, # only for TF v2.7\r\n output_sequence_length=sequence_length,\r\n standardize=custom_standardization)\r\n\r\n output_vectorizer = layers.experimental.preprocessing.TextVectorization(\r\n output_mode=\"int\", max_tokens=max_features, # ragged=False,\r\n output_sequence_length=sequence_length+1,\r\n standardize=custom_standardization)\r\n\r\n input_vectorizer.adapt(train_in_texts)\r\n output_vectorizer.adapt(train_out_texts)\r\n #saving the vectorizers also\r\n save_vectorizer(\r\n vectorizer=input_vectorizer, to_file=out_dir+'in_vect_model')\r\n save_vectorizer(\r\n vectorizer=output_vectorizer, to_file=out_dir+'out_vect_model')\r\n train_ds = make_dataset(train_pairs)\r\n test_ds = make_dataset(test_pairs)\r\n logging.info(\"Training Transformer Semantic EncoDec\")\r\n history = transformer.fit(train_ds,\r\n epochs=n_epochs,\r\n validation_data=test_ds,\r\n callbacks=[ #cp_callback,\r\n es_callback])\r\n logging.info(\"TRAINED!!\")\r\n rdf = pd.DataFrame(history.history)\r\n rdf.to_csv(out_dir + \"history.csv\")\r\n fig, axes = plt.subplots(2, 1)\r\n rdf[sort_cols(rdf.columns)].iloc[:, :2].plot(ax=axes[0])\r\n axes[0].grid(b=True,which='major',axis='both',linestyle='--')\r\n rdf[sort_cols(rdf.columns)].iloc[:, 2:].plot(ax=axes[1])\r\n axes[1].grid(b=True,which='major',axis='both',linestyle='--')\r\n plt.savefig(out_dir + 'history_plot.pdf')\r\n \"\"\" Notes about saving the model weights:\r\n - must be the same paramers when you load the model\r\n - if you specify a directory, you will save them without a prefix\r\n \"\"\"\r\n logging.info(\"Saving learned weights to {}\\n\".format(\r\n out_dir+'transformer_model_weights/model'))\r\n transformer.save_weights(out_dir+'transformer_model_weights/model')\r\n\r\n","repo_name":"VilmaGlez/historical_sources","sub_path":"historical_sources/transformer_predictor.py","file_name":"transformer_predictor.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70084636439","text":"'''\n@Author: your name\n@Date: 2020-06-16 10:54:53\n@LastEditTime: 2020-06-17 11:13:26\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: /Cracking_the_Code_Interview/Leetcode/Singly_Linked_List/142.Linked_List_Cycle_II.py\n'''\n# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.\n\n# To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.\n\n# Note: Do not modify the linked list.\n\n# class Solution:\n# def detectCycle(self, head: ListNode):\n# runner = walker = head\n# while runner and runner.next:\n# runner = runner.next.next\n# walker = walker.next\n# if runner == walker:\n# seeker = head\n# while seeker != walker:\n# walker = walker.next\n# seeker = seeker.next\n# return walker\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef _mergeLists(self,a, b):\n tail = a\n head = a\n a = a.next\n while b:\n tail.next = b\n tail = tail.next\n b = b.next\n if a:\n a, b = b, a \n return head\n\ndef _reverseList(head):\n last = None\n currentNode = head\n while currentNode:\n currentNode.next = last\n last = currentNode\n currentNode = currentNode.next\n return last\n\ndef printList(node) : \n while (node!=None):\n print(node.val,end=\" \")\n node = node.next\na = ListNode(1)\na.next = ListNode(2)\na.next.next = ListNode(3)\nprintList(a)\n\nb = ListNode(5)\nb.next = ListNode(4)\nprintList(b)\n\ndef _mergeLists(a, b):\n l1 = a \n while (b):\n next = l1.next\n l1.next = b\n b = b.next\n l1.next.next = next \n l1 = next \n_mergeLists(a,b)\nprintList(_reverseList(a))","repo_name":"lzxyzq/Cracking_the_Coding_Interview","sub_path":"Cracking_the_Code_Interview/Leetcode/2.Singly_Linked_List/142.Linked_List_Cycle_II.py","file_name":"142.Linked_List_Cycle_II.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"31057141588","text":"import os\nimport time\nimport logging\nimport shlex\nimport subprocess\n\nfrom gateway_code.common import logger_call\nfrom gateway_code.open_nodes.common.node_no import NodeNoBase\nfrom gateway_code.utils.lora_gateway_bridge import LoraGatewayBridge\nfrom gateway_code.utils.mosquitto import Mosquitto\n\nLOGGER = logging.getLogger('gateway_code')\nLOG_DIR = '/var/log/gateway-server'\nLORA_PKT_FORWARDER_START_CMD = ('sudo ' # needs to be root to access GPIO\n 'CFG_DIR=/var/local/config /opt/lora/start.sh')\nLORA_PKT_FORWARDER_MAX_TRIES = 50\n\n\nclass NodeLoraGateway(NodeNoBase):\n \"\"\" Open node LoRa gateway implementation \"\"\"\n\n TYPE = 'lora_gw'\n MOSQUITTO_PORT = 1883\n\n def __init__(self):\n self.lora_pkt_fwd_out = open(os.devnull, 'w')\n self._start_lora_pkt_fwd()\n self.mosquitto = Mosquitto(self.MOSQUITTO_PORT)\n self.lora_gateway_bridge = LoraGatewayBridge()\n\n @staticmethod\n def _lora_pkt_fwd_pid():\n try:\n return subprocess.check_output(shlex.split('pgrep lora_pkt_fwd'))\n except subprocess.CalledProcessError:\n return None\n\n def _start_lora_pkt_fwd(self):\n _pid = self._lora_pkt_fwd_pid()\n if _pid is None:\n LOGGER.debug(\"Starting lora_pkt_fwd\")\n _tries = 0\n # Sometimes the lora_pkt_forwarder fails to start so try multiple\n # times.\n while _pid is None and _tries <= LORA_PKT_FORWARDER_MAX_TRIES:\n subprocess.Popen(shlex.split(LORA_PKT_FORWARDER_START_CMD),\n stdout=self.lora_pkt_fwd_out,\n stderr=self.lora_pkt_fwd_out)\n time.sleep(2)\n _pid = self._lora_pkt_fwd_pid()\n if _pid is None:\n LOGGER.debug(\"Restarting lora_pkt_fwd\")\n _tries += 1\n LOGGER.debug(\"lora_pkt_forwarder started\")\n\n def __del__(self):\n self.lora_pkt_fwd_out.close()\n\n @logger_call(\"Node LoRa gateway: Setup node\")\n def setup(self, firmware_path=None):\n \"\"\"Start mosquitto and the gateway bridge.\"\"\"\n ret_val = self.mosquitto.start()\n ret_val += self.lora_gateway_bridge.start()\n return ret_val\n\n @logger_call(\"Node LoRa gateway: teardown node\")\n def teardown(self):\n \"\"\"Stop the gateway bridge and mosquitto.\"\"\"\n ret_val = self.lora_gateway_bridge.stop()\n ret_val += self.mosquitto.stop()\n return ret_val\n","repo_name":"iot-lab/iot-lab-gateway","sub_path":"gateway_code/open_nodes/node_lora_gateway.py","file_name":"node_lora_gateway.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"85"} +{"seq_id":"19777923167","text":"from customtkinter import *\nfrom modules.frames import CopyWidgets, MoveWidgets, DeleteWidgets\n\napp = CTk()\napp.geometry(\"900x600\")\napp.grid_rowconfigure(0, weight=1)\napp.grid_columnconfigure(0, weight=1)\napp.title(\"Yet Another Dev Tools\")\n\nset_appearance_mode(\"system\")\nset_default_color_theme(\"dark-blue\")\n\nmove_widgets = MoveWidgets(master_app=app)\nmove_widgets.frame()\n\ncopy_widgets = CopyWidgets(master_app=app)\ncopy_widgets.frame()\n\nrename_widgets = DeleteWidgets(master_app=app)\nrename_widgets.frame()\n\napp.mainloop()\n","repo_name":"djjohns/YADT","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34116726242","text":"\"\"\"\n Given a circular array (the next element of the last element is \n the first element of the array), print the Next Greater Number \n for every element. The Next Greater Number of a number x is the \n first greater number to its traversing-order next in the array, \n which means you could search circularly to find its next greater \n number. If it doesn't exist, output -1 for this number.\n\n Example:\n Input: [1,2,1]\n Output: [2,-1,2]\n Explanation: The first 1's next greater number is 2;\n\t The number 2 can't find next greater number;\n\t The second 1's next greater number needs to \n search circularly, which is also 2.\n\n Note: The length of given array won't exceed 10000.\n\"\"\"\n#Difficulty: Medium\n#224 / 224 test cases passed.\n#Runtime: 3468 ms\n#Memory Usage: 15.8 MB\n\n#Runtime: 3468 ms, faster than 10.47% of Python3 online submissions for Next Greater Element II.\n#Memory Usage: 15.8 MB, less than 39.94% of Python3 online submissions for Next Greater Element II.\n\nclass Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n length = len(nums)\n nums += nums\n for i in range(length):\n for j in range(i, i+length):\n if nums[i] < nums[j]:\n nums[i] = nums[j]\n break\n else:\n nums[i] = -1\n return nums[:length]\n","repo_name":"YuriSpiridonov/LeetCode","sub_path":"Medium/503.NextGreaterElementII.py","file_name":"503.NextGreaterElementII.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"85"} +{"seq_id":"6256372032","text":"from flask import render_template, url_for, redirect, request, redirect\nfrom backend import app\nfrom backend.key import YELP_API_KEY, STRIPE_API_KEY, STRIPE_SECRET_KEY\nfrom pdb import set_trace as bp\n# uncomplete library\n# from yelp.client import Client\nimport json\nimport requests\nimport stripe\n\nheaders = {\n\t'Content-Type': 'application/json',\n\t'Authorization': 'Bearer %s' % YELP_API_KEY,\n}\n\nstripe.api_key = STRIPE_SECRET_KEY\n\n@app.route('/')\ndef home():\n\treturn render_template('index.html')\n\n@app.route('/api/opentable')\ndef opentable():\n\treturn ''\n\n@app.route('/api/yelp')\ndef yelp():\n\t# initialize client\n\t# client = Client(YELP_API_KEY)\n\t# business_response = client.business.get_by_id('yelp-san-francisco')\n\t# print business_response.json()\n\t# response = client.business.get_by_location('94404')\n\tapi_url_base = 'https://api.yelp.com/v3/businesses/search?term=restaurant&attributes=reservation&'\n\tlocation = request.args.get('location')\n\turl = api_url_base + 'location=' + location\n\tresponse = requests.get(url, headers=headers)\n\tif response.status_code == 200:\n\t\treturn response.content, 200\n\telse:\n\t\treturn {'error': 'Cannot get restaurant information, try again later'}\n\n@app.route('/api/yelp/biz')\ndef biz():\n\tapi_url_base = 'https://api.yelp.com/v3/businesses/'\n\tid = request.args.get('id')\n\turl = api_url_base + id\n\tresponse = requests.get(url, headers=headers)\n\tif response.status_code == 200:\n\t\treturn response.content, 200\n\telse:\n\t\treturn 'something wrong'\n\t\t\n\n@app.route('/api/yelp/book')\ndef book():\n\tapi_url_base = 'https://www.yelp.com/reservations/'\n\talias = request.args.get('alias')\n\tdate = request.args.get('date')\n\ttime = request.args.get('time')\n\tcovers = request.args.get('covers')\n\turl = '{}{}?date={}&time={}&covers={}&source=yelp_biz'.format(api_url_base, alias, date, time, covers)\n\t# print(url)\n\tresponse = requests.get(url)\n\tif response.status_code == 200:\n\t\treturn response.content, 200\n\telse:\n\t\treturn 'failed'\n\n@app.route('/api/stripe/pay', methods=['GET', 'POST'])\ndef pay():\n\tif request.method == 'POST':\n\t\tdata = request.get_json()\n\t\ttoken = data['token']\n\t\tamount = data['amount']\n\n\t\tcharge = stripe.Charge.create(\n\t\t\tamount = int(amount * 100),\n\t\t\tcurrency = 'usd',\n\t\t\tdescription = 'Test charge',\n\t\t\tsource = token,\n\t\t\tstatement_descriptor = 'Customize description',\n\t\t\tmetadata = {'order_id': 1234},\n\t\t\treceipt_email = 'angelia.fan@gmail.com',\n\t\t)\n\n\t\t# Stripe is using webhook, need to build another api call for stripe to get information back\n\telse:\n\t\treturn 'testing get api call'\n\n@app.route('/api/stripe/widget', methods=['GET'])\ndef stripe_widget():\n\ttoken = request.args.get('stripeToken')\n\temail = request.args.get('stripeEmail')\n\treturn redirect(url_for('home'))\n","repo_name":"LuuuFan/reservation","sub_path":"backend/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"20129479442","text":"import discord\nfrom config import *\nimport datetime\n\nasync def help(ctx, command):\n commandList = commandTree.get_commands(type=discord.AppCommandType.chat_input)\n if command is None:\n embed = discord.Embed(title=commandListTitle, description=commandListDesc)\n embed.set_footer(text=commandListFooter)\n embed.timestamp = datetime.datetime.now()\n for commandObject in commandList:\n embed.add_field(name=commandObject.name, value=commandObject.description)\n else:\n if command == \"quote\":\n detailInfos = helpCommandData[command][1].split(',')\n embedDescText = helpCommandData[command][0]\n embedDescText += '\\n' + detailInfos[0]\n footerText = commandListFooter\n else:\n footerText = helpCommandData[command][1]\n embedDescText = helpCommandData[command][0]\n embed = discord.Embed(title=\"/\" + command, description=embedDescText)\n embed.set_author(name=client.get_user(botId).name + '#' + client.get_user(botId).discriminator, url=\"https://discord.com/developers/applications/1073762890445766656/information\", icon_url=client.get_user(botId).avatar)\n if command == \"quote\":\n detailIndividualInfoDict = {}\n for detailIndividualInfo in detailInfos[1:]:\n detailIndividualInfoDict[detailIndividualInfo.split(':')[0]] = detailIndividualInfo.split(':')[1]\n print(detailIndividualInfoDict)\n for detailInfoTitle, detailInfoContent in detailIndividualInfoDict.items():\n embed.add_field(name=detailInfoTitle, value=detailInfoContent)\n embed.set_footer(text=footerText)\n embed.timestamp = datetime.datetime.now()\n await ctx.followup.send(embed=embed)","repo_name":"sousakak/ElainaBot","sub_path":"commands/helpCommand.py","file_name":"helpCommand.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12430108","text":"\"\"\"\nClasses for local execution of the jobs, without a queue system or a remote\ncluster.\nThere's no queue system so job id is always 0, and queue_parse always returns\n'complete'.\nLocalServer.complete will not return until the scripts finished its execution.\n\"\"\"\nfrom typing import Tuple, List, Any, Dict, Optional, Iterator, Callable, Union\nimport types\nimport logging\n\nfrom carcosa.cluster import ClusterServer, ClusterClient\nfrom carcosa import scripts\n\nJOB_ID = '0'\nSTATUS = 'complete'\n\n\nclass LocalServer(ClusterServer):\n @property\n def qsystem(self) -> str:\n return 'slurm'\n\n def metrics(self,\n job_id: Optional[int] = None) -> Iterator[Tuple[str, ...]]:\n \"\"\"\n Get job metrics from ``sacct``.\n \"\"\"\n logging.info('Getting job metrics')\n\n yield tuple([''] * 14)\n\n def queue_test(self) -> bool:\n \"\"\"\n Check if the slurm queue system is present in the node.\n\n Returns:\n is_present (bool)\n \"\"\"\n return True\n\n def submit(self, script_path: str) -> Optional[str]:\n \"\"\"\n Execute a job, this will **NOT** return until the script have executed,\n because there's no underlying queue system.\n\n Args:\n script_path (str):\n Path to the sbatch script\n\n Returns:\n job_id (str):\n ID of the submitted job\n \"\"\"\n args = ['bash', script_path]\n res = self.cmd(args)\n if res.returncode != 0:\n logging.error('Local job failed with code {}'.format(\n res.returncode)\n )\n return None\n return JOB_ID\n\n def kill(self, job_ids: List[Union[int, str]]) -> bool:\n \"\"\"\n Terminate all jobs in job_ids\n\n Args:\n job_ids (list)\n\n Returns:\n success (bool)\n \"\"\"\n return True\n\n def queue_parser(self, job_id: Optional[str] = None) \\\n -> Iterator[Tuple[str, ...]]:\n \"\"\"\n Get the information of the running jobs. Returns the job id and the\n state of the jobs.\n\n Args:\n job_id (int):\n Job ID to check.\n \"\"\"\n yield (JOB_ID, STATUS)\n\nclass LocalClient(ClusterClient):\n @property\n def server(self) -> LocalServer:\n if self._server is None:\n self._server = self._get_server()\n return self._server\n\n def cleanup(self) -> None:\n pass\n\n def _get_server(self) -> LocalServer:\n return LocalServer()\n\n def metrics(self, job_id: int = None) -> Iterator[Tuple[str, ...]]:\n return self.server.metrics(job_id=job_id)\n\n def gen_scripts(self,\n script: scripts.Script,\n options: Dict,\n function: Optional[Callable[..., Any]] = None,\n args: Optional[Tuple] = None,\n kwargs: Optional[Dict] = None,\n cmd: Optional[str] = None) -> bool:\n \"\"\"\n Generate the scripts to run the job in slurm. The job to run can be a\n python function or a plaintext command.\n\n To run a function a ``function``, ``args`` and ``kwargs`` arguments\n must be passed, if a function is passed the ``cmd`` attribute is\n ignored.\n\n If a function is not passed, a command may be passed through the\n ``cmd`` argument.\n\n Args:\n local_path (str):\n Path for the job in the local filesystem\n remote_path (str):\n Path for the job in the remote filesystem\n jobname (str):\n Identifier for the job, will be used to generate the scripts\n files\n options (dict):\n Options for sbatch. See :meth:`SlurmClient.parse_options` for\n the available arguments.\n function (types.FunctionType, optional):\n Function to be executed in the queue system\n args (tuple):\n Arguments to be passed to the function (only used if function\n is not None).\n kwargs (dict):\n Keyword arguments passed to the function (only used if function\n is not None)\n cmd (str):\n Command to be executed, if a function is passed this argument\n is not used.\n\n Returns:\n success (bool)\n \"\"\"\n if function:\n if not isinstance(function, types.FunctionType):\n raise TypeError(\n 'A function must be passed, not {}'.format(type(function))\n )\n\n # Execute the python file that loads and run the target\n # function.\n cmd = 'python {python_file}'.format(\n python_file=script.remote.filepath('python')\n )\n\n # Generate the python file that loads the marshal serialized\n # function, and runs it.\n with open(script.local.filepath('python'), 'w') as f:\n f.write(\n scripts.FUNC_RUNNER.format(\n marshal_file=script.remote.filepath('marshal'),\n out_file=script.remote.filepath('out')\n )\n )\n\n # Save the serialized function to a file.\n with open(script.local.filepath('marshal'), 'wb') as f:\n m_obj = (function.__code__, args, kwargs)\n try:\n marshal.dump(m_obj, f)\n except ValueError:\n logging.error(\n 'Marshal can not serialize some elements.'\n )\n self.cleanup()\n return False\n\n script_args = dict(\n precmd=self.parse_options(**options),\n name=script.name,\n command=cmd\n )\n\n # Generate the sbatch script that will be sent to slurm.\n with open(script.local.sbatch, 'w') as f:\n f.write(\n scripts.SCRIPT_RUNNER.format(script_args)\n )\n\n return True\n\n def submit(self, script: scripts.Script) -> str:\n \"\"\"\n Submit a job to slurm and get the job id\n\n Returns:\n job_id (str)\n \"\"\"\n return self.server.submit(script.remote.filepath('sbatch'))\n\n def parse_options(self, **kwargs: Any) -> str:\n \"\"\"\n Get options and convert it to the apropiate #SBATCH string.\n\n Args:\n kwargs (dict):\n Available options:\n\n - ``jname``: string (--job-name)\n - ``time``: string (--time) format: DD-HH:MM:SS\n - ``queue``: string (--qos)\n - ``workdir``: string (--workdir)\n - ``error``: string (--error)\n - ``output``: string (--output)\n - ``nodes``: int (--nodes)\n - ``ntasks``: int (--ntasks)\n - ``cpus_per_task``: int (--cpus-per-task)\n - ``tasks_per_node``: int (--tasks-per-node)\n - ``exclusive``: bool (--exclusive)\n \"\"\"\n options = []\n\n strings = {\n 'jname': '--job-name',\n 'queue': '--qos',\n 'workdir': '--workdir',\n 'error': '--error',\n 'output': '--output'\n }\n for k, v in strings.items():\n if k not in kwargs:\n continue\n options.append(\n '{prefix} {directive}={val}'.format(\n prefix=OPT_PREFIX,\n directive=v,\n val=kwargs[k]\n )\n )\n\n ints = {\n 'nodes': '--nodes',\n 'ntasks': '--ntasks',\n 'cpus_per_task': '--cpus-per-task',\n 'tasks_per_node': '--tasks-per-node'\n }\n for k, v in ints.items():\n if k not in kwargs:\n continue\n options.append(\n '{prefix} {directive}={val}'.format(\n prefix=OPT_PREFIX,\n directive=v,\n val=str(kwargs[k])\n )\n )\n\n bools = {'exclusive': '--exclusive'}\n for k, v in bools.items():\n if k not in kwargs:\n continue\n if kwargs[k]:\n options.append(\n '{prefix} {directive}'.format(\n prefix=OPT_PREFIX,\n directive=v,\n )\n )\n\n return '\\n'.join(options)\n","repo_name":"quim0/carcosa","sub_path":"carcosa/qsystems/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":8753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73644232279","text":"import numpy as np\nimport sys\nfrom Action_Replay_Buffer import *\nimport tensorflow as tf\nimport os\n\ndef create_tf_session(use_gpu, gpu_frac=0.8, allow_gpu_growth=True, which_gpu=0):\n print(\"creating custom GPU session\")\n if use_gpu:\n # gpu options\n gpu_options = tf.GPUOptions(\n per_process_gpu_memory_fraction=gpu_frac,\n allow_growth=allow_gpu_growth)\n # TF config\n config = tf.ConfigProto(\n gpu_options=gpu_options,\n log_device_placement=False,\n allow_soft_placement=True,\n inter_op_parallelism_threads=1,\n intra_op_parallelism_threads=1)\n # set env variable to specify which gpu to use\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(which_gpu)\n else:\n # TF config without gpu\n config = tf.ConfigProto(device_count={'GPU': 0})\n\n # use config to create TF session\n sess = tf.Session(config=config)\n return sess\n\ndef intrinsic_reward(obs, goal, ARP):\n if ARP.at_subgoal == True:\n return 1\n return 0\n\ndef achieved_subgoal(env, observation, goal_xy):\n coords = get_ALE_coord(env, observation)\n k = 10 # Because Calvin says so.\n if np.linalg.norm(coords - goal_xy) < k:\n return True\n else:\n return False\n\ndef get_ALE_coord(env, observation):\n obs = observation\n for action in [4,5,11]:\n rgb_coords = action_difference_of_frames(env,action,obs)\n if np.sum(rgb_coords) > 0:\n action_used = action\n rgb_coords = rgb_coords\n break\n if (action == 11 and np.sum(rgb_coords) == 0): #note to change to 11 later\n return (-1,-1)\n nonzero_coords = np.where(rgb_coords[:,:,0] != 0)\n [mean_y, mean_x] = [np.mean(nonzero_coords[0]),np.mean(nonzero_coords[1])]\n coords = (float(mean_x),float(mean_y))\n return coords\n\ndef action_difference_of_frames(env, action, obs):\n observation = obs\n env = env.unwrapped\n clone_state = env.clone_full_state()\n test_action = action\n for _ in range(3):\n next_observation, reward, done, info = env.step(test_action)\n\n # Black box things that move\n #replace treadmill in picture\n observation[135:142,59:101,:] = np.zeros((7,42,3))\n next_observation[135:142,59:101,:] = np.zeros((7,42,3))\n\n #replace header in picture\n observation[:20,:,:] = np.zeros((20,160,3))\n next_observation[:20,:,:] = np.zeros((20,160,3))\n\n #replace skull in picture\n observation[165:180,52:114,:] = np.zeros((15, 62, 3))\n next_observation[165:180,52:114,:] = np.zeros((15, 62, 3))\n\n #replace key in picture\n observation[98:116,10:23,:] = np.zeros((18, 13, 3))\n next_observation[98:116,10:23,:] = np.zeros((18, 13, 3))\n\n rgb_coords = next_observation-observation\n if np.sum(rgb_coords) != 0:\n env.restore_full_state(clone_state)\n return rgb_coords\n\n observation = next_observation\n\n env.restore_full_state(clone_state)\n return np.zeros(1)\n\ndef controller_targets(rewards, next_observations, controller, discount):\n #next_observations = np.array([obs[0] for obs in next_observations])\n q_values = controller.get_q_vals(next_observations)\n targets = rewards + discount * np.max(q_values, axis = 1)\n return targets\n\ndef meta_controller_targets(rewards, next_observations, meta_controller, discount):\n q_values = meta_controller.get_q_vals(next_observations)\n targets = rewards + discount * np.max(q_values, axis = 1)\n return targets\n\ndef random_goal_idx(goal_dim):\n return np.random.randint(low = 0, high = goal_dim)\n\ndef convertToBinaryMask(subgoal_coordinates):\n # Input:\n # subgoal_coordinates: list of two tuples. First tuple (r, c) coordinates of top left corner of box\n # Second tuple (r, c) coordinates of bottom right corner of box.\n # Output:\n # 3D numpy array of shape (210, 160, 3), with entries in region specified by subgoal_coordinates set to 1\n # and 0 elsewhere.\n gameSize = (210,160,3)\n topLeft = subgoal_coordinates[0]\n bottomRight = subgoal_coordinates[1]\n upper_y_bound = topLeft[0]\n lower_y_bound = bottomRight[0]\n left_x_bound = topLeft[1]\n right_x_bound = bottomRight[1]\n mask = np.zeros(gameSize)\n mask[upper_y_bound:lower_y_bound, left_x_bound:right_x_bound, :] = 1\n return mask\n\ndef convertToSubgoalCoordinates(mask):\n # Input:\n # mask: 3D numpy array of shape (210, 160, 3) for binary mask of subgoals\n # Output:\n # subgoal_coordinates: tuple (r, c) coordinates, the centroid of region of 1's\n one_idx = np.where(mask[:, :, 0] == 1)\n row_coord = int((min(one_idx[0]) + max(one_idx[0])) / 2)\n col_coord = int((min(one_idx[1]) + max(one_idx[1])) / 2)\n return (row_coord, col_coord)\n","repo_name":"madeleinesnyder/Subbat","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"10095736235","text":"\"\"\"add timestamps to result\n\nRevision ID: bb65a9ca237d\nRevises: a1b59b3ae0ca\nCreate Date: 2021-03-10 11:43:55.480014\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bb65a9ca237d'\ndown_revision = 'a1b59b3ae0ca'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('result', schema=None) as batch_op:\n batch_op.add_column(sa.Column('created_at', sa.DateTime(), nullable=True))\n batch_op.add_column(sa.Column('modified_at', sa.DateTime(), nullable=True))\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('result', schema=None) as batch_op:\n batch_op.drop_column('modified_at')\n batch_op.drop_column('created_at')\n\n # ### end Alembic commands ###\n","repo_name":"bubbl-oss/evoting","sub_path":"migrations/versions/bb65a9ca237d_add_timestamps_to_result.py","file_name":"bb65a9ca237d_add_timestamps_to_result.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"29247196613","text":"from . import TestCase, setup_fixtures\nfrom apps.surveys18.models import Survey, Subsidy, Refuse, RefuseReason\n\n\nclass ModelTestCase(TestCase):\n @classmethod\n def setUpTestData(cls):\n # load fixtures\n setup_fixtures()\n\n def test_create_survey(self):\n survey_id = Survey.objects.get(id=3)\n\n subsidy_list_before_size = Subsidy.objects.count()\n\n # new value\n new_subsidy = Subsidy.objects.create(survey=survey_id)\n new_subsidy.save()\n\n subsidy_list_after_size = Subsidy.objects.count()\n self.assertEqual(subsidy_list_after_size, subsidy_list_before_size + 1)\n\n def test_survey_delete(self):\n Survey.objects.filter(id=1).delete()\n subsidy_list = Subsidy.objects.filter(survey__id=1)\n self.assertEqual(subsidy_list.count(), 0)\n\n def test_survey_delete_all(self):\n Survey.objects.all().delete()\n self.assertEqual(Subsidy.objects.count(), 0)\n self.assertEqual(Refuse.objects.count(), 0)\n","repo_name":"COAStatistics/alss-dev","sub_path":"src/apps/surveys18/tests/test_subsidy.py","file_name":"test_subsidy.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30158065655","text":"import numpy as np\nfrom scipy.stats import kstest\nfrom helpers import get_new_component_coordinates\n\nimport logging, logger\n\nlog = logger.get_logger(__name__)\n\n\ndef check_sparsity(wavefield: np.ndarray, threshold=0.03) -> bool:\n \"\"\"Check if the number of non-zero components in an array exceeds the sparsity threshold\n\n Args:\n wavefield (np.ndarray): array to check for number of non-zero components.\n threshold (float, optional): Return True if fraction of non-zero components is above. Defaults to 0.03.\n\n Returns:\n bool: True if the threshold is exceeded\n \"\"\"\n log.debugv(\n f\"{np.count_nonzero(wavefield)}/{np.prod(wavefield.shape)} = {np.count_nonzero(wavefield) / np.prod(wavefield.shape)}\"\n )\n return np.count_nonzero(wavefield) / np.prod(wavefield.shape) > threshold\n\n\ndef check_spatial(\n new_components: np.ndarray,\n max_doppler: int,\n min_doppler=0,\n doppler_axis=0,\n p_threshold=1e-10,\n min_new_components=100,\n) -> bool:\n \"\"\"Check the spatial stopping criterion\n\n Check if the spatial (in doppler-shift) distribution of the new components is\n starting to be consistent with a uniform distribution. We check with a KS test\n with a p-value threshold.\n\n Note that the threshold is much lower than what would normally be accepted as\n we are trying to catch the moment when the distribution is becoming to be uniform\n\n The criterion is only applied if the number of new components is greater than min_new_components\n\n\n Args:\n new_components (np.ndarray): An array with a list of new components.\n max_doppler (float): Max doppler index to consider\n min_doppler (int, optional): Min doppler index to consider. Defaults to 0.\n doppler_axis (int, optional): Which axis is the doppler axis. Defaults to 0.\n p_threshold (_type_, optional): P-threshold for the KS test. Defaults to 1e-10.\n min_new_components (int, optional): Minimum count of new components above which this test applies. Defaults to 100.\n\n Returns:\n bool: True if the p_value exceeded the threshold\n \"\"\"\n new_components = np.array(new_components.tolist()).transpose()\n # Sometimes there will be no new components (in particular, in noise free cases), or too few:\n if len(new_components) == 0 or min_new_components > len(new_components[0]):\n return False\n doppler_scaled = (new_components[doppler_axis] - min_doppler) / (max_doppler - min_doppler)\n doppler_ks = kstest(doppler_scaled, \"uniform\")\n log.debug(f\"new components count {len(new_components[0]):.3g}\")\n log.debug(f\"doppler ks {doppler_ks.pvalue:.3g}\")\n\n return doppler_ks.pvalue > p_threshold\n\n\ndef check_stopping(\n io: dict,\n step: int,\n doppler_axis=0,\n check_sparse=True,\n sparsity_threshold=0.03,\n check_doppler_distribution=True,\n spatial_threshold=1e-10,\n):\n \"\"\"Check if the stopping criteria are met\n\n Can check both spatial and sparsity criteria\n\n Args:\n io (dict): Input/output dictionary as used by lambda loop\n step (int): Step at which to check the stopping criteria\n doppler_axis (int, optional): Which axis is the doppler axi. Defaults to 0.\n check_sparse (bool, optional): Apply the sparsity criterion. Defaults to True.\n sparsity_threshold (float, optional): Sparsity threshold. Defaults to 0.03.\n check_doppler_distribution (bool, optional): Apply the spatial criterion. Defaults to True.\n spatial_threshold (_type_, optional): Spatial test p-value threshold. Defaults to 1e-10.\n\n Returns:\n _type_: True if either stopping criterion is triggered\n \"\"\"\n new_components = get_new_component_coordinates(io, step)\n wavefield = io[\"models\"][step]\n if check_sparse:\n log.debug(\"Checking sparse\")\n if check_sparsity(wavefield, threshold=sparsity_threshold):\n log.info(\"Sparsity triggered\")\n return True\n if check_doppler_distribution:\n log.debug(\"Checking spatial\")\n if check_spatial(\n new_components, wavefield.shape[doppler_axis], doppler_axis=doppler_axis, p_threshold=spatial_threshold\n ):\n log.info(\"Spatial triggered\")\n return True\n log.debug(\"No stopping criterion fulfilled\")\n return False\n","repo_name":"sosl/H-FISTA","sub_path":"stopping.py","file_name":"stopping.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"31937909531","text":"def flatten(seq):\n sum = []\n for i in seq: \n if isinstance(i, (list, tuple)):\n sum.extend(flatten(i))\n else:\n sum.append(i)\n return sum\n\nassert flatten([1, 2, 3, 4, [1,3,[1,2,[5]]]]) == [1, 2, 3, 4, 1, 3, 1, 2, 5]","repo_name":"xRizur/Python_Classes","sub_path":"Zestaw_4/4_7.py","file_name":"4_7.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17402790528","text":"#Continue: if i want to skip current iteration for some purpose. And,going to the next\n#iteration is the concept of continue statements.\n# WAP to print odd number by using logic of even number.\n\"\"\"\nn = int(input(\"Enter the number:\"))\nfor i in range(1,n+1):\n if i%2==0:\n continue\n else:\n print(\"Odd:\",i)\n\"\"\"\n\n\"\"\"\nfor x in range(10):\n if x>5:\n continue\n else:\n print(x)\n\n\"\"\"\ni=0\nwhile(i<10):\n i+=1\n if i%2==0:\n continue\n \n print(\"odd\",i)\n \n\n\n\n\n\"\"\"\nL = [100,200,50,60,800,700,765,900]\nfor i in L:\n if i>500:\n continue\n print(i)\n\"\"\"\n","repo_name":"vipuldhandre/Python_Practise","sub_path":"continue_statements.py","file_name":"continue_statements.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42524471877","text":"# Author : Adrien Pillou\r\n# Date : 12/16/2020\r\n#--- Day 16: Ticket Translation ---\r\n# Answer : 21978\r\n\r\n'''\r\n.--------------------------------------------------------.\r\n| ????: 101 ?????: 102 ??????????: 103 ???: 104 |\r\n| |\r\n| ??: 301 ??: 302 ???????: 303 ??????? |\r\n| ??: 401 ??: 402 ???? ????: 403 ????????? |\r\n'--------------------------------------------------------'\r\n'''\r\n\r\nimport os\r\nimport math\r\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\r\n\r\n# Check if a value is within at least one range\r\ndef is_valid(value:int):\r\n global ranges\r\n for r in ranges:\r\n if value >= r[0] and value <= r[1]:\r\n return True\r\n return False\r\n\r\nranges = []\r\nmy_ticket = tuple()\r\ntickets = []\r\nerror_rate = 0\r\n\r\nif __name__ == \"__main__\":\r\n with open('in.txt') as f:\r\n x = f.readlines()\r\n x = [l.strip() for l in x]\r\n\r\n # Gathering fields and ranges\r\n fields = x[0:20]\r\n for f in fields:\r\n f = f.split(':')\r\n values = f[1]\r\n values = values.split('or')\r\n ranges.append(values[0])\r\n ranges.append(values[1])\r\n\r\n for i in range(len(ranges)):\r\n ranges[i] = ranges[i].split('-')\r\n ranges[i] = (int(ranges[i][0]), int(ranges[i][1]))\r\n\r\n # Gathering my ticket\r\n my_ticket = x[22].split(',')\r\n for i in range(len(my_ticket)):\r\n my_ticket[i] = int(my_ticket[i])\r\n\r\n # Gathering all tickets\r\n tickets = x[25:]\r\n for i, t in enumerate(tickets):\r\n tickets[i] = tickets[i].split(',')\r\n for v in range(len(tickets[i])):\r\n tickets[i][v] = int(tickets[i][v])\r\n tickets[i] = tuple(tickets[i])\r\n\r\n # Sum up error rate\r\n for t in tickets:\r\n for v in t:\r\n if not is_valid(v):\r\n error_rate += v\r\n print(error_rate)\r\n\r\n ","repo_name":"adrienpillou/Advent-of-Code-2020","sub_path":"16/partone.py","file_name":"partone.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27050523782","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 28 15:36:15 2019\r\n\r\n@author: sec\r\n\"\"\"\r\n#tm_1 = \"%04d\" % (now.tm_year)\r\n#tm_2 = \"%04d.%02d.%02d\" % (now.tm_year, now.tm_mon, now.tm_mday)\r\n#query = input(\"네이버에서 크롤링 할 내용을 적으세요 예시)블록체인\\n\").replace(\" \",\"+\")\r\n#s_date = input(\"크롤링 할 시작할 날짜를 적으세요. 예시){}.01.01 \\n\".format(tm_1))\r\n#e_date = input(\"크롤링 할 마지막 날짜를 적으세요. 예시){} \\n\".format(tm_2))\r\n\r\nimport time\r\nnow = time.localtime()\r\ntm_0 = \"(%04d-%02d-%02d %02dh_%02dm_%02ds)\" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)\r\n\r\nprint(\"=\"*50+\"\\n먼저, '네이버 홈페이지'에 '검색 내용'을 입력하세요.\"); print(\"반드시 '뉴스' 파트의 '검색옵션'에서 설정을 하고 실행해주세요. \\n\"+\"=\"*50)\r\nquery = input(\"네이버뉴스 '댓글'을 크롤링 합니다. 2페이지의 url를 입력해주세요. \\n\").split(\"start=\")[0] + \"start=\"\r\npage = int(input(\"내용을 출력합니다. 페이지의 숫자를 적으세요. 예시) 1 \\n\"))\r\nc_p_num_0 = int(input(\"각 기사에서 크롤링 할 댓글의 개수를 20단위로 적으세요. ex)20 40 60 \\n\"))\r\nc_p_num = c_p_num_0//20\r\n\r\nimport os\r\nDATA_PATH = os.getcwd().replace('\\\\','/')\r\nRESULT_PATH = DATA_PATH + \"/result/\"\r\n\r\ndir_path = DATA_PATH\r\ndir_name = 'result'\r\nif not os.path.exists('./result/'): \r\n os.mkdir(dir_path + '/' + dir_name + '/')\r\n \r\nprint(\"\\n>>>>>> result 폴더가 생성되고, '최신순'으로 결과가 저장됩니다. <<<<<< \\n\")\r\n\r\n\r\n\r\n\r\nimport re\r\nimport requests as req\r\nfrom bs4 import BeautifulSoup as bs\r\nimport json\r\n\r\nextra = \"m_view=1&includeAllCount=true&\"\r\n\r\nview = \"society\" # view관련 오류시 F12 > network > js >json에서 확인후 it 등으로 이를 변경해주세요.\r\n\r\ndef crawler_comment(line):\r\n \r\n print(\"{0}페이지까지 댓글이 {1}개씩 출력됩니다.\".format(line, c_p_num_0))\r\n \r\n print(\"==========================================\")\r\n \r\n f = open(RESULT_PATH + 'comment.txt', 'w', encoding='UTF-8')\r\n \r\n base_url = query\r\n \r\n for i in range(0, line) : \r\n i = (i*10)+1\r\n url = base_url + \"{}\".format(i)\r\n source_code = req.get(url)\r\n plain_text = source_code.text\r\n soup = bs(plain_text, 'lxml')\r\n \r\n for link in soup.select(\"dd > ._sp_each_url\"):\r\n url = link.get('href')\r\n #print(url)\r\n url = url[:37] + extra + url[37:]\r\n print(url)\r\n \r\n oid = url.split(\"oid=\")[1].split(\"&\")[0] \r\n aid = url.split(\"aid=\")[1]\r\n \r\n header = { \r\n \"User-agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\", \r\n \"referer\":url, \r\n }\r\n sort = \"new\" #FAVORITE \r\n #c_p_num = 3\r\n for page_num in range(1, c_p_num+1):\r\n c_url=\"https://apis.naver.com/commentBox/cbox/web_neo_list_jsonp.json?ticket=news&templateId=view_\"+ view +\"&pool=cbox5&_callback=jQuery1707138182064460843_1523512042464&lang=ko&country=&objectId=news\" + oid + \"%2C\" + aid + \"&categoryId=&pageSize=20&indexSize=10&groupId=&listType=OBJECT&pageType=more&page=\" + str(page_num) + \"&refresh=false&sort=\"+sort\r\n #page = 1\r\n #c_url=\"https://apis.naver.com/commentBox/cbox/web_neo_list_jsonp.json?ticket=news&templateId=view_\"+ view +\"&pool=cbox5&_callback=jQuery1707138182064460843_1523512042464&lang=ko&country=&objectId=news\" + oid + \"%2C\" + aid + \"&categoryId=&pageSize=20&indexSize=10&groupId=&listType=OBJECT&pageType=more&page=\" + str(page_num) + \"&refresh=false&sort=\"+sort\r\n \r\n r=req.get(c_url, headers=header) \r\n #print(r)\r\n data = r.text\r\n #print(data)\r\n \r\n idx1 = data.find('(') \r\n idx2 = data.find(')')\r\n #print(idx1, idx2)\r\n \r\n try :\r\n json_data = data[idx1+1:idx2]\r\n #print(type(json_data))\r\n \r\n json_data = json.loads(json_data)\r\n #print(type(json_data))\r\n \r\n if json_data['result']['commentList'] == []:\r\n pass #댓글이 없습니다.\r\n else : \r\n for j in range(0, len(json_data['result']['commentList'])):\r\n #닉네임\r\n name = json_data['result']['commentList'][j]['maskedUserId']\r\n \r\n #본문\r\n content = json_data['result']['commentList'][j]['contents'].replace(\"\\n\", \" \")\r\n #이모티콘 제거\r\n RE_EMOJI = re.compile('[\\U00010000-\\U0010ffff]', flags=re.UNICODE)\r\n contents = RE_EMOJI.sub(r'', content)\r\n \r\n #시간\r\n time = json_data['result']['commentList'][j]['regTime'][:10]\r\n \r\n print(time, name, content)\r\n \r\n f.write(\"{}\\t{}\\t{}\\t{}\\n\".format(time, url, name, contents))\r\n print(\"==========================================\")\r\n except Exception as e:\r\n print(e)\r\n print(\"예외가 발생하여 댓글을 제외하였습니다\")\r\n print(\"==========================================\")\r\n continue\r\n f.close()\r\n\r\n \r\ncrawler_comment(page)\r\n\r\n\r\n\r\n\r\n\r\nimport pandas as pd\r\n\r\ndef excel_make():\r\n data = pd.read_csv(RESULT_PATH + 'comment.txt', sep='\\t',header=None)\r\n data.columns = ['time','url','name','contents']\r\n print(data)\r\n #url의 값이 2번째와 1번째가 동일하다면, 2번째는 \"\"로 표현하고 싶다\r\n xlsx_name = RESULT_PATH + 'comment_result {}'.format(tm_0) + '.xlsx'\r\n data.to_excel(xlsx_name, encoding='utf-8')\r\nexcel_make()\r\n\r\n","repo_name":"sschoi2427/korean_crawler","sub_path":"naver_cralwer/4_crawler_news_comment.py","file_name":"4_crawler_news_comment.py","file_ext":"py","file_size_in_byte":6231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15956213442","text":"\"\"\"\nWrapper script for converting .bim (binary) to .sp (matrix)\n\nAuthor: K. Enevoldsen\n\"\"\"\n\nfrom pathlib import Path\nimport os\n\n\n# set WD\nhome = Path.home()\nwd = os.path.abspath(os.path.join(home, 'NLPPred'))\nos.chdir(wd)\n\nfiles = [f for f in os.listdir() if f.endswith(\".bim\")]\nnew_files = [f.split(\".\")[0][3:] for f in os.listdir()\n if f.startswith(\"new\") and f.endswith(\".sp\")]\nfiles = [f for f in files if f.split(\".\")[0][3:] not in new_files]\n\n\n#awk '(NR==FNR){arr[$2];next}($2 in arr){print $2}' > over.all mhcabd.bim mhcabe.bim mhcabc.bim mhcabg.bim mhcabi.bim mhcuvps.bim mhcuvis.bim mhcuvk.bim mhcubvbuc.bim mhcuvms.bim mhcuvbo.bim mhccel.bim\n\nfor f in files:\n f = f.split(\".\")[0]\n new_f = \"intersect_\" + f[3:]\n cmd = \"./ldak5.linux --make-sp \" + new_f + \" --bfile \" + f + \" --extract over.all\"\n os.system(cmd)\n print(f\"{f} done\")\n\n\n\"./ldak5.linux --make-sp \" + \"inter_test_abc\" + \" --bfile \" + \"mhcabc\" + \" --extract over.abc.abd\"\n\"./ldak5.linux --make-sp \" + \"inter_test_abd\" + \" --bfile \" + \"mhcabd\" + \" --extract over.abc.abd\"\n\nos.system(test)\n\n#\n#mv dir/new* /path/to/destination\n\n","repo_name":"HLasse/Data-Science-Exam","sub_path":"GenomeDK_genbert-master/make_matrix.py","file_name":"make_matrix.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"35751969167","text":"from __future__ import with_statement\r\nimport Pyro4\r\n\r\nclass CallbackServer(object):\r\n def doCallback(self, callback):\r\n print(\"server: doing callback 1 to client\")\r\n try:\r\n callback.call1()\r\n except:\r\n print(\"got an exception from the callback.\")\r\n print(\"\".join(Pyro4.util.getPyroTraceback()))\r\n print(\"server: doing callback 2 to client\")\r\n try:\r\n callback.call2()\r\n except:\r\n print(\"got an exception from the callback.\")\r\n print(\"\".join(Pyro4.util.getPyroTraceback()))\r\n print(\"server: callbacks done\")\r\n\r\nwith Pyro4.core.Daemon() as daemon:\r\n with Pyro4.naming.locateNS() as ns:\r\n obj=CallbackServer()\r\n uri=daemon.register(obj)\r\n ns.register(\"example.callback2\",uri)\r\n print(\"Server ready.\")\r\n daemon.requestLoop()\r\n","repo_name":"delmic/Pyro4","sub_path":"examples/callback/server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"34165482398","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: Chrysovalantou Kalaitzidou\n\nThe current code is part of the third assignment in class Methods in Bioinformatics and refers to\nClassification alorithms & in particular the K-nn and Naive Bayes.\n\nThis particular script contains the implementation of Naive Bayes\nclassifier.\n\n\"\"\"\n\nfrom Functions import*\nimport scipy.stats\n\n\n\ndef Naive_Bayes(Data,Labels,Hold_indices,Train_set,Test_set):\n\n\t#Train_set,Test_set,Data_dict = Splitting(Data,Labels)\n\n\tX = Data.T ; D= X.shape[0]; N = X.shape[1]\n\n\treal_index = list(range(N))\n\tk = len(Hold_indices) #; print(k)\n\t\n\tOrder_labels = []\t\t\t## Ordering Labels \n\t\n\tfor i in Hold_indices.keys():\n\t\tOrder_labels.append(i)\n\t\t\n\tClass_Priors = np.zeros(k)\n\t\n\tfor c in range(len(Order_labels)):\n\t\tkey = Order_labels[c]\n\t\tClass_Priors[c] = len(Hold_indices[key]) / len(Train_set)\n\t\t\n\tprint(\"The Prior Probabilty of its Class is: {}\".format(Class_Priors))\n\t\n\t### Classes: 10 objects, each one an array of the samples belonging to this particular class.\n\t##\tMeans:\t 10 objects, each one an array of the means of each variable, in this particular class.\n\t#\tStdv:\t 10 objects, each one an array of the std of each variable, in this particular class.\n\t\n\tClasses = np.zeros(k,dtype = object)\n\tMeans = np.zeros(k,dtype = object)\n\tStdv = np.zeros(k,dtype = object)\n\n\tfor c in range(len(Order_labels)):\n\t\tkey = Order_labels[c]\n\t\t\n\t\tClasses[c] = np.array(X[:,Hold_indices[key]])\n\t\tMeans[c] = np.mean(Classes[c], axis =1)\n\t\tStdv[c]\t = np.std(Classes[c], axis=1)\n\t\t\n\tTrain_Array = np.array(X[:, Train_set]); print(\"Shape of Train Matrix: {}\".format(Train_Array.shape))\n\tTest_Array = np.array(X[:, Test_set]); print(\"Shape of Test Matrix: {}\".format(Test_Array.shape))\n\t\n\tm = Test_Array.shape[1]\t\t# Samples\n\tn = Test_Array.shape[0]\t\t# Variables \n\n\tPredicted_Labels = []\n\n\tfor i in range(m):\n\t\tProbability = np.zeros(k, dtype=object)\n\t\tfor c in range(len(Order_labels)):\n\t\t\tkey = Order_labels[c]\n\t\t\tPredictions = np.zeros(n)\n\t\t\tfor j in range(n):\n\t\t\t\tConditional = scipy.stats.norm.pdf(Test_Array[j,i], loc = Means[c][j], scale = Stdv[c][j])\n\t\t\t\t## zero conditional probability\n\t\t\t\tif Conditional == 0 or np.isnan(Conditional):\n\t\t\t\t\t#print(Test_Array[j,i])\n\t\t\t\t\tvec = np.array(X[j, Hold_indices[key]])\n\t\t\t\t\tn_c = list(vec).count(Test_Array[j,i]) #; print(\"nc:{}\".format(n_c))\n\t\t\t\t\tn_l = len(Hold_indices[key])\n\t\t\t\t\tt \t= len(set(Hold_indices[key])); p = 1/t\n\t\t\t\t\tm \t= 1\n\t\t\t\t\t\n\t\t\t\t\tConditional = (n_c + m*p)/(n_l + m)\n\t\t\t\t\n\t\t\t\tPredictions[j] = Conditional\n\t\t\tProduct = np.prod(Predictions)\n\t\t\tProbability[c] = np.dot(Product,Class_Priors[c])\n\n\t\tMax_Prob = np.argmax(Probability)\n\t\tPredicted_Labels.append(Order_labels[Max_Prob])\n\t\n\treturn(Predicted_Labels)\n\t\n# ------ ------ ------ ------ ------ ------ ------ ------ ------- ----\n# ------ ------ ------ ------ ------ ------ ------ ------ ------- ----\n","repo_name":"Chrysovalantou/Classification-Methods","sub_path":"Bayes.py","file_name":"Bayes.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"23216340348","text":"from waldur_core.cost_tracking import CostTrackingStrategy, ConsumableItem, CostTrackingRegister\n\nfrom . import models, utils, PriceItemTypes\n\n\nclass InstanceStrategy(CostTrackingStrategy):\n resource_class = models.Instance\n\n class Types(object):\n FLAVOR = PriceItemTypes.FLAVOR\n\n @classmethod\n def get_consumable_items(cls):\n for flavor_name in set(models.Flavor.objects.all().values_list('name', flat=True)):\n yield utils.get_consumable_item(flavor_name)\n\n @classmethod\n def get_configuration(cls, instance):\n consumables = {}\n if instance.state != models.Instance.States.ERRED:\n consumables[ConsumableItem(item_type=cls.Types.FLAVOR, key=instance.flavor_name)] = 1\n return consumables\n\n\nCostTrackingRegister.register_strategy(InstanceStrategy)\n\n\nclass VolumeStrategy(CostTrackingStrategy):\n resource_class = models.Volume\n\n class Types(object):\n STORAGE = PriceItemTypes.STORAGE\n\n class Keys(object):\n STORAGE = '1 GB'\n\n @classmethod\n def get_consumable_items(cls):\n return [ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE, name='1 GB of storage', units='GB')]\n\n @classmethod\n def get_configuration(cls, volume):\n return {ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE): float(volume.size) / 1024}\n\n\nCostTrackingRegister.register_strategy(VolumeStrategy)\n\n\nclass SnapshotStrategy(CostTrackingStrategy):\n resource_class = models.Snapshot\n\n class Types(object):\n STORAGE = PriceItemTypes.STORAGE\n\n class Keys(object):\n STORAGE = '1 GB'\n\n @classmethod\n def get_consumable_items(cls):\n return [ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE, name='1 GB of storage', units='GB')]\n\n @classmethod\n def get_configuration(cls, snapshot):\n return {ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE): float(snapshot.size) / 1024}\n\n\nCostTrackingRegister.register_strategy(SnapshotStrategy)\n","repo_name":"opennode/waldur-openstack","sub_path":"src/waldur_openstack/openstack_tenant/cost_tracking.py","file_name":"cost_tracking.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"3682948389","text":"import cv2 as cv\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\npath = r'C:\\Users\\DELL\\Downloads\\photos_openCV\\Photos\\Cats.jpg'\nimg = cv.imread(path)\ncv.imshow('Cats', img)\n\nblank = np.zeros(img.shape[:2], dtype='uint8')\n\n# Histogram allow us to visualize the distribution of pixel intensities in an image.\n\n# 1. Computing histogram for grayscale images.\n\n# convert to gray image:\n# gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n# cv.imshow('Gray Image', gray)\n\n# circle = cv.circle(blank, (img.shape[1]//2, img.shape[0]//2), 100, 255, -1)\n# cv.imshow('Circle', circle)\n\n# mask = cv.bitwise_and(gray, gray, mask=circle)\n# cv.imshow('Mask', mask)\n\n\n# grayscale histogram:\n# gray_his = cv.calcHist([gray], [0], None, [256], [0, 256])\n# gray_his = cv.calcHist([gray], [0], mask, [256], [0, 256])\n# 1st parameter --> is image parameter will pass -> list of images.\n# 2nd parameter --> number of channels -> specify the index of the channel, want to compute a histogram for.\n# 2nd parameter --> is zero, because image is gray scale image.\n# 3rd parameter --> is mask -> if we want to computer a histogram for portion of an image.\n# 4th parameter --> is number of bins that we want to use for computing the histogram.\n# bins represent the interval of pixel intensities.\n# 5th parameter --> range of all possible pixel value.\n# example --> in this image there are close to 4000 pixel have an intensity of 60.\n\n\n# we can also do this, create a mask and then compute the histogram only on that particular mask.\n\n# plt.figure()\n# plt.title('Grayscale Histogram')\n# plt.xlabel('Bins')\n# plt.ylabel('# of pixels')\n# plt.plot(gray_his)\n# plt.xlim([0, 256]) # limit across x axis\n# plt.show()\n\n\n# 2. Computing histogram for colour images.\n\nmask = cv.circle(blank, (img.shape[1]//2, img.shape[0]//2), 100, 255, -1)\n\nmasked = cv.bitwise_and(img, img, mask=mask)\ncv.imshow('Masked', masked)\n\n# mask need to be in binary format.\n\nplt.figure()\nplt.title('Color Histogram')\nplt.xlabel('Bins')\nplt.ylabel('# of pixels')\n\ncolors = ('b', 'g', 'r')\n\nfor i, col in enumerate(colors):\n # hist = cv.calcHist([img], [i], None, [256], [0, 256])\n hist = cv.calcHist([img], [i], mask, [256], [0, 256])\n plt.plot(hist, color=col)\n plt.xlim([0, 256])\n\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\ncv.waitKey(0)","repo_name":"Avatar521999/openCV_by_pravesh_singh","sub_path":"histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17669638439","text":"import random\n\ndef Fact(x):\n if x ==0:\n return 1\n if x ==1:\n return 1\n else:\n return Fact(x-1)*x\n\n\ndef nCr(n,r):\n return Fact(n)/(Fact(r)*(Fact(n-r)))\n\ndef nPr(n,r):\n return Fact(n)/Fact(n-r)\n\n\ndef FreshDeck():\n L=[]\n i=0\n k=1\n while k<14: \n k=k+1 \n L.append(Card(k,'h'))\n i = i +1\n L.append(Card(k,'d'))\n i = i +1\n L.append(Card(k,'c',))\n i =i +1\n L.append(Card(k,'s'))\n return L\n\ndef ShuffleDeck(N):\n M=[]\n while len(N)>0:\n x = random.randint(0,len(N)-1) \n M.append(N[x])\n N.remove(N[x]) \n return M\n\ndef Deal(deck,remaining_players):\n Hand=[]\n for index in range(remaining_players):\n \n x = deck[0]\n y = deck[1]\n deck.remove(x)\n deck.remove(y)\n Hand.append(HoleCards(x,y)) \n \n\n deck_remaining = deck\n\n return Hand, deck_remaining\n\ndef Deal_Flop(deck):\n \n x = deck[0]\n y = deck[1]\n z = deck[2]\n deck.remove(x)\n deck.remove(y)\n deck.remove(z)\n Out=Flop(x,y,z) \n \n deck_remaining = deck\n\n return Out, deck_remaining\n","repo_name":"IEIE99/pokerCool","sub_path":"PokerFunctions_.py","file_name":"PokerFunctions_.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15668431686","text":"\nfrom PIL import Image\nimport numpy as np\n\nnp.random.seed(seed=2023)\n\n# convert a RGB image to grayscale\n# input (rgb): numpy array of shape (H, W, 3)\n# output (gray): numpy array of shape (H, W)\ndef rgb2gray(rgb):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\tH,W,channel = rgb.shape\n\tgray = np.zeros((H, W, 1))\n\tfor i in range (H):\n\t\tfor j in range (W):\n\t\t\tgray[i,j] = (rgb[i,j,0]*1913+rgb[i,j,1]*4815+rgb[i,j,2]*3272)/10000\n\treturn gray\n\n#load the data\n# input (i0_path): path to the first image\n# input (i1_path): path to the second image\n# input (gt_path): path to the disparity image\n# output (i_0): numpy array of shape (H, W, 3)\n# output (i_1): numpy array of shape (H, W, 3)\n# output (g_t): numpy array of shape (H, W)\ndef load_data(i0_path, i1_path, gt_path):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\ti_0 = Image.open(i0_path)\n\ti_0 = np.array((i_0))/256\n\ti_1 = Image.open(i1_path)\n\ti_1 = np.array((i_1))/256\n\tg_t = Image.open(gt_path)\n\tg_t = np.array((g_t))/256\n\n\treturn i_0, i_1, g_t\n\n# image to the size of the non-zero elements of disparity map\n# input (img): numpy array of shape (H, W)\n# input (d): numpy array of shape (H, W)\n# output (img_crop): numpy array of shape (H', W')\ndef crop_image(img, d):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\tsumOfRow = d.sum(axis=1).reshape(-1,1)\n\tsumOfColumn = d.sum(axis=0).reshape(1,-1)\n\tindexLeft = 0\n\tindexRight = sumOfColumn.size-1\n\tindexTop = 0\n\tindexBottom = sumOfRow.size-1\n\twhile(sumOfColumn[0,indexLeft]==0):\n\t\tindexLeft = indexLeft+1\n\twhile(sumOfColumn[0,indexRight]==0):\n\t\tindexRight = indexRight-1\n\twhile(sumOfRow[indexTop,0]==0):\n\t\tindexTop = indexTop+1\n\twhile(sumOfRow[indexBottom,0]==0):\n\t\tindexBottom = indexBottom-1\n\timg_crop = img[indexLeft:indexRight+1,indexTop:indexBottom+1]\n\n\treturn img_crop\n\n#\t##############################################################################################\n#\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n#\t##############################################################################################\n#\n#\tmask = d != 0\n#\tnonzero_indices = np.argwhere(mask)\n#\n#\tif len(nonzero_indices) == 0:\n#\t\treturn np.array([]) # 或者根据需要返回适当的默认值\n#\n#\tmin_row, min_col = np.min(nonzero_indices, axis=0)\n#\tmax_row, max_col = np.max(nonzero_indices, axis=0)\n#\n#\timg_crop = img[min_row:max_row + 1, min_col:max_col + 1]\n#\n#\treturn img_crop\n\n\n# shift all pixels of i1 by the value of the disparity map\n# input (i_1): numpy array of shape (H, W)\n# input (d): numpy array of shape (H, W)\n# output (i_d): numpy array of shape (H, W)\ndef shift_disparity(i_1,d):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\tH_i,W_i,channel_of_i = i_1.shape\n\ti_d = np.zeros((H_i,W_i,3))\n\tfor i in range(H_i):\n\t\tfor j in range (W_i):\n\t\t\tif j - d[i, j] >= 0:\n\t\t\t\ti_d[i,j] = i_1[i,j-int(d[i,j])]\n\treturn i_d\n\n# compute the negative log of the Gaussian likelihood\n# input (i_0): numpy array of shape (H, W)\n# input (i_1_d): numpy array of shape (H, W)\n# input (mu): float\n# input (sigma): float\n# output (nll): numpy scalar of shape ()\ndef gaussian_nllh(i_0, i_1_d, mu, sigma):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\tdiff = i_0-i_1_d\n\tnll = 0.5 * ((diff - mu )** 2)/ (sigma ** 2) + np.log(sigma * (2*np.pi) ** 0.5)\n\tnll = np.sum(nll)\n\treturn nll\n\n\n# compute the negative log of the Laplacian likelihood\n# input (i_0): numpy array of shape (H, W)\n# input (i_1_d): numpy array of shape (H, W)\n# input (mu): float\n# input (s): float\n# output (nll): numpy scalar of shape ()\ndef laplacian_nllh(i_0, i_1_d, mu,s):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\tdiff = i_0 - i_1_d\n\tnll = np.log(1 / (2*s)) - np.absolute(diff - mu) / s\n\tnll = np.sum(nll)\n\treturn nll\n\n# replace p% of the image pixels with values from a normal distribution\n# input (img): numpy array of shape (H, W)\n# input (p): float\n# output (img_noise): numpy array of shape (H, W)\ndef make_noise(img, p):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\tmean = 0.38\n\tstandard_deviation = 0.78\n\tnoise = np.random.normal(mean,standard_deviation,img.shape)\n\tflattened_img = img.flatten()\n\tmask = np.random.choice([True,False],size = flattened_img.shape,p=[p/100,1-p/100])\n\timg_noise = np.where(mask,noise.flatten(),flattened_img).reshape(img.shape)\n\treturn img_noise\n\n# apply noise to i1_sh and return the values of the negative lok-likelihood for both likelihood models with mu, sigma, and s\n# input (i0): numpy array of shape (H, W)\n# input (i1_sh): numpy array of shape (H, W)\n# input (noise): float\n# input (mu): float\n# input (sigma): float\n# input (s): float\n# output (gnllh) - gaussian negative log-likelihood: numpy scalar of shape ()\n# output (lnllh) - laplacian negative log-likelihood: numpy scalar of shape ()\ndef get_nllh_for_corrupted(i_0, i_1_d, noise, mu, sigma, s):\n\n\t##############################################################################################\n\t#\t\t\t\t\t\t\t\t\t\tIMPLEMENT\t\t\t\t\t\t\t\t\t\t\t #\n\t##############################################################################################\n\ti1_sh = make_noise(i_1_d,noise)\n\tgnllh = gaussian_nllh(i_0,i1_sh,mu,sigma)\n\tlnllh = laplacian_nllh(i_0,i1_sh,mu,s)\n\n\treturn gnllh, lnllh\n\n# DO NOT CHANGE\ndef main():\n\t# load images\n\ti0, i1, gt = load_data('./data/i0.png', './data/i1.png', './data/gt.png')\n\n\ti0, i1 = rgb2gray(i0), rgb2gray(i1)\n\n\t# shift i1\n\ti1_sh = shift_disparity(i1, gt)\n\n\t# crop images\n\ti0 = crop_image(i0, gt)\n\ti1_sh = crop_image(i1_sh, gt)\n\n\tmu = 0.0\n\tsigma = 1.3\n\ts = 1.3\n\tfor noise in [0.0, 15.0, 28.0]:\n\n\t\tgnllh, lnllh = get_nllh_for_corrupted(i0, i1_sh, noise, mu, sigma, s)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"yyinyangg/CV2","sub_path":"P1/skeleton3_Aobo Tan.py","file_name":"skeleton3_Aobo Tan.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71028507157","text":"input = \"\"\"\nR 4\nU 4\nL 3\nD 1\nR 4\nD 1\nL 5\nR 2\n\"\"\".strip()\n\ninput = \"\"\"\nR 5\nU 8\nL 8\nD 3\nR 17\nD 10\nL 25\nU 20\"\"\".strip()\n\ninput = open('input.txt').read().strip()\n\n# head = (0, 0)\nrope = [(0, 0) for _ in range(10)]\nprint(\"rope\", rope)\n\ntail_positions = set()\n\ndef get_dir_deltas(direction):\n if direction == \"R\":\n return (1, 0)\n if direction == \"U\": return (0, 1)\n if direction == \"L\": return (-1, 0)\n if direction == \"D\": return (0, -1)\n\n assert False, f\"bad direction {direction}\"\n\ndef print_debug():\n for y in range(-20, 20):\n for x in range(-20, 20):\n x = x\n y = y\n if (x, y) in set(rope):\n i = rope.index((x, y))\n print(f'{i}', end='')\n elif (x, y) in tail_positions:\n print('#', end='')\n else:\n print('.', end='')\n print()\n print()\n\ndef update_positions(head, tail, dx, dy):\n # returns the new head and tail\n\n # move the head\n new_head = (head[0] + dx, head[1] + dy)\n new_tail = list(tail)\n\n # if head two steps away from up down left or right, tail must move one step in that direction\n dtailx = abs(new_head[0] - tail[0])\n dtaily = abs(new_head[1] - tail[1])\n\n # print('from', head, 'to', tail, 'is', (dtailx, dtaily))\n\n if dtailx <= 1 and dtaily <= 1:\n # tail does not move\n pass\n # elif (dtailx == 2 and dtaily != 2) or (dtailx != 2 and dtaily == 2):\n # new_tail = (tail[0] + dx, tail[1] + dy)\n else:\n # diag, move once in the direction of dx dy\n # but also move once to match the other dimension\n new_tail = [tail[0] + dx, tail[1] + dy]\n\n if abs(dx) == 1:\n # moving in x direction, converge in y direction\n new_tail[1] = new_head[1]\n else:\n new_tail[0] = new_head[0]\n return new_head, tuple(new_tail)\n\ndef update_tail(head, tail):\n # returns the new tail\n\n # move the head\n # new_head = (head[0] + dx, head[1] + dy)\n new_tail = list(tail)\n\n # if head two steps away from up down left or right, tail must move one step in that direction\n dtailx = (head[0] - tail[0])\n dtaily = (head[1] - tail[1])\n\n # print('from', head, 'to', tail, 'is', (dtailx, dtaily))\n\n if abs(dtailx) <= 1 and abs(dtaily) <= 1:\n # tail does not move, because it is directly adjacent\n pass\n else:\n # move each dimension as requrired by 1\n if dtailx < 0:\n new_tail[0] -= 1\n elif dtailx > 0:\n new_tail[0] += 1\n\n if dtaily < 0:\n new_tail[1] -= 1\n elif dtaily > 0:\n new_tail[1] += 1\n\n return tuple(new_tail)\n\nfor step in input.splitlines():\n direction, distance = step.split()\n distance = int(distance)\n print('==', direction, distance, '==')\n\n dx, dy = get_dir_deltas(direction)\n\n print_debug()\n\n for _ in range(distance):\n step_dx = dx\n step_dy = dy\n\n # move the head of the rope\n new_head = (rope[0][0] + dx, rope[0][1] + dy)\n rope[0] = new_head\n\n for idx in range(len(rope) - 1):\n head_idx = idx\n tail_idx = idx + 1\n\n new_tail = update_tail(rope[head_idx], rope[tail_idx])\n\n # rope[head_idx] = new_head\n rope[tail_idx] = new_tail\n # print_debug()\n # head, tail = update_positions(head, tail, dx, dy)\n tail_positions.add(rope[len(rope) - 1])\n\nprint('answer', len(tail_positions))","repo_name":"Chris-Johnston/adventofcode","sub_path":"2022/day09/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41864889257","text":"# -*- Mode: Python -*-\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport avl\n\n\ndef analyze_file(filename):\n f = {}\n with open(filename) as fle:\n data = fle.read()\n for ch in data:\n if ch in f:\n f[ch] += 1\n else:\n f[ch] = 1\n f = f.items()\n return [(x[1], x[0]) for x in f]\n\n\ndef huffman_tree(f):\n t = avl.newavl(f)\n while len(t) > 1:\n w1, c1 = n1 = t[0]\n w2, c2 = n2 = t[1]\n t.remove(n1)\n t.remove(n2)\n t.insert(((w1+w2), (c1, c2)))\n return t[0]\n\n\ndef walk(r, t, s=''):\n if isinstance(t, basestring):\n r.append((s, t))\n else:\n walk(r, t[0], s+'0')\n walk(r, t[1], s+'1')\n\n\ndef huffman_code(t):\n r = []\n walk(r, t[1])\n r = [(len(x[0]), x) for x in r]\n r.sort()\n return [x[1] for x in r]\n\n\nif __name__ == '__main__':\n import sys\n code = huffman_code(huffman_tree(analyze_file(sys.argv[1])))\n for s, ch in code:\n print('%08s %s' % (repr(ch), s))\n","repo_name":"samrushing/avl","sub_path":"huffman.py","file_name":"huffman.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"19622917465","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 15 01:30:30 2021\n\n@author: jeff\n\"\"\"\n\n\"\"\"\nKey Idea:\n remember minCoin(total) and everytime check minCoin(total - coin)\n\"\"\"\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n count = {}\n \n def minCoin(total):\n if total < 0:\n return -1\n if total == 0:\n return 0\n if total in count:\n return count[total]\n min_count = float(\"inf\")\n for coin in coins:\n res = minCoin(total - coin)\n if res >= 0 and res < min_count:\n min_count = 1 + res\n count[total] = min_count if min_count != float(\"inf\") else -1\n return count[total]\n \n return minCoin(amount)\n \n \nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n dp = [float(\"inf\")] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for i in range(coin, amount+1):\n dp[i] = min(dp[i], dp[i-coin] + 1)\n \n return dp[amount] if dp[amount] != float(\"inf\") else -1","repo_name":"r06921039/Leetcode","sub_path":"Dynamic Programming/322_Coin_Change.py","file_name":"322_Coin_Change.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"69624794","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 24 16:16:10 2018\n\n@author: Frevel\n\"\"\"\n\ndef fib_sum_even(limit):\n '''\n Returns the sum of all even fibonacci numbers up to limit.\n \n limit (int) : upper limit\n Returns int\n '''\n a = 1 # base case\n b = 2 # base case\n temp_result = 0\n result = 2\n while(a + b <= limit):\n temp_result = a + b\n a = b\n b = temp_result\n if temp_result % 2 == 0:\n result += temp_result\n return result\n\nprint(fib_sum_even(int(input(\"Get the sum of all even fibonacci numbers up to: \"))))","repo_name":"Frevel/Project-Euler","sub_path":"pe2.py","file_name":"pe2.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"6936675551","text":"# -*- coding: utf-8 -*-\n\"\"\"\nStiekeminleesfile\n\"\"\"\n\n{\n \"tags\": [\n \"remove-input\",\n ]\n}\n\nansw1 = widgets.Checkbox(\n value=False,\n description='You want to know whether you can predict blood glucose level from gene expression data, and have samples of gene expression data for patients with different blood glucose levels.',\n disabled=False,\n indent=False,\n layout = {'width': \"max-content\"}\n)\n\nansw2 = widgets.Checkbox(\n value=False,\n description='You\\'ve measured the transcriptome of single cells in a certain tissue and want to find out how many different cell types there are.',\n disabled=False,\n indent=False,\n layout = {'width': \"max-content\"}\n)\n\nansw3 = widgets.Checkbox(\n value=False,\n description='You\\'ve got data on formation of 3D DNA structures of interacting DNA and the chromatin marks along the DNA and want to predict 3D DNA structure formation.',\n disabled=False,\n indent=False,\n layout = {'width': \"max-content\"}\n)\n\nansw4 = widgets.Checkbox(\n value=False,\n description='You\\'ve got labeled data of the number of seals in aerial pictures of sand banks and try to train a convolutional neural network to automatically count the number of seals',\n disabled=False,\n indent=False,\n layout = {'width': \"max-content\"}\n)\n\n\n\n\nwidgets.Box(\n [\n answ1,\n answ2,\n answ3,\n answ4\n ]\n)\n\ndef checkCorrect(answOne, answTwo, answThree, answFour):\n sumAnswers = sum([answOne, answTwo, answThree, answFour])\n if sumAnswers >= 2:\n print('You should only select one option!')\n if answTwo == True and not sum([answOne, answThree, answFour]) >= 1:\n print(\"Correct. Here you don't know the true cell types and want to cluster in the multidimensional gene expression space on some distance metric!\")\n if sum([answOne, answTwo, answThree, answFour]) == 0:\n print(\"\")\n if sumAnswers == 1 and not answTwo == True:\n print(\"Incorrect, this is a supervised learning approach!\")\n\n\nprint(\"Which of the below best characterises an unsupervised learning problem?\")\nprint()\nwidgets.interact(checkCorrect,\n answOne = answ1, answTwo = answ2, answThree = answ3, answFour = answ4)\nprint()","repo_name":"DieStok/Basic-Machine-Learning-for-Bioinformatics","sub_path":"Day1/Practical/InteractiveQuestion1.py","file_name":"InteractiveQuestion1.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"15046998722","text":"import json\nfrom candidate import Candidates\n\n\ndef load_candidates_from_json(path):\n \"\"\"возвращает список всех кандидатов\"\"\"\n with open(path, 'r', encoding='utf-8') as f:\n data = json.load(f)\n arr = []\n for item in data:\n candidate = Candidates(item['id'], item['name'], item['picture'], item['position'], item['gender'],\n item['age'], item['skills'])\n arr.append(candidate)\n return arr\n\n\ndef get_candidate(candidate_id: int, arr: list) -> Candidates:\n \"\"\"возвращает одного кандидата по его id\"\"\"\n\n for item in arr:\n if item.id == candidate_id:\n return item\n\n\ndef get_candidates_by_name(candidate_name: str, arr: list) -> Candidates:\n \"\"\"возвращает кандидатов по имени\"\"\"\n\n ret_arr = []\n for item in arr:\n if candidate_name.lower() in item.name.lower():\n ret_arr.append(item)\n return ret_arr\n\n\ndef get_candidates_by_skill(skill_name: str, arr: list) -> Candidates:\n \"\"\"возвращает кандидатов по навыку\"\"\"\n\n ret_arr = []\n for item in arr:\n if skill_name.lower() in item.skills.lower():\n ret_arr.append(item)\n return ret_arr\n\n\n\n\n\n\n\n","repo_name":"Xytki/HomeWork_11","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38070902406","text":"#!/usr/bin/python3\n\"\"\"this module defines a module that prints a square with #\n\"\"\"\n\n\ndef print_square(size):\n \"\"\"print square func\n \"\"\"\n if type(size) is not int:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n\n for i in range(size):\n print(\"#\" * size)\n","repo_name":"duncmv/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/4-print_square.py","file_name":"4-print_square.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21355863893","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.nn.functional as F\nfrom collections import OrderedDict\n\nclass ConvBlock(nn.Module):\n \"\"\"Layer to perform a convolution followed by ELU\n \"\"\"\n def __init__(self, in_channels, out_channels):\n super(ConvBlock, self).__init__()\n\n self.conv = Conv3x3(in_channels, out_channels)\n self.nonlin = nn.ELU(inplace=True)\n\n def forward(self, x):\n out = self.conv(x)\n out = self.nonlin(out)\n return out\n\nclass Conv3x3(nn.Module):\n \"\"\"Layer to pad and convolve input\n \"\"\"\n def __init__(self, in_channels, out_channels, use_refl=True):\n super(Conv3x3, self).__init__()\n\n if use_refl:\n self.pad = nn.ReflectionPad2d(1)\n else:\n self.pad = nn.ZeroPad2d(1)\n self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3)\n\n def forward(self, x):\n out = self.pad(x)\n out = self.conv(out)\n return out\n \nclass UpSample(nn.Module):\n \n def __init__(self,):\n super(UpSample, self).__init__()\n self.pixel_shuffle = nn.PixelShuffle(upscale_factor = 2)\n \n def forward(self, x):\n \"\"\"Upsample input tensor by a factor of 2\n \"\"\"\n \n return self.pixel_shuffle(x)\n\n\nclass DepthDecoder(nn.Module):\n \"\"\"\n \"\"\"\n def __init__(self, config):\n super(DepthDecoder, self).__init__()\n\n self.config = config\n self.use_skip = True\n \n self.num_in_channels = [64, 256, 512, 1024, 2048]\n self.num_out_channels= [128, 256, 1024, 2048, 4096]\n self.N_gain = len(self.num_in_channels)\n \n self.upconvs = []\n for i in range(self.N_gain):\n num_in_channel = self.num_in_channels[i]\n num_out_channel = self.num_out_channels[i]\n \n self.upconvs.append(ConvBlock(num_in_channel, num_out_channel))\n \n self.upconvs = nn.ModuleList(self.upconvs)\n \n self.dispconv = ConvBlock(32, 1)\n \n self.upsample = UpSample()\n self.sigmoid = nn.Sigmoid()\n \n def forward(self, input_features):\n \n x = input_features[-1]\n \n for i in range(self.N_gain-1, -1, -1):\n x = self.upconvs[i](x)\n x = self.upsample(x)\n if i > 0:\n x += input_features[i-1]\n \n \n x = self.dispconv(x)\n \n disp = self.sigmoid(x)\n \n return disp\n\n\n","repo_name":"PengZai/dymicmono","sub_path":"networks/cnn/depth_decoder.py","file_name":"depth_decoder.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23711529073","text":"import cv2\nfrom google.colab.patches import cv2_imshow \nfrom sklearn.cluster import KMeans\nimport numpy as np\nimport random\nimport torch\nimport argparse\nfrom tqdm import tqdm\nimport os\n\n\n\nclass_to_color = {'ball': (255, 0, 255),\n 'player_team_1': (255, 0, 0),\n 'player_team_2': (0, 0, 255),\n 'referee': (0, 255, 0),\n 'outsider': (0, 204, 204)}\n\nclass_to_id = {'ball': 0,\n 'player_team_1': 1,\n 'player_team_2': 2,\n 'goalkeeper_team_1': 3,\n 'goalkeeper_team_2': 4,\n 'referee': 5,\n 'outsider': 6}\n\ndef parse_opt():\n parser = argparse.ArgumentParser()\n parser.add_argument('--source', type=str, help='input video path', required=True)\n parser.add_argument('--output_video', default = 'output_video.mp4', type=str, help='output video path')\n parser.add_argument('--output_bboxes', default = './results/', type=str, help='output bboxes directory path')\n parser.add_argument('--yolo_repo', default='./yolov5', type=str, help='yolov5 repository path')\n parser.add_argument('--model_weights', default='./weights/dpvsa_detector_1080.pt', type=str, help='output video path')\n parser.add_argument('--imsz', default=1080, type=int, help='model image input size')\n\n args = parser.parse_args()\n \n return args\n\n\ndef detect_video(args=None):\n\n # Initilizing video caputure and writing objects\n print(\"loading video input from {}\".format(args.source))\n video = cv2.VideoCapture(args.source)\n\n length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))\n width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = video.get(cv2.CAP_PROP_FPS)\n\n print(\"writing video output to {}\".format(args.output_video))\n video_writer = cv2.VideoWriter(args.output_video, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))\n\n # Loading pytorch object detector model\n print(\"loading model weights from {}\".format(args.model_weights))\n model = torch.hub.load(args.yolo_repo, 'custom', path=args.model_weights, source='local') \n\n # Initializing kmeans trained flag\n kmeans_trained = False\n\n\n print(\"using {} as model image input size\".format(args.imsz))\n # Processing each frame with our pipeline\n print(\"Processing frames...\")\n for i in tqdm(range(length)):\n\n ret, frame = video.read()\n\n if not ret:\n break\n\n # Getting object bounding boxes with yoloV5s \n with torch.no_grad():\n pred = model(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), args.imsz)\n\n bboxes = pred.pandas().xyxy[0].copy()\n\n # Cropping player bounding boxes as separate small images \n bboxes['cropped_image'] = None\n bboxes['rgb_average'] = None\n \n for idx, bbox in bboxes.iterrows():\n if bbox['name'] == 'person' or bbox['name'] == 'player':\n x1, x2, y1, y2 = int(bbox['xmin']), int(bbox['xmax']), int(bbox['ymin']), int(bbox['ymax'])\n cropped_image = frame[y1:y2, x1:x2]\n bboxes.at[idx,'cropped_image'] = cropped_image\n bboxes.at[idx,'rgb_average'] = cropped_image.mean(axis=0).mean(axis=0)\n\n # On the first frame, use the player patches to train a k-means model\n if not kmeans_trained and ('player' in list(bboxes['name']) or 'person' in list(bboxes['name'])):\n # cluster feature vectors\n kmeans = KMeans(n_clusters=2, random_state=22)\n avg = np.vstack(list(bboxes.loc[(bboxes['name'] == 'person') | (bboxes['name'] == 'player')]['rgb_average']))\n kmeans.fit(avg)\n kmeans_trained = True\n\n # Using k-mean model to cluster detected players in 2 groups\n bboxes['kmeans_result'] = None\n for idx, bbox in bboxes.iterrows():\n if bbox['name'] == 'person' or bbox['name'] == 'player':\n bboxes.at[idx,'kmeans_result'] = kmeans.predict([bbox['rgb_average']])[0]\n \n # Drawing bounding boxes and predicted labesl on frame\n for idx, bbox in bboxes.iterrows():\n if bbox['name'] == 'person' or bbox['name'] == 'player':\n if bbox['kmeans_result'] == 0:\n bbox['name'] = 'player_team_1'\n bboxes.at[idx, 'name'] = 'player_team_1'\n if bbox['kmeans_result'] == 1:\n bbox['name'] = 'player_team_2'\n bboxes.at[idx, 'name'] = 'player_team_2'\n\n x1, x2, y1, y2 = int(bbox['xmin']), int(bbox['xmax']), int(bbox['ymin']), int(bbox['ymax'])\n cv2.rectangle(frame, (x1,y1), (x2,y2), class_to_color[bbox['name']], thickness=2, lineType=cv2.LINE_AA)\n cv2.putText(frame, bbox['name'], (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, class_to_color[bbox['name']], 1)\n\n\n # Writing frame\n video_writer.write(frame)\n\n # Writing frame bboxes results\n if not os.path.isdir(args.output_bboxes):\n os.mkdir(args.output_bboxes)\n frame_results = np.array([[bbox['xmin'], bbox['ymin'], bbox['xmax'], bbox['ymax'], bbox['confidence'], class_to_id[bbox['name']]] for idx, bbox in bboxes.iterrows()])\n np.save(os.path.join(args.output_bboxes, 'result_frame_{}'.format(i+1)), frame_results)\n\n # After processing all frames, releasing video objects\n print(\"Done! Output video saved to {}\".format(args.output_video))\n \n video.release()\n video_writer.release()\n cv2.destroyAllWindows() \n\ndef main():\n args = parse_opt()\n detect_video(args)\n\nif __name__ == '__main__':\n main()\n","repo_name":"PauloGamarra/dpvsa2021-gpt4","sub_path":"detect_video.py","file_name":"detect_video.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"1291638091","text":"\nimport os\n\nimport helper_github_action as utils\nfrom helper_file_handler import FullRawFileHandler, PartConfFileHandler\nfrom utilities.base_utility import BaseUtility\n\n\nclass LoggerUtility(BaseUtility):\n\n def implement_utility(self):\n utils.info(\"Adding LoggerUtility.\")\n should_execute = True\n\n log_files_prefix = utils.get_input('logger_log_files_prefix')\n utils.info(\"log_files_prefix: {}\".format(log_files_prefix))\n if not log_files_prefix or log_files_prefix == \"NONE\":\n utils.error(\n \"skipping the logger adding as logger_log_files_prefix input is not defined.\")\n should_execute = False\n\n logger_sourcetype = utils.get_input('logger_sourcetype')\n utils.info(\"logger_sourcetype: {}\".format(logger_sourcetype))\n if not logger_sourcetype or logger_sourcetype == \"NONE\":\n utils.error(\n \"skipping the logger adding as logger_sourcetype input is not defined.\")\n should_execute = False\n\n self.words_for_replacement = {\n '<<>>': log_files_prefix,\n '<<>>': logger_sourcetype\n }\n\n if not should_execute:\n return False\n\n update1 = self.add_logger_manager_py()\n update2 = self.add_props_content()\n\n if update1 or update2:\n utils.info(\"Updated logger related files.\")\n return [\n os.path.join(utils.CommonDirPaths.APP_DIR_FOR_UTILITIES,\n 'bin', 'logger_manager.py'),\n os.path.join(utils.CommonDirPaths.APP_DIR_FOR_UTILITIES,\n 'default', 'props.conf')\n ]\n utils.info(\"No change in logger related files.\")\n\n\n def add_logger_manager_py(self):\n return FullRawFileHandler(\n os.path.join(os.path.dirname(__file__), 'logger_manager.py'),\n os.path.join(utils.CommonDirPaths.APP_DIR_FOR_UTILITIES,\n 'bin', 'logger_manager.py'),\n self.words_for_replacement\n ).validate_file_content()\n\n\n def add_props_content(self):\n return PartConfFileHandler(\n os.path.join(os.path.dirname(__file__), 'props.conf'),\n os.path.join(utils.CommonDirPaths.APP_DIR_FOR_UTILITIES,\n 'default', 'props.conf'),\n self.words_for_replacement\n ).validate_config()\n","repo_name":"VatsalJagani/splunk-app-action","sub_path":"src/utilities/logger/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"34497331558","text":"import os\nimport sys\nimport torch\nimport torchaudio\n\ntry:\n from speakerlab.process.processor import FBank\n from speakerlab.utils.builder import dynamic_import\nexcept ImportError:\n sys.path.append('%s/../..' % os.path.dirname(__file__))\n from speakerlab.process.processor import FBank\n from speakerlab.utils.builder import dynamic_import\n\nfrom modelscope.hub.snapshot_download import snapshot_download\nfrom modelscope.pipelines.util import is_official_hub_path\n\nERes2Net_COMMON = {\n 'obj': 'speakerlab.models.eres2net.ResNet_aug.ERes2Net',\n 'args': {\n 'feat_dim': 80,\n 'embedding_size': 192,\n }\n}\n\nsupports = {\n 'damo/speech_eres2net_sv_zh-cn_16k-common': {\n 'revision': 'v1.0.4',\n 'model': ERes2Net_COMMON,\n 'model_pt': 'pretrained_eres2net_aug.ckpt',\n }\n}\n\n\nclass embedding:\n def __init__(self, wav_file):\n model_id = 'damo/speech_eres2net_sv_zh-cn_16k-common'\n conf = supports[model_id]\n pretrained_model = \"./model/pretrained_eres2net_aug.ckpt\"\n pretrained_state = torch.load(pretrained_model,map_location=\"cuda:0\")\n\n model = conf['model']\n self.embedding_model = dynamic_import(model['obj'])(**model['args'])\n self.embedding_model.load_state_dict(pretrained_state)\n self.embedding_model.eval()\n self.feature_extractor = FBank(80, sample_rate=16000, mean_nor=True)\n self.wav_file = wav_file\n\n def load_wav(self):\n obj_fs = 16000\n wav_file = self.wav_file\n if type(wav_file) == str:\n wav, fs = torchaudio.load(wav_file)\n if fs != obj_fs:\n print(f'[WARNING]: The sample rate of {wav_file} is not {obj_fs}, resample it.')\n wav, fs = torchaudio.sox_effects.apply_effects_tensor(\n wav, fs, effects=[['rate', str(obj_fs)]]\n )\n if wav.shape[0] > 1:\n wav = wav[0, :].unsqueeze(0)\n return wav\n elif type(wav_file) == torch.Tensor:\n return wav_file\n\n def compute_embedding(self):\n wav = self.load_wav()\n feat = self.feature_extractor(wav).unsqueeze(0)\n with torch.no_grad():\n embedding = self.embedding_model(feat).detach().cpu().numpy()\n return embedding\n","repo_name":"FLamefiREz/speaker-verification","sub_path":"Speaker/speakerlab/bin/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"1863007372","text":"import jsonpickle\nfrom project import app\nfrom project.database import db_session\nfrom flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity, get_current_user\nfrom flask_classy import FlaskView, route\nfrom flask import jsonify, request\nimport datetime\nfrom project.model.user import User\nfrom project.model.class_model import Class\nfrom project.logger import Logger\nfrom project.controllers.utilities.user_management import Jwt_helper \n# from project.controllers.utilities.class_management import Json_helper\nfrom project.model.student import Student\nfrom project.model.exam import Exam \n\n\n\n\nclass ClassView(FlaskView):\n trailing_slash=True\n route_prefix='api'\n \n\n @route('/add/', methods=['POST'])\n @jwt_required\n def add(self):\n if not request.is_json:\n return jsonify({\"msg\": \"missing json request\"}), 400\n name = request.json.get(\"name\", None)\n desciption = request.json.get(\"description\", None)\n students = []\n user_id = get_current_user().id\n exams = []\n\n try:\n session = db_session()\n new_class = Class(name, desciption, students, user_id, exams)\n session.add(new_class)\n session.commit()\n return jsonify(success=True), 201\n except Exception as e:\n session.rollback()\n Logger.debug(\"could not create new class\")\n Logger.error(e.message)\n return jsonify(success=False), 400\n \n # @route('/get/limit//', methods=[\"GET\"])\n # # @jwt_required\n # def get_exams(self, limit):\n # try:\n # result = User.query.filter_by(username=\"ms95\").first().classes\n # result = Json_helper.to_send(result)\n # return jsonpickle.encode(result[0])\n # except IndexError:\n # return jsonify({'msg': 'list index out of range'}), 204\n\n\n\n\n @route('//add/students/', methods=['PUT'])\n @jwt_required\n def add_students(self, class_id):\n try:\n if not request.is_json:\n return jsonify({\"msg\": \"missing json request\"}), 400\n students = request.json.get('students', None)\n the_class = Class.query.filter_by(id=class_id).first()\n session = db_session()\n for student_id in students:\n student = Student.query.filter_by(id=student_id).first()\n student.classes.append(the_class)\n the_class.students.append(student)\n if the_class.exams:\n for exam in the_class.exams:\n exam.students.append(student)\n session.add(exam)\n session.add(the_class)\n session.add(student)\n session.commit()\n return jsonify(success=True), 200\n except Exception as e:\n session.rollback()\n Logger.debug(\"could not assign students to class\")\n Logger.error(e.message)\n return jsonify(success=False), 400\n\n \n @route('//add/exams/', methods=['PUT'])\n @jwt_required\n def add_exams(self, class_id):\n try:\n session = db_session()\n if not request.is_json:\n return jsonify({\"msg\": \"missing json request\"}), 400\n exams = request.json.get('exams', None)\n the_class = Class.query.filter_by(id=class_id).first()\n for exam_id in exams:\n exam = Exam.query.filter_by(id=exam_id).first()\n exam.students += the_class.students\n the_class.exams.append(exam)\n exam.classes.append(the_class)\n session.add(the_class)\n session.add(exam)\n session.commit()\n return jsonify(success=True), 200\n except Exception as e:\n session.rollback()\n Logger.debug(\"could not assign exams to class\")\n Logger.error(e.message)\n return jsonify(success=False), 400\n\n\nClassView.register(app)","repo_name":"Msiavashi/OMR-Flask","sub_path":"project/controllers/Class-API.py","file_name":"Class-API.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"74982534678","text":"#program converts the number into a number system of a given base\ndef konwersja_liczb (number,sys_base):\n \n #next number by which we can divide our number\n max_divider = sys_base\n\n #all dividers smaller than our number being next powers of our sys_base (for 2 those are 1,2,4,8,16,32 ...)\n dividers = [1]\n\n result=''\n\n #program find all powers of base system smaller than our number\n while max_divider <= number:\n dividers.append(max_divider)\n max_divider*=sys_base\n\n #program finds how many multilples of our dividers are in our number\n for i in reversed(dividers):\n result += str(number//i)\n number-=(i*(number//i))\n\n return result\n","repo_name":"Bauero/My_functions","sub_path":"Kon_to_other_sys.py","file_name":"Kon_to_other_sys.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19971226643","text":"import os, sys\r\nimport math, time\r\nimport logging\r\nimport traceback\r\nimport pygame\r\nfrom pygame.locals import *\r\n\r\n#Screen size in pixels\r\nscreen_width = 320\r\nscreen_height = 240\r\n\r\n#Crosshair Position\r\ncrosshair_pos = (200, 100)\r\n\r\n#Functions to create resources\r\nclass Crosshair(pygame.sprite.Sprite):\r\n def __init__(self, image, position):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.image.load(image)\r\n self.position = position\r\n\r\n def update(self):\r\n pos = pygame.mouse.get_pos()\r\n #pos = crosshair_pos\r\n self.rect = self.image.get_rect()\r\n self.rect.center = pos\r\n\r\nclass BorderX(pygame.sprite.Sprite):\r\n def __init__(self, image, position):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.image.load(image)\r\n self.position = position\r\n\r\n def update(self):\r\n pos = pygame.mouse.get_pos()\r\n #pos = crosshair_pos\r\n self.rect = self.image.get_rect()\r\n self.rect.center = pos\r\n self.rect.top = 0\r\n\r\nclass BorderY(pygame.sprite.Sprite):\r\n def __init__(self, image, position):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.image.load(image)\r\n self.position = position\r\n\r\n def update(self):\r\n pos = pygame.mouse.get_pos()\r\n #pos = crosshair_pos\r\n self.rect = self.image.get_rect()\r\n self.rect.center = pos\r\n self.rect.left = 0\r\n\r\ndef main():\r\n#Setup Logger\r\n logging.basicConfig(filename='debug.log',level=logging.DEBUG)\r\n logger = logging.getLogger(__name__)\r\n\r\n try:\r\n#Initialize PyGame\r\n pygame.init()\r\n # screen = pygame.display.set_mode((screen_width, screen_height))\r\n screen = pygame.display.set_mode((0,0))\r\n pygame.display.set_caption('PKE Screen')\r\n pygame.mouse.set_visible(0)\r\n font = pygame.font.SysFont('Lucida Console', 12, bold=False)\r\n\r\n pygame.mixer.music.load('media/PKE_Loop.wav')\r\n pygame.mixer.music.play(-1) #Plays loop forever\r\n\r\n#Create Background\r\n background = pygame.Surface(screen.get_size())\r\n background = background.convert()\r\n background.fill((230, 230, 200))\r\n\r\n#Display Background\r\n screen.blit(background, (0, 0))\r\n pygame.display.flip()\r\n\r\n#Prepare Game Objects\r\n rect = screen.get_rect()\r\n lines = Crosshair('media/lines.png', rect.center)\r\n borderx = BorderX('media/borderx.png', rect.center)\r\n bordery = BorderY('media/bordery.png', rect.center)\r\n allsprites = pygame.sprite.RenderPlain(lines, borderx, bordery)\r\n\r\n #Sine Wave Parameters\r\n frequency = 5\r\n amplitude = 20 #In pixels\r\n speed = 3\r\n sin_offset = 70\r\n\r\n#Main Loop\r\n while 1:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n return\r\n elif event.type == KEYDOWN:\r\n if event.key == pygame.K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()\r\n return\r\n\r\n #Update Sprites\r\n allsprites.update()\r\n\r\n #Calculate and Print Crosshair Coordinates (0,0 = middle of screen)\r\n #mouse_pos = pygame.mouse.get_pos()\r\n mouse_pos = crosshair_pos\r\n coordx = int(mouse_pos[0] - screen_width/2)\r\n coordy = int(screen_height - mouse_pos[1])\r\n coord_text = font.render('Position: (' + str(coordx) + ', ' + str(coordy) + ')', 1, (0, 0, 0))\r\n\r\n #Ghost Details\r\n class_text = font.render('Class: Unknown', 1, (0, 0, 0))\r\n\r\n #Set Background Color (must be done before drawing the sine wave)\r\n background.fill((230, 230, 200))\r\n\r\n #Calculate and Print Sine Wave\r\n for x in range(0, screen_width):\r\n y = int((screen_height/2) + amplitude * math.sin(frequency *((float(x)/320) * (2 * math.pi) + (speed*time.time())))) + sin_offset\r\n background.set_at((x, y), (0, 0, 0))\r\n\r\n #Draw Everything\r\n screen.blit(background, (0, 0))\r\n screen.blit(coord_text, (10, 5))\r\n screen.blit(class_text, (10, 20))\r\n allsprites.draw(screen)\r\n\r\n pygame.display.flip()\r\n\r\n except Exception as error:\r\n logger.exception(error)\r\n\r\n#this calls the 'main' function when this script is executed\r\nif __name__ == '__main__': main()\r\n","repo_name":"cfunseth/PyKE-Meter","sub_path":"pkeScreen.py","file_name":"pkeScreen.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33249618097","text":"\nfrom ATPS_functions import *\nimport os\nimport os.path\nimport shutil\nimport pandas as pd\nimport glob\nimport gc\nimport mne\nimport numpy as np\n#python3 runn.py -G TP53,RB1,BRCA1 -S Mus_musculus,Homo_sapiens,Rattus_norvegicus,canis_lupus,panthera_tigris,ovis_aries,orycteropus_afer,cervus_canadensis,prionailurus_bengalensis -I Rattus_norvegicus -R 100\n############# handle interest error\n\n\n#sudo python3 ATPS.py -G TP53,ATM,CDX2 -S Homo_sapiens,Felis_catus,Pan_troglodytes,Equus_caballus,Canis_lupus -I Homo_sapiens -A mu\n\n\nn = len(sys.argv)\ngenes = ''\nSpecies = ''\ninterest = ''\ninp_path = ''\ntax = ''\nsave = ''\nmodel_csv = ''\ncsv_instance = ''\ngblocks_state = \"T\"\nfor i in range(1,n):\n if sys.argv[i] == \"-G\": ## required\n genes = sys.argv[i+1].split(',')\n if sys.argv[i] == \"-S\": ## optional\n Species = sys.argv[i+1].split(',')\n if sys.argv[i] == \"-O\": ## optional required comment: create a folder and get the path of the folder using pwd command\n save = sys.argv[i+1]\n if sys.argv[i] == \"-T\": ## optional\n tax = sys.argv[i+1] \n if sys.argv[i] == \"-I\": ## optional\n interest = sys.argv[i+1]\n if sys.argv[i] == \"-IF\": ##optional\n inp_path = sys.argv[i+1]\n if sys.argv[i] == \"-A\": ##optional\n align_type = sys.argv[i+1]\n if sys.argv[i] == \"-R\": ##optional\n replica = sys.argv[i+1]\n if sys.argv[i] == '-C': ##optional\n cpu = sys.argv[i+1]\n if sys.argv[i] == '-RA': ##optional\n ram = sys.argv[i+1]\n if sys.argv[i] == '-GS':\n gblocks_state = sys.argv[i+1]\n \n \nif os.path.exists(save):\n print(f\"{save} exists\")\nelse:\n print(f\"{save} does not exist\")\n sys.exit(0)\n\n# print(os.system(\"pwd\"))\n# print(os.system(\"ls\"))\n# print(\":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\")\n# print(os.system(\"which phyml\"))\n# print(genes)\n# print(Species)\n# print(interest)\n# print(align_type)\n\n#os.system(\"touch /home/bioinfo/Desktop/you/Gblocks_0.91b/test.py\")\ntry:\n del_codeml_dir()\nexcept:\n pass\npath = path_dir()\ndeletion_files()\ntry:\n os.remove(\"Gene_Output.csv\")\nexcept:\n print(\"\")\n \n \n\n#print(\"=========================================================\")\n#print(\"downloading and setup Gblocks and Jmodeltest ........ pleas wait\")\n#print(\"=========================================================\")\n\n#download()\n\n#try:\n# os.system(\"codeml\")\n#except ImportError:\n# os.system(\"sudo apt-get install -y paml\") \n\n#try:\n# os.system(\"codeml\")\n#except ImportError:\n# print(\"Sorry you didn't install codeml on your device so you can install it by following the instruction in this link : http://abacus.gene.ucl.ac.uk/software/paml.html\")\n# q = input(\"to quit press 1 :\")\n# if q == \"1\" :\n# sys.exit(0)\n\ntry:\n os.remove(\"codeml.ctl\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"rst\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"rst1\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"rub\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"lnf\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"2NG.dN\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"2NG.dS\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"2NG.t\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"4fold.nuc\")\nexcept:\n print(\"\")\ntry:\n os.remove(\"mlc\")\nexcept:\n print(\"\")\n\ncounts = 0\ninp_file = ''\nfetch = 1\nif inp_path:\n genes = [\n os.path.basename(file_path).replace(\".fasta\", \"\") for file_path in glob.glob(f\"{inp_path}/*.fasta\")\n ]\n fetch = 0\n # inp_files = os.listdir(inp_path)\n # print(inp_files)\n # genes = [gene.split('.')[0] for gene in inp_files]\n#model = \"Name,Model0, Model7,Model8,Model8a,Model2a,Model2,LRT(M7_vs_M8),LRT(M8a_vs_M8),LRT(M2a_vs_M2),p-v7vs8,p-v8avs8,p-v2avs2\"\nLF = glob.glob(\"*\")\n# if \"Study_Output.csv\" not in LF:\n# os.system(\"echo 'Name,Model0, Model7,Model8,Model8a,Model2a,Model2,LRT(M7_vs_M8),LRT(M8a_vs_M8),LRT(M2a_vs_M2),p-v7vs8,p-v8avs8,p-v2avs2' >> Study_Output.csv\")\n\ncodeml_creating_file()\n\nwith open(f\"Study_Output.csv\", \"w\") as newfile:\n wr = csv.writer(newfile)\n wr.writerow([\"Name\",\"Model0\", \"Model7\", \"Model8\",\"Model8a\", \"Model2a\", \"Model2\", \"LRT(M7_vs_M8)\", \"LRT(M8a_vs_M8)\", \"LRT(M2a_vs_M2)\", \"p-v7vs8\", \"p-v8avs8\", \"p-v2avs2\"])\n \nfor g in genes:\n path = os.getcwd()\n #fetchingbyspecies(\"TP53\",[\"Mus musculus\",\"Homo sapiens\",\"Rattus norvegicus\"])\n deletion_files()\n print(\"=========================================================\")\n print(\"sequence fetching........ pleas wait\")\n print(\"=========================================================\")\n # if fetch == 0:\n # inp_file = inp_files[counts]\n\n list_empty, interestt = fetchingbyspecies(g,Species, interest, fetch, inp_path, inp_file)\n if list_empty == False:\n continue\n interest = interestt.lower()\n #key_list = fetching(tax, g)\n ###\n print(os.system(\"ls\"))\n print(list_empty, interestt)\n print(\"=========================================================\")\n print(\"sequence MSA has been started ........ pleas wait\")\n print(\"=========================================================\")\n file_path = \"ProteinSequences.fasta\"\n diff_aligners(file_path , align_type)\n #os.system(\"python3 exit.py\")\n if interest != '':\n reversedd(interest)\n else: reversedd(interest)\n print(\"=========================================================\")\n print(\"sequence filtration........ pleas wait\")\n print(\"=========================================================\")\n Gblocks(gblocks_state)\n convert_fst_phy()\n rem_spaces()\n jmodel()\n try:\n partition, freq, pinvar = parsing_jmodeltest()\n except:\n #os.system(\"sudo apt install default-jdk\")\n convert_fst_phy()\n rem_spaces()\n print(\"=========================================================\")\n print(\"model building........ pleas wait\")\n print(\"=========================================================\")\n jmodel()\n partition, freq, pinvar = parsing_jmodeltest()\n if partition == '' or freq == '':\n partition, freq, pinvar = spare_parse()\n if pinvar == '':\n pinvar = 'e'\n print(\"=========================================================\")\n print(\"bulding tree ........ pleas wait\")\n print(\"=========================================================\")\n try:\n os.system(\"sudo adduser --disabled-password --gecos '' atps\")\n except:\n print(\"\")\n #os.system(\"su atps\")\n phyml(partition, freq, pinvar, replica)\n try:\n convert_to_newickTree()\n except:\n #os.system(\"sudo apt-get install -y phyml\")\n phyml(partition, freq, pinvar, replica)\n convert_to_newickTree()\n \n parsing_treefile()\n try:\n del_codeml_dir()\n except:\n pass\n \n print(\"=========================================================\")\n print(\"phylofit running and wingscore will excecute ........ pleas wait\")\n print(\"=========================================================\")\n #try:\n # phast(g)\n #except:\n # pass\n creat_codeml_dir()\n os.system(\"python3 exit.py\")\n print(\"=========================================================\")\n print(\"codeml has been started model 078 ........ pleas wait it may take some time\")\n print(\"=========================================================\")\n model078()\n try:\n shutil.move(\"rub\", 'codeml078')\n except:\n # os.system(\"sudo apt-get install -y paml\")\n model078()\n shutil.move(\"rub\", 'codeml078')\n shutil.move(\"rst1\", 'codeml078')\n shutil.move(\"rst\", 'codeml078')\n shutil.move(\"lnf\", 'codeml078')\n shutil.move(\"codeml078_mlc.txt\", 'codeml078')\n shutil.move(\"2NG.t\", 'codeml078')\n shutil.move(\"2NG.dS\", 'codeml078')\n shutil.move(\"2NG.dN\", 'codeml078')\n shutil.move(\"4fold.nuc\", 'codeml078')\n os.system(\"python3 exit.py\")\n o = open(\"genes_without_BEB.txt\", \"w\")\n try:\n BEB_list = BEB(path)\n except:\n o.writelines(g)\n o.writelines(\"/n\")\n try:\n Positive_selection_sites(BEB_list ,interest,path)\n except:\n pass\n print(\"=========================================================\")\n print(\"codeml has been started model 8a ........ pleas wait it may take some time\")\n print(\"=========================================================\")\n model8a()\n print(interest)\n shutil.move(\"rub\", 'codeml8a')\n shutil.move(\"rst1\", 'codeml8a')\n shutil.move(\"rst\", 'codeml8a')\n shutil.move(\"lnf\", 'codeml8a')\n shutil.move(\"codeml8a_mlc.txt\", 'codeml8a')\n shutil.move(\"2NG.t\", 'codeml8a')\n shutil.move(\"2NG.dS\", 'codeml8a')\n shutil.move(\"2NG.dN\", 'codeml8a')\n shutil.move(\"4fold.nuc\", 'codeml8a')\n os.system(\"python3 exit.py\")\n if interest != '':\n print(interest)\n hashing(interest)\n print(\"=========================================================\")\n print(\"codeml has been started model 078 ........ pleas wait it may take some time\")\n print(\"=========================================================\")\n model2a()\n shutil.move(\"rub\", 'codeml2a')\n shutil.move(\"rst1\", 'codeml2a')\n shutil.move(\"rst\", 'codeml2a')\n shutil.move(\"lnf\", 'codeml2a')\n shutil.move(\"codeml2a_mlc.txt\", 'codeml2a')\n shutil.move(\"2NG.t\", 'codeml2a')\n shutil.move(\"2NG.dS\", 'codeml2a')\n shutil.move(\"2NG.dN\", 'codeml2a')\n shutil.move(\"4fold.nuc\", 'codeml2a')\n os.system(\"python3 exit.py\")\n print(\"=========================================================\")\n print(\"codeml has been started model 078 ........ pleas wait it may take some time\")\n print(\"=========================================================\")\n model2()\n shutil.move(\"rub\", 'codeml2')\n shutil.move(\"rst1\", 'codeml2')\n shutil.move(\"rst\", 'codeml2')\n shutil.move(\"lnf\", 'codeml2')\n shutil.move(\"codeml2_mlc.txt\", 'codeml2')\n shutil.move(\"2NG.t\", 'codeml2')\n shutil.move(\"2NG.dS\", 'codeml2')\n shutil.move(\"2NG.dN\", 'codeml2')\n shutil.move(\"4fold.nuc\", 'codeml2')\n os.system(\"python3 exit.py\")\n gc.collect()\n csv_instance = ''\n model_csv = ''\n if interest != '':\n models = codeml_output(1,g)\n with open(\"Study_Output.csv\", \"a\") as newfile:\n wr = csv.writer(newfile)\n wr.writerow(models)\n else:\n model = codeml_output(0,g)\n with open(\"Study_Output.csv\", \"a\") as newfile:\n wr = csv.writer(newfile)\n wr.writerow(models)\n print(\"=========================================================\")\n print(\"file saving ........\")\n print(\"=========================================================\")\n saving_(g, save)\n del_codeml_dir()\n counts += 1\n try:\n os.remove(\"Gene_Output.csv\")\n except:\n pass\n try:\n del_paths = glob.glob(os.path.join(path + '/' + g + '.gene','*.gene'))\n for del_path in del_paths:\n shutil.rmtree(del_path)\n except:\n pass\n##\n##\ndf = pd.read_csv(r'Study_Output.csv')\np78 = np.asfarray(df['p-v7vs8'])\na, x = mne.stats.bonferroni_correction(p78, alpha=0.05)\np88a = np.asfarray(df['p-v8avs8'])\nb, y = mne.stats.bonferroni_correction(p88a, alpha=0.05)\np22a = np.asfarray(df['p-v2avs2'])\nc, z = mne.stats.bonferroni_correction(p22a, alpha=0.05)\ndf['adj78'] = x\ndf['adj88a'] = y\ndf['adj22a'] = z\ndf.to_csv(f\"{save}/Study_Output_adjPvlaue.csv\")\nnumber_of_fetched_species()\n","repo_name":"ATP-S/Automated-Tool-for-Positive-Selection-ATPS-","sub_path":"Code/ATPS.py","file_name":"ATPS.py","file_ext":"py","file_size_in_byte":11518,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"20470197532","text":"from django.test import TestCase\n\nfrom ..factories import (\n EmailFactory,\n ExerciseFactory,\n EmailReplyFactory,\n EmailReplyTaskScoreFactory,\n ExerciseTaskFactory,\n)\n\nfrom ..models import ExerciseEmailProperties\n\n\nclass ExerciseModelTests(TestCase):\n\n def test_set_email_reveal_times_with_no_emails(self):\n exercise = ExerciseFactory()\n\n self.assertEqual(0, exercise.emails.all().count())\n exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise)\n self.assertEqual(0, exercise_reveal_times.count())\n\n def test_set_email_reveal_times_with_less_than_ten_emails(self):\n emails = EmailFactory.create_batch(4)\n exercise = ExerciseFactory.create(emails=emails)\n exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise)\n\n exercise.set_email_reveal_times()\n received_emails = [e for e in exercise_reveal_times if e.reveal_time is 0]\n\n self.assertEqual(4, exercise.emails.all().count())\n self.assertEqual(1, len(received_emails))\n\n def test_set_email_reveal_times_with_more_than_ten_emails(self):\n emails = EmailFactory.create_batch(27)\n exercise = ExerciseFactory.create(emails=emails)\n exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise)\n\n exercise.set_email_reveal_times()\n received_emails = [e for e in exercise_reveal_times if e.reveal_time is 0]\n\n self.assertEqual(27, exercise.emails.all().count())\n self.assertTrue(2 <= len(received_emails) <= 4)\n\n def test_sticky_received_emails(self):\n \"\"\"\n Current logic dictates that received emails shouldn't change after saving the Exercise.\n \"\"\"\n emails = EmailFactory.create_batch(35)\n exercise = ExerciseFactory.create(emails=emails)\n exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise)\n\n exercise.set_email_reveal_times()\n received_emails = [e for e in exercise_reveal_times if e.reveal_time is 0]\n received_email_ids = [re.id for re in exercise.emails.all()]\n\n self.assertEqual(35, exercise.emails.all().count())\n self.assertTrue(3 <= len(received_emails) <= 5)\n\n exercise.title = 'Updated Exercise'\n exercise.save()\n\n received_email_ids_after_update = [re.id for re in exercise.emails.all()]\n self.assertEqual(set(received_email_ids), set(received_email_ids_after_update))\n\n def test_email_reply_scoring(self):\n \"\"\"\n Test the EmailReply.score()\n \"\"\"\n task = ExerciseTaskFactory(\n name=\"Legend Score\",\n debrief_over_threshold=\"Well done for being a legend\",\n debrief_under_threshold=\"Try harder to reach legend status\",\n score_threshold=3,\n )\n\n email_reply = EmailReplyFactory()\n\n score_one = EmailReplyTaskScoreFactory(\n task=task,\n value=4,\n email_reply=email_reply,\n )\n\n score_two = EmailReplyTaskScoreFactory(\n task=task,\n value=2,\n )\n\n self.assertTrue(score_one in email_reply.scores)\n self.assertFalse(score_two in email_reply.scores)\n","repo_name":"dhenu79/phishtray-dev","sub_path":"exercise/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21904502672","text":"import cv2\n\n#Camara\ncap = cv2.VideoCapture(0)\n\n#Trackers e iniciador\ntracker = cv2.TrackerMOSSE_create()\n#tracker = cv2.TrackerCSRT_create()\nsuccess, img = cap.read()\nbbox = cv2.selectROI(\"Tracking\", img, False)\ntracker.init(img, bbox)\n\ndef drawBox(img, bbox):\n x ,y , w,h = int (bbox[0]), int (bbox[1]), int (bbox[2]), int (bbox[3])\n cv2.rectangle(img, (x,y), ((x+w), (y+h)), (255,0,255), 3 , 1)\n cv2.putText(img, \"Es de mas de 8000\", (75, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\nwhile True:\n#Loop de reconocimiento y captura de imagen\n timer = cv2.getTickCount()\n success, img = cap.read()\n\n success, bbox = tracker.update(img)\n print(bbox)\n\n if success:\n drawBox(img, bbox)\n else:\n cv2.putText(img, \"No se detecta el nivel de poder\", (75, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n fps = cv2.getTickFrequency()/(cv2.getTickCount()-timer)\n cv2.putText(img, str(int(fps)), (75,50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)\n cv2.imshow(\"Tracking\", img)\n\n if cv2.waitKey(1) & 0xff ==ord('q'):\n break\n\n","repo_name":"Guridi/TrackingObjetos","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70698144279","text":"from tkinter import ttk\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import messagebox\r\nfrom tkinter.font import Font\r\nfrom Speach2Text import STT\r\nimport sys\r\nsys.path.append('../summary/')\r\nfrom Base_Summary import Final_Summary\r\n\r\n# Root Setup\r\nroot = tk.Tk()\r\ntext = tk.Text(root)\r\n\r\n\r\n# setting the minimun size of the root window\r\nroot.minsize(400, 400)\r\n# Background Color of the window\r\nroot.configure(background='#242F3E')\r\n\r\nmyFont = Font(family=\"Times New Roman\", size=12,)\r\ntext.configure(font=myFont)\r\n\r\nmyFont.configure(size=30)\r\n\r\n\r\nroot.title('Recorder and Transcript')\r\n\r\nimg = PhotoImage(file='../image/microphone.png')\r\nroot.tk.call('wm', 'iconphoto', root._w, img)\r\n\r\nstyle = ttk.Style()\r\nstyle.theme_use('clam')\r\n\r\nphoto = PhotoImage(file='../image/microphone.png').subsample(40, 40)\r\n\r\n\r\n\r\n\r\nlabel1 = ttk.Label(root, text='To record the audio click the recorder and to stop click once again.')\r\nlabel1.grid(row=0, column=0)\r\n\r\nbtn2 = tk.StringVar()\r\n\r\n# Play the original audio\r\nPlayButton = ttk.Button(root, text='Play Original', width=20, command=STT.play_original)\r\nPlayButton.grid(row=10, column=0 , padx=10,pady=10)\r\n\r\n# Play the Summarized audio\r\nPlayButton = ttk.Button(root, text='Play Summary', width=20, command=STT.play_summary)\r\nPlayButton.grid(row=11, column=0 , padx=10,pady=10)\r\n\r\n# Display the summarized result\r\nMyButton1 = ttk.Button(root, text='Summary', width=20, command=STT.display_summary)\r\nMyButton1.grid(row=15, column=0,padx=10,pady=10)\r\n\r\n\r\n\r\n\r\n\r\nMyButton3 = ttk.Button(root, image=photo, command=STT.buttonClick)#, activebackground='#c1bfbf', overrelief='groove', relief='sunken')\r\nMyButton3.grid(row=5, column=0 , padx=10,pady=10)\r\n\r\nroot.wm_attributes('-topmost', 1)\r\nbtn2.set('google')\r\nroot.mainloop()","repo_name":"AniTho/Signy-Intern","sub_path":"Week 1/Recorder/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27187469062","text":"import torch\nfrom tqdm import trange\nfrom transformers import GPT2Tokenizer, GPT2LMHeadModel\n\n\nclass GPT2(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2-medium')\n self.model = GPT2LMHeadModel.from_pretrained(\n 'gpt2-medium',\n output_hidden_states=True\n )\n self.embed_size = self.model.transformer.config.hidden_size\n self.model.eval()\n for param in self.model.parameters():\n param.requires_grad = False\n\n def forward(self, x):\n with torch.no_grad():\n x = self.model(x)\n return x\n\n def get_repr(self, x):\n with torch.no_grad():\n hidden = self.model.transformer(x.long())\n return hidden['last_hidden_state']\n\n def generate_text(self, x, max_length):\n r\"\"\"\n args:\n x: a tokenized string.ex:'Who was Jim Henson ?'\n max_length: max_length of generate sentence.\n \"\"\"\n x = [50256] + self.tokenizer.encode(x)\n for _ in trange(max_length, ascii=True):\n context = torch.tensor([x])\n output = self(context)\n token = output['logits'][..., -1, :].argmax(dim=-1)\n x += [token.tolist()[-1]]\n\n return self.tokenizer.decode(x)\n\n\nif __name__ == \"__main__\":\n model = GPT2()\n sentence = 'Who was Jim Henson ?'\n a = model.tokenizer.encode(sentence)\n print(vars(model(torch.tensor(a)))['hidden_states'][-1])\n print(model.get_repr(torch.tensor(a)))\n","repo_name":"nail1021734/pplm","sub_path":"model/gpt2.py","file_name":"gpt2.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"11310575273","text":"import os\nimport poll_db as db\nfrom datetime import datetime, timedelta\nfrom telegram import (\n Update,\n InlineKeyboardMarkup,\n InlineKeyboardButton,\n ReplyKeyboardMarkup,\n ReplyKeyboardRemove,\n)\nfrom telegram.ext import (\n filters,\n MessageHandler,\n CommandHandler,\n CallbackContext,\n ConversationHandler,\n CallbackQueryHandler,\n)\nimport asyncio\n\nfrom utils import authenticated\n\n# Define the different states a chat can be in\n(\n ENTER_START_CREATION,\n ENTER_QUESTION,\n ENTER_OPTIONS,\n ENTER_CORRECT_ANSWER,\n ENTER_CREATE_POLL,\n ENTER_EXPLANATION,\n ENTER_SEND_POLL,\n) = range(7)\n\n# Dictionary to store the currently created poll\ncurrent_poll = {}\n\n# emotes\npill_emote = \"💊 \" # title poll\nalarm_emote = \"⏰ \" # poll closed\nlight_bulb_emote = \"💡 \" # leaderboard\n\ntop_emote = \"🔝 \" # longest streak\nfirst_medal_emote = \"🥇 \"\nsecond_medal_emote = \"🥈 \"\nthird_medal_emote = \"🥉 \"\nsos_emote = \"🆘 \"\nboom_emote = \"💥 \"\nsad_emote = \"😢 \"\nsun_emote = \"☀️ \"\nastronaut_emote = \"👨‍🚀 \"\nman_emote = \"👨 \"\ntoothbrush_emote = \"🪥 \"\nwalking_emote = \"🚶‍♂️ \"\nrocket_emote = \"🚀 \"\nearth_emote = \"🌍 \"\nstar_emote = \"⭐️ \"\nsatellite_emote = \"🛰 \"\nhi_emote = \"👋 \"\nmoon_emote = \"🌕 \"\nfootsteps_emote = \"👣 \"\nalien_emote = \"👽 \"\nknife_emote = \"🔪 \"\ngun_emote = \"🔫 \"\nmeat_emote = \"🥩 \"\nchef_emote = \"👨‍🍳 \"\ncomet_emote = \"☄️ \"\nmedal_emote = \"🎖 \"\nmayori_emote = \"🗿 \"\nufo_emote = \"🛸 \"\ncrown_emote = \"👑 \"\nstatue_emote = \"🗽 \"\n\n\ndef conversation_handler():\n conversation_handler = ConversationHandler(\n entry_points=[CommandHandler(\"create\", chose_creation)],\n states={\n ENTER_START_CREATION: [\n MessageHandler(filters.TEXT & ~filters.COMMAND, start_creation)\n ],\n ENTER_QUESTION: [\n MessageHandler(filters.TEXT & ~filters.COMMAND, enter_question)\n ],\n ENTER_OPTIONS: [\n MessageHandler(filters.TEXT & ~filters.COMMAND, enter_options)\n ],\n ENTER_CORRECT_ANSWER: [CallbackQueryHandler(enter_correct_answer)],\n ENTER_EXPLANATION: [\n MessageHandler(filters.TEXT & ~filters.COMMAND, enter_explanation)\n ],\n ENTER_CREATE_POLL: [CallbackQueryHandler(enter_create_poll)],\n ENTER_SEND_POLL: [CallbackQueryHandler(enter_send_poll)],\n },\n fallbacks=[],\n allow_reentry=True,\n )\n\n return conversation_handler\n\n\n# Function to handle the /reset command\n@authenticated\nasync def reset(update: Update, _: CallbackContext):\n current_poll.clear()\n reply_markup = ReplyKeyboardRemove()\n await update.message.reply_text(\n \"Poll resetted successfully!\\n\\nPress /create to create a new poll or /help to see the available commands.\",\n reply_markup=reply_markup,\n )\n\n@authenticated\n# Function to handle the /poll command\nasync def chose_creation(update: Update, _: CallbackContext):\n current_poll.clear()\n await update.message.reply_text(\n \"Choose what you want to do:\",\n reply_markup=ReplyKeyboardMarkup([[\"Create Poll\"]]),\n )\n return ENTER_START_CREATION\n\n\n# Function to handle the /poll command\nasync def start_creation(update: Update, context: CallbackContext):\n reply_markup = ReplyKeyboardRemove()\n text = update.message.text\n if text == \"Create Poll\":\n # Start the poll creation conversation\n await update.message.reply_text(\n \"Okay, let's create a poll!\\n\\nWrite the question:\",\n reply_markup=reply_markup,\n )\n if text == \"/reset\":\n await reset(update, context)\n return ConversationHandler.END\n\n return ENTER_QUESTION\n\n\n# Function to handle the question of the poll\nasync def enter_question(update: Update, context: CallbackContext):\n text = update.message.text\n if text == \"/reset\":\n await reset(update, context)\n return ConversationHandler.END\n if len(text) > 300:\n await update.message.reply_text(\n \"The question is \"\n + len(text)\n + \" characters! Please write a shorter one.\"\n )\n return ENTER_QUESTION\n \n current_poll_id = db.Poll().get_next_poll_id()\n intro = pill_emote + \"DEILIPILL #\" + str(current_poll_id)\n current_poll[\"question\"] = intro + \"\\n\\n\" + text\n await update.message.reply_text(\n \"Nice! Now send me the options separated with a comma (,). For example: Option 1,Option 2,Option 3,Option 4\"\n )\n return ENTER_OPTIONS\n\n\n# Function to handle the options of the poll\nasync def enter_options(update: Update, context: CallbackContext):\n text = update.message.text\n if text == \"/reset\":\n await reset(update, context)\n return ConversationHandler.END\n\n options = text.split(\",\")\n current_poll[\"options\"] = options\n keyboard = [\n [InlineKeyboardButton(option, callback_data=str(index))]\n for index, option in enumerate(options)\n ]\n reply_markup = InlineKeyboardMarkup(keyboard)\n await update.message.reply_text(\n \"Now choose the correct answer:\", reply_markup=reply_markup\n )\n return ENTER_CORRECT_ANSWER\n\n\n# Function to handle the correct answer of the poll\nasync def enter_correct_answer(update: Update, context: CallbackContext):\n selected_option = update.callback_query.data\n current_poll[\"correct_option\"] = int(selected_option)\n # scrivi un messaggio con il riepilogo del sondaggio\n await update.callback_query.message.reply_text(\n \"Nice! Now send me the explanation of the correct answer:\"\n )\n return ENTER_EXPLANATION\n\n\n# Function to handle the explanation of the poll\nasync def enter_explanation(update: Update, context: CallbackContext):\n text = update.message.text\n if text == \"/reset\":\n await reset(update, context)\n return ConversationHandler.END\n if len(text) > 200:\n await update.message.reply_text(\n \"The explanation is \"\n + len(text)\n + \" characters! Please write a shorter one.\"\n )\n return ENTER_EXPLANATION\n\n current_poll[\"explanation\"] = text\n await update.message.reply_text(\n \"Okay, the poll is ready!\\n\\nHere's a summary of the poll:\\n\\nQuestion:\\n\"\n + str(current_poll[\"question\"])\n + \"\\n\\nOptions:\\n\"\n + \"\\n\".join(current_poll[\"options\"])\n + \"\\n\\nCorrect answer: \"\n + str(current_poll[\"correct_option\"] + 1)\n + \"\\n\\nExplanation: \"\n + current_poll[\"explanation\"]\n + \"\\n\\nDo you want to create the poll?\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n \"Yes\", callback_data=str(0)\n ), # callback_data is used to identify different buttons\n InlineKeyboardButton(\"No\", callback_data=str(1)),\n ]\n ]\n ),\n )\n return ENTER_CREATE_POLL\n\n\n# Function to create the poll\nasync def enter_create_poll(update: Update, context: CallbackContext):\n # create the poll and save it in the surveys dictionary with a unique id\n selected_option = update.callback_query.data\n if selected_option == \"0\":\n await update.callback_query.message.reply_text(\n \"Poll created successfully!\\n\\nDo you want send the poll to the group?\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n \"Yes\", callback_data=str(0)\n ), # callback_data is used to identify different buttons\n InlineKeyboardButton(\"No\", callback_data=str(1)),\n ]\n ]\n ),\n )\n else:\n await update.callback_query.message.reply_text(\"Poll creation aborted!\")\n await reset(update, context)\n return ENTER_SEND_POLL\n\n\n# Function to send the poll to the group\nasync def enter_send_poll(update: Update, context: CallbackContext):\n # send the poll to the group\n selected_option = update.callback_query.data\n if selected_option == \"0\":\n # send the poll to the group\n poll_message = await context.bot.send_poll(\n chat_id=os.environ.get(\"GROUP_ID\"),\n question=current_poll[\"question\"],\n options=current_poll[\"options\"],\n is_anonymous=False,\n type=\"quiz\",\n correct_option_id=current_poll[\"correct_option\"],\n explanation=current_poll[\"explanation\"],\n )\n current_poll_id = db.Poll().get_next_poll_id()\n telegram_poll_id = poll_message.poll.id\n start_time = datetime.now()\n end_time = start_time + timedelta(hours=24)\n options = \", \".join(current_poll[\"options\"])\n\n # add the poll to the database\n db.Poll().add_poll(\n current_poll_id,\n telegram_poll_id,\n poll_message.message_id,\n current_poll[\"question\"],\n options,\n current_poll[\"correct_option\"],\n current_poll[\"explanation\"],\n start_time,\n end_time,\n )\n\n # schedule the poll to be closed\n asyncio.create_task(\n schedule_close_poll(\n context.bot, current_poll_id, poll_message.message_id, end_time\n )\n )\n\n await update.callback_query.message.reply_text(\"Poll sent successfully!\")\n else:\n await update.callback_query.message.reply_text(\"Poll sending aborted!\")\n await reset(update, context)\n return ConversationHandler.END\n\n\n@authenticated\nasync def generate_test_poll(update: Update, context: CallbackContext):\n # create a poll with a direct command instead of the conversation handler\n current_poll_id = db.Poll().get_next_poll_id()\n intro = pill_emote + \"DEILIPILL #\" + str(current_poll_id)\n question = intro + \"\\n\\n\" + \"What is the capital of Italy?\"\n options = [\"Rome\", \"Milan\", \"Turin\", \"Naples\"]\n correct_option = 1\n explanation = \"Milan is the capital of Italy.\"\n poll_message = await context.bot.send_poll(\n chat_id=os.environ.get(\"GROUP_ID\"),\n question=question,\n options=options,\n is_anonymous=False,\n type=\"quiz\",\n correct_option_id=correct_option,\n explanation=explanation,\n )\n telegram_poll_id = poll_message.poll.id\n start_time = datetime.now()\n end_time = start_time + timedelta(seconds=10)\n options = \", \".join(options)\n\n # add the poll to the database\n db.Poll().add_poll(\n current_poll_id,\n telegram_poll_id,\n poll_message.message_id,\n question,\n options,\n correct_option,\n explanation,\n start_time,\n end_time,\n )\n await update.message.reply_text(\"Poll sent successfully!\")\n\n asyncio.create_task(\n schedule_close_poll(\n context.bot, current_poll_id, poll_message.message_id, end_time\n )\n )\n return ConversationHandler.END\n\n\nasync def close_poll(bot, poll_id, message_id, delete):\n telegram_poll_id = db.Poll().get_telegram_poll_id_from_poll_id(poll_id)\n if not db.Poll().get_poll(telegram_poll_id):\n return\n \n db.Poll().close_poll(poll_id)\n await bot.stop_poll(chat_id=os.environ.get(\"GROUP_ID\"), message_id=message_id)\n\n if not delete:\n message = alarm_emote + \"DEILIPILL #\" + str(poll_id) + \" closed!\"\n await bot.send_message(chat_id=os.environ.get(\"GROUP_ID\"), text=message)\n\n db.Poll().update_scores(poll_id)\n await print_scoreboard(bot)\n\n\nasync def schedule_close_poll(bot, poll_id, message_id, end_date):\n delta = end_date - datetime.now()\n await asyncio.sleep(delta.total_seconds())\n\n telegram_poll_id = db.Poll().get_telegram_poll_id_from_poll_id(poll_id)\n if db.Poll().get_poll(telegram_poll_id)[9] == 1:\n return\n \n await close_poll(bot, poll_id, message_id, False)\n\n\nasync def print_scoreboard(bot):\n scoreboard = db.Poll().get_scoreboard()\n intro = f\"{light_bulb_emote} SCOREBOARD:\\n\\n\"\n results_string = intro + \"\\n\\n\".join(\n [\n compose_string(grid_position, score_tuple)\n for grid_position, score_tuple in enumerate(scoreboard, 1)\n ]\n )\n\n await bot.send_message(\n chat_id=os.environ.get(\"GROUP_ID\"),\n text=results_string,\n )\n\n\ndef compose_string(grid_position, score_tuple):\n _, username, score, streak, longest_streak = score_tuple\n if grid_position == 1:\n user_score = f\"{first_medal_emote}\\n{username}: {score} \"\n elif grid_position == 2:\n user_score = f\"{second_medal_emote}\\n{username}: {score} \"\n elif grid_position == 3:\n user_score = f\"{third_medal_emote}\\n{username}: {score} \"\n else:\n user_score = f\"{grid_position}.\\n{username}: {score} \"\n if streak == 0 and longest_streak == 0:\n return (\n user_score\n + f\"points\\nStreak not found{sad_emote}\\n{top_emote}streak: {longest_streak}\"\n )\n if streak == 0:\n return (\n user_score\n + f\"points\\n{sos_emote}{boom_emote}Streak over...{sad_emote}\\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 1:\n return (\n user_score\n + f\"points\\n({streak} in a row) {astronaut_emote}Get dressed... \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 2:\n return (\n user_score\n + f\"points\\n({streak} in a row) {rocket_emote}{walking_emote}Walking in... \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 3:\n return (\n user_score\n + f\"points\\n({streak} in a row) {earth_emote}{rocket_emote}Leaving Earth... \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 4:\n return (\n user_score\n + f\"points\\n({streak} in a row) {rocket_emote}{star_emote}In orbit! \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 5:\n return (\n user_score\n + f\"points\\n({streak} in a row) {rocket_emote}{hi_emote}{satellite_emote}Waving Starlink! \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 6:\n return (\n user_score\n + f\"points\\n({streak} in a row) {rocket_emote}{moon_emote}Approaching Moon... \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 7:\n return (\n user_score\n + f\"points\\n({streak} in a row) {astronaut_emote}{footsteps_emote}Walking on Moon... \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 8:\n return (\n user_score\n + f\"points\\n({streak} in a row) {astronaut_emote}{hi_emote}{alien_emote}Meeting Bang-o Bong-o!# \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 9:\n return (\n user_score\n + f\"points\\n({streak} in a row) {astronaut_emote}{knife_emote}{alien_emote}Killing Bang-o Bong-o!# \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 10:\n return (\n user_score\n + f\"points\\n({streak} in a row) {chef_emote}{meat_emote}Eating Bang-o Bong-o!# \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 11:\n return (\n user_score\n + f\"points\\n({streak} in a row) {moon_emote}{rocket_emote}Leaving Moon... \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 12:\n return (\n user_score\n + f\"points\\n({streak} in a row) {rocket_emote}{comet_emote}Watching Halley's comet! \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 13:\n return (\n user_score\n + f\"points\\n({streak} in a row) {rocket_emote}{earth_emote}Coming back to Earth... \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak == 14:\n return (\n user_score\n + f\"points\\n({streak} in a row) {man_emote}{medal_emote}Obtaining honors! \\n{top_emote}streak: {longest_streak}\"\n )\n elif streak > 14:\n return (\n user_score\n + f\"points\\n({streak} in a row) {mayori_emote}You are a Chad! \\n{top_emote}streak: {longest_streak}\"\n )\n\n","repo_name":"gianmarconaro/PollTelegramBot","sub_path":"poll_generator.py","file_name":"poll_generator.py","file_ext":"py","file_size_in_byte":16341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17107724334","text":"from ._types import SpecResult, SecurityCheckProgram, CheckPayload\nfrom . import _pss, _expert\n\nimport typing as t\n\nsupported_programs = [\n _pss.create_program(),\n _expert.create_program(),\n]\n\n\ndef check(\n programs: t.List[SecurityCheckProgram], payload: CheckPayload\n) -> t.List[SpecResult]:\n \"\"\"Run the security check programs on the given spec.\n\n Args:\n programs: List of programs to run.\n payload: The security check payload.\n\n Returns:\n A list of security check results.\n \"\"\"\n rv = []\n for program in programs:\n rv.append(program.check(payload))\n\n return rv\n\n\n__all__ = [\n \"SpecResult\",\n \"SecurityCheckProgram\",\n \"CheckPayload\",\n \"supported_programs\",\n \"check\",\n]\n","repo_name":"b4fun/SecKubeGPT","sub_path":"prompt/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"14105541764","text":"from Modules import *\n\ndef Imageprocessing(image):\n \n im = Image.open(image)\n\n # Define transforms\n preprocess = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])\n\n # Preprocess the image\n img_tensor = preprocess(im)\n return img_tensor.numpy()\n\n\n\n\n\ndef ImagePrediction(image_path, model, topks, device,indexClass):\n img=Imageprocessing(image_path)\n img = Image.open(image_path)\n img=torch.FloatTensor([img])\n model.eval()\n output=model(img.to(device))\n probability=torch.exp(output.cpu())\n top_p,top_c = probability.topk(topks,dim=1)\n# print(type(idx_to_class))\n top_class = [indexClass.get(x) for x in top_c.numpy()[0]]\n return top_p,top_class","repo_name":"joskalenda/Creat-image-classifer","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"39592670300","text":"# 모든 값이 0으로 채워져 있는 길이가 N인 배열 A가 있다. 영선이는 다음과 같은 두 연산을 수행할 수 있다.\n# 배열에 있는 값 하나를 1 증가시킨다.\n# 배열에 있는 모든 값을 두 배 시킨다.\n# 배열 B가 주어졌을 때, 배열 A를 B로 만들기 위한 연산의 최소 횟수를 구하는 프로그램을 작성하시오.\n\nn = int(input())\nobj_arr = list(map(int,input().split()))\ncnt = 0\ndef find_even(arr):\n for i in arr:\n if i % 2 == 1:\n return False\n return True\n\ndef count_odd(arr):\n cnt = 0\n for i in range(len(arr)):\n if arr[i] % 2 == 1:\n arr[i]-=1\n cnt+=1\n return cnt\n\nwhile obj_arr.count(0) != len(obj_arr):\n flag = find_even(obj_arr)\n if flag == True:\n for i in range(n):\n obj_arr[i] = obj_arr[i]//2\n cnt+=1\n elif flag == False:\n cnt += count_odd(obj_arr)\nprint(cnt)","repo_name":"ksunbum97/algorithm_test","sub_path":"백준/12931.py","file_name":"12931.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5959393173","text":"import pyblish.api\nfrom maya import cmds\n\n\nclass ValidateInstancesNote(pyblish.api.InstancePlugin):\n \"\"\"Validate Notes\n Check if there have some notes\n \"\"\"\n\n order = pyblish.api.ValidatorOrder\n hosts = [\"maya\"]\n label = \"Check Note\"\n\n def process(self, instance):\n assembly = instance.data[\"assembly\"]\n if assembly:\n try:\n notes = cmds.getAttr(assembly + \".notes\")\n except ValueError:\n notes = \"\"\n if not notes:\n self.log.warning(\"Did not found notes. Better write some.\")\n else:\n raise Exception(\"No assembly found.\")\n","repo_name":"getblessing/jiminy-tailcoat","sub_path":"tailcoat/plugins/maya/publish/validate_instances_note.py","file_name":"validate_instances_note.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23993347021","text":"from matplotlib.colors import LogNorm\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom process_data import DataLabels\n\ndef plot_features_vs_target(file_name, features, target, save_tag='features_vs_target'):\n data = pd.read_csv(file_name)\n fig = plt.figure(figsize=(7.0, 7.0))\n for i in range(len(features)):\n axs = plt.subplot(4, 4, i + 1)\n x = data[target]\n y = data[features[i]]\n axs.hist2d(x, y, bins=50, range=[(x.min(), x.max()), (y.min(), y.max())],\n cmap='rainbow', norm=LogNorm(), alpha=0.7)\n axs.text(0.03, 0.97, features[i] + ' vs ' + target,\n ha='left', va='top', fontsize=6.0, color='#d00', transform=plt.gca().transAxes)\n plt.subplots_adjust(left=0.07, right=0.98, top=0.98, bottom=0.04, wspace=0.4, hspace=0.2)\n plt.savefig(file_name.replace('data', 'plots').replace('.csv', '_' + save_tag))\n plt.close()\n\nif __name__ == '__main__':\n data_labels = DataLabels()\n features = data_labels.features\n target = data_labels.target\n plot_features_vs_target('data/training.csv', features, target)\n plot_features_vs_target('data/training_sampled.csv', features, target)\n plot_features_vs_target('data/training_sampled_processed.csv', features, target)\n plot_features_vs_target('data/validation.csv', features, target)\n plot_features_vs_target('data/validation_processed.csv', features, target)\n features = data_labels.features_ratio\n plot_features_vs_target('data/training_sampled_processed.csv', features, target,\n 'features_ratio_vs_target')\n","repo_name":"cdragoiu/machine_learning","sub_path":"chlorophyll_estimation/scripts/plot_features_vs_target.py","file_name":"plot_features_vs_target.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26130385066","text":"import os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport sys\nsys.path.append('./models')\nimport numpy as np\nfrom datetime import datetime\nfrom torchvision.utils import make_grid\nfrom net import SwinMCNet\nfrom data import get_loader,test_dataset\nfrom utils import clip_gradient\nfrom tensorboardX import SummaryWriter\nimport logging\nimport torch.backends.cudnn as cudnn\nfrom options import opt\nfrom loss.ssim import SSIM\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2,3\"\ncudnn.benchmark = True\n\n#build the model\nmodel = SwinMCNet()\nif(opt.load is not None):\n model.load_pre(opt.load)\n print('load model from ',opt.load)\nmodel = nn.DataParallel(model).cuda()\n# model = model.cuda()\n\n\nbase, body = [], []\nfor name, param in model.named_parameters(): \n if 'swin_image' in name or 'swin_thermal' in name:\n print(name)\n base.append(param)\n else:\n print(name)\n body.append(param)\noptimizer = torch.optim.SGD([{'params': base}, {'params': body}], lr=opt.lr, momentum=opt.momentum,\n weight_decay=opt.decay_rate, nesterov=True)\n\n\n#set the path\ntrain_root = opt.train_data_root\ntest_root = opt.val_data_root\n\nsave_path=opt.save_path\n\nif not os.path.exists(save_path):\n os.makedirs(save_path)\n\n#load data\nprint('load data...')\nnum_gpus = torch.cuda.device_count()\nprint(f\"========>num_gpus:{num_gpus}==========\")\ntrain_loader = get_loader(train_root, batchsize=opt.batchsize, trainsize=opt.trainsize)\ntest_loader = test_dataset(test_root, opt.trainsize)\ntotal_step = len(train_loader)\n\nlogging.basicConfig(filename=save_path+'log.log',format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]', level = logging.INFO,filemode='a',datefmt='%Y-%m-%d %I:%M:%S %p')\nlogging.info(\"SwinMCNet-Train\")\nlogging.info('epoch:{};lr:{};batchsize:{};trainsize:{};clip:{};decay_rate:{};load:{};save_path:{}'.format(opt.epoch,opt.lr,opt.batchsize,opt.trainsize,opt.clip,opt.decay_rate,opt.load,save_path))\n\n# loss\ndef iou_loss(pred, mask):\n pred = torch.sigmoid(pred)\n inter = (pred * mask).sum(dim=(2, 3))\n union = (pred + mask).sum(dim=(2, 3))\n iou = 1 - (inter + 1) / (union - inter + 1)\n return iou.mean()\nssim_loss = SSIM(window_size=11, size_average=True)\n\nstep=0\nwriter = SummaryWriter(save_path+'summary')\nbest_mae=1\nbest_epoch=1\n\n#train function\ndef train(train_loader, model, optimizer, epoch,save_path):\n global step\n model.train()\n loss_all=0\n epoch_step=0\n try:\n for i, (images, ts, gts, bodys, details) in enumerate(train_loader, start=1):\n optimizer.zero_grad()\n \n image, t, gt, body, detail = images.cuda(), ts.cuda(), gts.cuda(), bodys.cuda(), details.cuda()\n\n outi1, outt1, out1, outi2, outt2, out2 = model(image,t)\n \n \n lossi1 = F.binary_cross_entropy_with_logits(outi1, body) + ssim_loss(outi1, body)\n losst1 = F.binary_cross_entropy_with_logits(outt1, detail) + ssim_loss(outt1, detail)\n loss1 = F.binary_cross_entropy_with_logits(out1, gt) + iou_loss(out1, gt) + ssim_loss(out1, gt)\n\n lossi2 = F.binary_cross_entropy_with_logits(outi2, body) + ssim_loss(outi2, body)\n losst2 = F.binary_cross_entropy_with_logits(outt2, detail) + ssim_loss(outt2, detail)\n loss2 = F.binary_cross_entropy_with_logits(out2, gt) + iou_loss(out2, gt) + ssim_loss(out2, gt)\n\n loss = (lossi1 + losst1 + loss1 + lossi2 + losst2 + loss2)/2\n \n loss.backward()\n\n clip_gradient(optimizer, opt.clip)\n optimizer.step()\n step+=1\n epoch_step+=1\n loss_all+=loss.data\n if i % 50 == 0 or i == total_step or i==1:\n print('%s | epoch:%d/%d | step:%d/%d | lr=%.6f | lossi1=%.6f | losst1=%.6f | loss1=%.6f | lossi2=%.6f | losst2=%.6f | loss2=%.6f'\n %(datetime.now(), epoch, opt.epoch, i, total_step, optimizer.param_groups[0]['lr'], lossi1.item(), \n losst1.item(), loss1.item(), lossi2.item(), losst2.item(), loss2.item()))\n\n logging.info('##TRAIN##:Epoch [{:03d}/{:03d}], Step [{:04d}/{:04d}], lr_bk: {:.6f}, Loss1: {:.4f} Loss2: {:0.4f}'.\n format( epoch, opt.epoch, i, total_step, optimizer.param_groups[0]['lr'], loss1.data, loss2.data))\n writer.add_scalar('Loss', loss.data, global_step=step)\n grid_image = make_grid(images[0].clone().cpu().data, 1, normalize=True)\n writer.add_image('RGB', grid_image, step)\n grid_image = make_grid(gts[0].clone().cpu().data, 1, normalize=True)\n writer.add_image('Ground_truth', grid_image, step)\n res=out1[0].clone()\n res = res.sigmoid().data.cpu().numpy().squeeze()\n res = (res - res.min()) / (res.max() - res.min() + 1e-8)\n writer.add_image('out1', torch.tensor(res), step,dataformats='HW')\n res=out2[0].clone()\n res = res.sigmoid().data.cpu().numpy().squeeze()\n res = (res - res.min()) / (res.max() - res.min() + 1e-8)\n writer.add_image('out2', torch.tensor(res), step,dataformats='HW')\n \n loss_all/=epoch_step\n logging.info('##TRAIN##:Epoch [{:03d}/{:03d}], Loss_AVG: {:.4f}'.format( epoch, opt.epoch, loss_all))\n writer.add_scalar('Loss-epoch', loss_all, global_step=epoch)\n if (epoch) % 50 == 0:\n torch.save(model.state_dict(), save_path+'SwinMCNet_epoch_{}.pth'.format(epoch))\n except KeyboardInterrupt: \n print('Keyboard Interrupt: save model and exit.')\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n torch.save(model.state_dict(), save_path+'SwinMCNet_epoch_{}.pth'.format(epoch))\n print('save checkpoints successfully!')\n raise\n \n#test function\ndef test(test_loader,model,epoch,save_path):\n global best_mae,best_epoch\n model.eval()\n with torch.no_grad():\n mae_sum=0\n #for i in range(1000):\n for i in range(test_loader.size):\n image, t, gt, (H, W), name = test_loader.load_data()\n gt = np.asarray(gt, np.float32)\n gt /= (gt.max() + 1e-8)\n image = image.cuda()\n t = t.cuda()\n #shape = (W,H)\n outi1, outt1, out1, outi2, outt2, out2 = model(image,t)\n res = out2\n res = F.interpolate(res, size=gt.shape, mode='bilinear')\n res = res.sigmoid().data.cpu().numpy().squeeze()\n res = (res - res.min()) / (res.max() - res.min() + 1e-8)\n mae_sum += np.sum(np.abs(res-gt))*1.0/(gt.shape[0]*gt.shape[1])\n mae=mae_sum/test_loader.size\n writer.add_scalar('MAE', torch.tensor(mae), global_step=epoch)\n print('\\n')\n print('##TEST##:Epoch: {} MAE: {}'.format(epoch,mae))\n \n if epoch==1:\n best_mae=mae\n else:\n if mae 40:\n pay = ((emp_hrs -40)*1.5*rate )+ 40 *rate\n else:\n pay = emp_hrs *rate\n\n print(\"Pay:\", pay)\n \n\nexcept:\n print(\"please enter valid number\")\n","repo_name":"gitabhinav/python","sub_path":"employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"37377482366","text":"#!/usr/bin/python3\n\"\"\"Define a class called Square\"\"\"\n\n\nclass Square:\n \"\"\"Represents a square.\n \n Attributes:\n __size (int): side of the square\n --position (tuple): position of the object\n \"\"\"\n\n def __init__(self, size=0, position=(0, 0)):\n \"\"\"Initializes the data.\n \n\n Args:\n size (int): The side length of the square (default is 0).\n position (tuple): The position of the square (default is (0, 0)).\n \"\"\"\n self.size = size\n self.position = position\n def __str__(self):\n \"\"\"Str method for print from main module.\n\n\n Returns:\n str: The string representation of the square.\n \"\"\"\n my_str = \"\"\n if self.__size == 0:\n return ''\n else:\n my_str += '\\n' * self.__position[1]\n for i in range(0, self.__size):\n my_str += ' ' * self.__position[0]\n my_str += '#' * self.__size\n my_str += '\\n'\n return my_str[:-1]\n\n @property\n def size(self):\n \"\"\"Retrieves the size.\"\"\"\n return self.__size\n\n @size.setter\n def size(self, value):\n \"\"\"Sets the size.\n\n Args:\n value (int): The size of the square.\n\n Raises:\n TypeError: If the value is not an integer.\n ValueError: If the value is less than 0.\n \"\"\"\n if not isinstance(value, int):\n raise TypeError(\"size must be an integer\")\n elif value < 0:\n raise ValueError(\"size must be >= 0\")\n self.__size = value\n\n @property\n def position(self):\n \"\"\"tuple: Retrieves the position.\"\"\"\n return self.__position\n\n @position.setter\n def position(self, value):\n \"\"\"reset the position to the square\n \n\n Args:\n value (tuple): The position of the square as a tuple of 2 positive integers.\n\n Raises:\n TypeError: If the value is not a tuple of 2 positive integers.\n \"\"\"\n if not isinstance(value, tuple) or len(value) != 2:\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n if not isinstance(value[0], int) or not isinstance(value[1], int):\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n if value[0] < 0 or value[1] < 0:\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n self.__position = value\n\n def area(self):\n \"\"\"calculate area of the square.\n\n\n Returns:\n int: The area of the square.\n \"\"\"\n return self.__size ** 2\n\n def my_print(self):\n \"\"\"Prints the square object\n\n Returns:\n None\n \"\"\"\n if self.__size == 0:\n print()\n else:\n for y in range(0, self.__position[1]):\n print()\n for i in range(0, self.__size):\n for x in range(0, self.__position[0]):\n print(\" \", end=\"\")\n for j in range(0, self.__size):\n print(\"#\", end=\"\")\n print()\n return ''\n","repo_name":"Amel83/alx-higher_level_programming","sub_path":"0x06-python-classes/101-square.py","file_name":"101-square.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"7881013579","text":"import utils.bvh2np as BVHLIB\nimport math\nimport copy\nimport numpy as np\nfrom pathlib import Path\n\nclass BVHChannel(object):\n ChannelTransformMatrixMap = {\n 'Xposition': lambda x: np.array([[1, 0, 0, x],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]]),\n 'Yposition': lambda x: np.array([[1, 0, 0, 0],\n [0, 1, 0, x],\n [0, 0, 1, 0],\n [0, 0, 0, 1]]),\n 'Zposition': lambda x: np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, x],\n [0, 0, 0, 1]]),\n 'Xrotation': lambda x: np.array([[1, 0, 0, 0],\n [0, math.cos(math.radians(x)), -math.sin(math.radians(x)), 0],\n [0, math.sin(math.radians(x)), math.cos(math.radians(x)), 0],\n [0, 0, 0, 1]]),\n 'Yrotation': lambda x: np.array([[math.cos(math.radians(x)), 0, math.sin(math.radians(x)), 0],\n [0, 1, 0, 0],\n [-math.sin(math.radians(x)), 0, math.cos(math.radians(x)), 0],\n [0, 0, 0, 1]]),\n 'Zrotation': lambda x: np.array([[math.cos(math.radians(x)), -math.sin(math.radians(x)), 0, 0],\n [math.sin(math.radians(x)), math.cos(math.radians(x)), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n }\n def __init__(self, name):\n super().__init__()\n self.name = name\n self.value = 0.0\n\n def set_value(self, value):\n self.value = value\n\n def matrix(self):\n return BVHChannel.ChannelTransformMatrixMap[self.name](self.value)\n\n def str(self):\n return 'Channel({name}) = {value}'.format(name=self.name, value=self.value)\n\nclass BVHNode(object):\n def __init__(self, name, offsets, channel_names, children, weight=1):\n super().__init__()\n self.name = name\n self.children = children # []\n self.channels = [BVHChannel(cn) for cn in channel_names] # []\n self.offsets = offsets # x, y, z\n # weight for calculate frame-frame distance\n self.weight = weight\n\n def search_node(self, name):\n if self.name == name:\n return self\n for child in self.children:\n result = child.search_node(name)\n if result:\n return result\n return None\n\n def __load_frame(self, frame_data_array):\n ''' \n this function modify frame_data_array, so \n make sure you only call load_frame instead of this\n '''\n for channel in self.channels:\n channel.set_value(frame_data_array.pop(0))\n for child in self.children:\n child.__load_frame(frame_data_array)\n\n def load_frame(self, frame_data_array):\n frame_data_array = copy.copy(frame_data_array)\n self.__load_frame(frame_data_array)\n\n def apply_transformation(self, parent_tran_matrix=np.identity(4)):\n self.coordinates = np.zeros((3,1))\n local_translation = np.array([[1, 0, 0, self.offsets[0]],\n [0, 1, 0, self.offsets[1]],\n [0, 0, 1, self.offsets[2]],\n [0, 0, 0, 1]])\n tran_matrix = np.identity(4)\n tran_matrix = np.dot(tran_matrix, parent_tran_matrix)\n tran_matrix = np.dot(tran_matrix, local_translation)\n for channel in self.channels:\n tran_matrix = np.dot(tran_matrix, channel.matrix())\n self.coordinates = np.dot(tran_matrix, np.append(self.coordinates, [[1]], axis=0))[:3]\n for child in self.children:\n child.apply_transformation(tran_matrix)\n\n def str(self, show_coordinates=False):\n s = 'Node({name}), offset({offset})\\n'\\\n .format(name=self.name,\n offset=', '.join([str(o) for o in self.offsets]))\n if show_coordinates:\n try:\n s = s + '\\tWorld coordinates: (%.2f, %.2f, %.2f)\\n' % (self.coordinates[0],\n self.coordinates[1],\n self.coordinates[2])\n except Exception as e:\n print('World coordinates is not available, call apply_transformation() first')\n s = s + '\\tChannels:\\n'\n for channel in self.channels:\n s = s + '\\t\\t' + channel.str() + '\\n'\n for child in self.children:\n lines = child.str(show_coordinates=show_coordinates).split('\\n')\n for line in lines:\n s = s + '\\t' + line + '\\n'\n return s\n\n def distance(node_a, node_b):\n assert(node_a.name == node_b.name and node_a.weight == node_b.weight)\n distance = np.linalg.norm(node_a.coordinates - node_b.coordinates) * node_a.weight\n for child_a, child_b in zip(node_a.children, node_b.children):\n distance += BVHNode.distance(child_a, child_b)\n return distance\n\n def frame_distance(self, frame_a, frame_b):\n root_a = copy.deepcopy(self)\n root_a.load_frame(frame_a)\n root_a.apply_transformation()\n root_b = copy.deepcopy(self)\n root_b.load_frame(frame_b)\n root_b.apply_transformation()\n return BVHNode.distance(root_a, root_b)\n\n\ndef parse_bvh_node(bvhlib_node):\n '''This function parses object from bvh-python (https://github.com/20tab/bvh-python)'''\n name = bvhlib_node.name\n offsets = [float(f) for f in bvhlib_node.children[0].value[1:]]\n channel_names = []\n for channels in bvhlib_node.filter('CHANNELS'):\n channel_names = [c for c in channels.value[2:]]\n children = []\n for c in bvhlib_node.filter('JOINT'):\n children.append(parse_bvh_node(c))\n node = BVHNode(name, offsets,\n channel_names, children)\n return node\n\ndef loads(s):\n bvhlib = BVHLIB.Bvh(s)\n root = parse_bvh_node(bvhlib.get_joints()[0])\n return root, [[float(f) for f in frame] for frame in bvhlib.frames], bvhlib.frame_time\n\ndef load(file_path):\n with open(file_path, 'r') as f:\n return loads(f.read())\n \n\nclass BvhNode(object):\n def __init__(\n self, name, offset, rotation_order,\n children=None, parent=None, is_root=False, is_end_site=False):\n if not is_end_site and \\\n rotation_order not in ['xyz', 'xzy', 'yxz', 'yzx', 'zxy', 'zyx']:\n raise ValueError(f'Rotation order invalid.')\n self.name = name\n self.offset = offset\n self.rotation_order = rotation_order\n self.children = children\n self.parent = parent\n self.is_root = is_root\n self.is_end_site = is_end_site\n \n\nclass BvhHeader(object):\n def __init__(self, root, nodes):\n self.root = root\n self.nodes = nodes\n\n\ndef write_header(writer, node, level):\n indent = ' ' * 4 * level\n if node.is_root:\n writer.write(f'{indent}ROOT {node.name}\\n')\n channel_num = 6\n elif node.is_end_site:\n writer.write(f'{indent}End Site\\n')\n channel_num = 0\n else:\n writer.write(f'{indent}JOINT {node.name}\\n')\n channel_num = 3\n writer.write(f'{indent}{\"{\"}\\n')\n\n indent = ' ' * 4 * (level + 1)\n writer.write(\n f'{indent}OFFSET '\n f'{node.offset[0]} {node.offset[1]} {node.offset[2]}\\n'\n )\n if channel_num:\n channel_line = f'{indent}CHANNELS {channel_num} '\n if node.is_root:\n channel_line += f'Xposition Yposition Zposition '\n channel_line += ' '.join([\n f'{axis.upper()}rotation'\n for axis in node.rotation_order\n ])\n writer.write(channel_line + '\\n')\n \n for child in node.children:\n write_header(writer, child, level + 1)\n \n indent = ' ' * 4 * level\n writer.write(f'{indent}{\"}\"}\\n')\n\n\ndef write_bvh(output_file, header, channels, frame_rate=30):\n output_file = Path(output_file)\n if not output_file.parent.exists():\n os.makedirs(output_file.parent)\n \n with output_file.open('w') as f:\n f.write('HIERARCHY\\n')\n write_header(writer=f, node=header.root, level=0)\n \n f.write('MOTION\\n')\n f.write(f'Frames: {len(channels)}\\n')\n f.write(f'Frame Time: {1 / frame_rate}\\n')\n\n for channel in channels:\n f.write(' '.join([f'{element}' for element in channel]) + '\\n')\n","repo_name":"EninumXJ/EgoMotion","sub_path":"utils/bvh_helper.py","file_name":"bvh_helper.py","file_ext":"py","file_size_in_byte":8942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"35675231449","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom os import environ, path\n\ndb = SQLAlchemy()\nDB_NAME = \"database.db\"\n\ndef create_app():\n app = Flask(__name__)\n app.config[\"SECRET_KEY\"] = environ.get(\"SECRET_KEY\", \"dev\")\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = f\"sqlite:///{DB_NAME}\"\n db.init_app(app)\n\n from .views import views\n\n app.register_blueprint(views, url_prefix=\"/\")\n create_database(app)\n\n return app\n\ndef create_database(app):\n if not path.exists(f\"website/{DB_NAME}\"):\n db.create_all(app=app)","repo_name":"GameGenesis/Country-Geoguessr","sub_path":"website/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"33290966177","text":"n, m = list(map(int, input().split()))\n\nfirst_plate = list()\nfor item in range(n):\n plate = input()\n first_plate.append(plate)\n\nsecond_plate = list()\nfor item in range(n):\n plate = input()\n second_plate.append(plate)\n \n\ndef count_meat(plates : list) -> int :\n result = 0\n \n for item in plates:\n meet = item.count('*')\n result +=meet\n \n return result\n\nprint(f\"{count_meat(first_plate)} {count_meat(second_plate)}\")","repo_name":"AliAlizadeh11/quera_problems","sub_path":"p210.py","file_name":"p210.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"7423640943","text":"import sys\n\nimport scipy.stats\n\ntypes = [str, int, int, int, int]\ndata = ([f(x) for f, x in zip(types, line.split())] for line in sys.stdin)\nT = scipy.stats.fisher_exact\nfor name, fg_hits, fg_total, bg_hits, bg_total in data:\n print(name, *T([[fg_hits, fg_total - fg_hits],\n [bg_hits, bg_total - bg_hits]],\n alternative='greater'))\n","repo_name":"aksarkar/frea-work","sub_path":"enr/conservation/fisher.py","file_name":"fisher.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38708499751","text":"import pygame\r\nimport random\r\n\r\ndef control(state):\r\n global player1_v, player2_v, player1_y, player2_y\r\n \r\n keys = pygame.key.get_pressed()\r\n if state == 2:\r\n if keys[pygame.K_w]:\r\n player1_v = -5\r\n elif keys[pygame.K_s]:\r\n player1_v = 5\r\n else:\r\n player1_v = 0\r\n elif state == 1:\r\n if ball_x < width // 2 and ball_vx < 0:\r\n if player1_y + player_height // 2 < ball_y:\r\n player1_v = 5\r\n elif player1_y + player_height // 2 > ball_y:\r\n player1_v = -5\r\n else:\r\n player1_v = 0\r\n else:\r\n player1_v = 0\r\n \r\n if keys[pygame.K_UP]:\r\n player2_v = -5\r\n elif keys[pygame.K_DOWN]:\r\n player2_v = 5\r\n else:\r\n player2_v = 0\r\n\r\n player1_y += player1_v\r\n player1_y = max(player1_y, 0)\r\n player1_y = min(player1_y, height - player_height)\r\n\r\n player2_y += player2_v\r\n player2_y = max(player2_y, 0)\r\n player2_y = min(player2_y, height - player_height)\r\n\r\n\r\ndef judge():\r\n global width, height,ball_v, ball_vx, ball_vy, ball_x, ball_y, ball_r, player1_v, player2_v, player1_y, player2_y, gap, player1_score, player2_score, mode, win, score\r\n \r\n if (ball_vx < 0) and (ball_x - gap - player_width - ball_r <= 0) and (ball_y >= player1_y and ball_y <= (player1_y + player_height)):\r\n ball_vx = - ball_vx\r\n sound = pygame.mixer.Sound('pong.wav')\r\n sound.play()\r\n if ball_v <= 6.4:\r\n ball_v *= random.randint(10,14) / 10\r\n else:\r\n ball_v *= random.randint(7,10) / 10\r\n \r\n elif (ball_vx > 0) and (width - gap - player_width - ball_r - ball_x <= 0) and (ball_y >= player2_y and ball_y <= (player2_y + player_height)):\r\n ball_vx = - ball_vx\r\n sound = pygame.mixer.Sound('pong.wav')\r\n sound.play()\r\n if ball_v <= 6.4:\r\n ball_v *= random.randint(10,14) / 10\r\n else:\r\n ball_v *= random.randint(7,10) / 10\r\n score += 1\r\n \r\n if player1_score == 5 or player2_score == 5:\r\n if player1_score == 5:\r\n x = 1\r\n elif player2_score == 5:\r\n x = 2\r\n font = pygame.font.Font(\"times.ttf\", 45)\r\n screen.fill(WHITE)\r\n text = font.render(f\"player {x} wins!\", True, RED)\r\n text_rect = text.get_rect()\r\n text_rect.center = (width // 2, height // 2)\r\n screen.blit(text, text_rect)\r\n win.play()\r\n\r\n\r\ndef ball():\r\n global width, height, ball_v, ball_vx, ball_vy, ball_x, ball_y, ball_r, player1_v, player2_v, player1_y, player2_y, gap, player1_score, player2_score\r\n \r\n screen.fill(WHITE)\r\n pygame.draw.line(screen, RED, [width // 2, 0], [width // 2, height], 2)\r\n pygame.draw.circle(screen, BLACK, (ball_x, ball_y), ball_r)\r\n pygame.draw.rect(screen, GREEN, (gap, player1_y, player_width, player_height))\r\n pygame.draw.rect(screen, RED, (width - gap - player_width, player2_y, player_width, player_height))\r\n \r\n if ball_x <= ball_r:\r\n reset_ball()\r\n player2_score += 1\r\n elif ball_x >= (width - ball_r):\r\n reset_ball()\r\n player1_score += 1\r\n \r\n if ball_y <= ball_r or ball_y >= (height - ball_r):\r\n ball_vy = - ball_vy\r\n sound = pygame.mixer.Sound('table.mp3')\r\n sound.play()\r\n\r\n ball_x += ball_vx\r\n ball_y += ball_vy\r\n\r\n\r\ndef reset_ball():\r\n global ball_x, ball_y, ball_vx, ball_vy, ball_r, player1_y, player2_y\r\n \r\n ball_x = width // 2\r\n ball_y = random.randint(height // 4, (height // 4) * 3)\r\n ball_v = 6\r\n ball_vx = random.randint(48,55) / 10\r\n player1_y = height // 2 - player_height // 2\r\n player2_y = height // 2 - player_height // 2\r\n if random.choice([True, False]):\r\n ball_vx = - ball_vx\r\n ball_vy = (ball_v ** 2 - ball_vx **2) ** 0.5\r\n pygame.time.wait(500)\r\n\r\n\r\ndef ui(state):\r\n global player1_score, player2_score, width, height, mode, score\r\n \r\n if state == 2:\r\n text = font.render(f\"player 1: {player1_score} player 2: {player2_score}\", True, BLACK)\r\n text_rect = text.get_rect()\r\n text_rect.center = (width // 2, height // 2)\r\n screen.blit(text, text_rect)\r\n\r\n elif state == 1:\r\n text = font.render(f\"robot: {player1_score} you: {score}\", True, BLACK)\r\n text_rect = text.get_rect()\r\n text_rect.center = (width // 2, height // 2)\r\n screen.blit(text, text_rect)\r\n\r\ndef get_highscore():\r\n highscore = 0\r\n highscore_name = \"\"\r\n\r\n with open(\"rank.txt\", \"r\") as file:\r\n lines = file.readlines()\r\n for line in lines:\r\n name, score = line.strip().split(\": \")\r\n score = int(score)\r\n if score > highscore:\r\n highscore = score\r\n highscore_name = name\r\n\r\n return highscore, highscore_name\r\n\r\n\r\ndef pvp():\r\n control(2)\r\n ball()\r\n ui(2)\r\n judge()\r\n\r\n\r\ndef pve():\r\n control(1)\r\n ball()\r\n ui(1)\r\n judge()\r\n \r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\n\r\npygame.init()\r\n\r\nwidth = 1200\r\nheight = 600\r\nsize = (width, height)\r\nscreen = pygame.display.set_mode(size)\r\n\r\npygame.display.set_caption(\"Pong\")\r\n\r\ndone = False\r\n\r\nclock = pygame.time.Clock()\r\n\r\nplayer_width = 10\r\nplayer_height = 80\r\nplayer1_y = height // 2 - player_height // 2\r\nplayer2_y = height // 2 - player_height // 2\r\nplayer1_v = 0\r\nplayer2_v = 0\r\n\r\nplayer1_score = 0\r\nplayer2_score = 0\r\nscore = 0\r\n\r\ngap = 20\r\n\r\nball_x = width // 2\r\nball_y = random.randint(height // 4, (height // 4) * 3)\r\nball_r = 10\r\nball_v = 6\r\nball_vx = random.randint(48,55) / 10\r\nif random.choice([True, False]):\r\n ball_vx = -ball_vx\r\nball_vy = (ball_v ** 2 - ball_vx **2) ** 0.5\r\n\r\nfont = pygame.font.Font(\"times.ttf\", 36)\r\nmode = 0\r\nwin = pygame.mixer.Sound('win.mp3')\r\nx = 0\r\n\r\nplayer_name = input(\"What's your name?\\n\")\r\nprint(f\"Enjoy your game, {player_name}!\")\r\n\r\nwhile not done:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_0:\r\n mode = 0\r\n elif event.key == pygame.K_1:\r\n mode = 1\r\n elif event.key == pygame.K_2:\r\n mode = 2\r\n \r\n if mode == 0:\r\n screen.fill(WHITE)\r\n text = font.render(\"PRESS 1 IF SINGLE-PLAYER; PRESS 2 IF MUTI-PLAYER\", True, BLACK)\r\n text_rect = text.get_rect()\r\n text_rect.center = (width // 2, height // 2)\r\n screen.blit(text, text_rect)\r\n player1_score = 0\r\n player2_score = 0\r\n score = 0\r\n \r\n elif mode == 1:\r\n if player1_score != 5 and player2_score !=5: \r\n pve()\r\n highscore, highscore_name = get_highscore()\r\n text = font.render(f\"highest score: {highscore} player name: {highscore_name}\", True, BLACK)\r\n text_rect = text.get_rect()\r\n text_rect.center = (width // 2, height // 2 + 50)\r\n screen.blit(text, text_rect)\r\n else:\r\n pygame.time.wait(int(win.get_length() * 1000))\r\n with open(\"rank.txt\", \"a\") as file:\r\n file.write(f\"{player_name}: {score}\\n\")\r\n mode = 0\r\n\r\n elif mode == 2:\r\n if player1_score != 5 and player2_score !=5:\r\n pvp()\r\n else:\r\n pygame.time.wait(int(win.get_length() * 1000))\r\n mode = 0\r\n\r\n pygame.display.flip()\r\n\r\n clock.tick(120)\r\n\r\npygame.quit()","repo_name":"LWZsama/pygame","sub_path":"pong/pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":7584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"37445934706","text":"def build_graph(nodes, clusters):\n\t'''\n\tinput: number of nodes, number of clusters\n\n\toutput: complete bipartite graph with vertices labeled 0,..,nodes-1 for \n\telements on the left and nodes,...,clusters-1 for elements on the right\n\n\tlogic: represent graph as a dictionary, each left node connects to every \n\tright node and vice versa. Just fill out dictionary using for-loops\n\t'''\n\tgraph = {}\n\tfor i in range(nodes):\n\t\tgraph[i] = [nodes + j for j in range(clusters)]\n\tfor j in range(clusters):\n\t\tgraph[nodes + j] = [i for i in range(nodes)]\n\treturn graph\n\n# initialize visitedList solely to test depthFirst on its own\nvisitedList = []\ndef depthFirst(graph, currentVertex, visited):\n '''\n\tinput: a graph, a starting vertex, and a list of nodes already visited.\n\tTypical input should be graph, the starting vertex, and [].\n\t\n\toutput: all cycle-free paths in the graph that start with \n\tvisited + currentVertex\n\t\n\tlogic: use recursion to find all paths. Start at currentVertex and traverse\n\tto next vertex if not already visited. When path cant continue, just add to\n\tvisitedList\n\t'''\n visited.append(currentVertex)\n for vertex in graph[currentVertex]:\n if vertex not in visited:\n depthFirst(graph, vertex, visited.copy())\n visitedList.append(visited)\n return visitedList\ndef cycles_graph(graph, nodes, clusters, B):\n\t'''\n\tInput: a graph, and the number of nodes to walk through\n\tOutput: all simple cycles paths in the graph \n\tlogic: use the depth first to find all paths starting at each vertex.\n\tUse filter to remove walks of length 3 or less since a simple cycle will need at least 4 vertices at it's smallest.\n\tRemove all nodes that don't end at a cluster. We end on a cluster when the length of the list of vertices is an even number\n\tsince this corresponds to an odd number of edges. \n\tLastly, add in the start node to the end of each list to represent the cluster node returning to the start node of the cycle. \n\t'''\n\tpaths = []\n\tvisitedList = []\n \n\tfor i in range(clusters):\n\t\tsomePaths = depthFirst(graph, i, [])\n\t\tpaths+=somePaths \n \n\tmulti_vertex_paths = list(filter(lambda c: len(c) >= 4, paths))\n\teven_length_paths = list(filter(lambda c: len(c) % 2 == 0 ,multi_vertex_paths))\n\tremoved_dups = [] \n\t[removed_dups.append(x) for x in even_length_paths if x not in removed_dups]\n \n\tfor path in removed_dups:\n\t\tpath.append(path[0]) \n \n\treturn removed_dups\n\n\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"wgrewe/D2P-Optimization-Fall-2021","sub_path":"Circuit_Functions/cycles_graph.py","file_name":"cycles_graph.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29123720309","text":"# Streamlit for PRC Viz\nimport streamlit as st\nimport os\nimport sys\n\nmodule_path = os.path.abspath('../../')\nif module_path not in sys.path:\n sys.path.append(module_path)\nfrom sparclur.prc._viz import PRCViz\nfrom sparclur.parsers.present_parsers import get_sparclur_renderers\n\nRENDERERS = [r.get_name() for r in get_sparclur_renderers()]\n\n# @st.cache\n# def get_viz(renderers):\n# filename = [renderer for renderer in renderers.values()][0].doc\n# return PRCViz(doc=filename, renderers=[renderer for renderer in renderers.values()])\n\ndef app(parsers, **kwargs):\n st.subheader(\"PDF Render Comparator\")\n\n renderers = {p_name: parser for (p_name, parser) in parsers.items() if p_name in RENDERERS}\n\n if len(renderers) < 2:\n st.write(\"Please select at least 2 of [%s]\" % ', '.join(RENDERERS))\n else:\n filename = [renderer for renderer in renderers.values()][0].doc\n viz = PRCViz(doc=filename, renderers=[renderer for renderer in renderers.values()])\n # viz = get_viz(renderers)\n\n fig = viz.plot_sims()\n st.pyplot(fig)\n select_page = st.selectbox('Page', options=list(range(viz.get_observed_pages())))\n display_fig = viz.display(page=select_page)\n st.pyplot(display_fig)\n","repo_name":"levelupresearch/sparclur","sub_path":"sparclur/lit_sparclur/_lit_prc.py","file_name":"_lit_prc.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"18941327787","text":"import smtplib\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr\nimport time\nimport urllib.request\nimport json\nnowTime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\nmy_sender = '2876363140@qq.com' # 发件人邮箱账号\nmy_pass = 'jzalaltaeyuxdhcf' #发件人邮箱密码(当时申请smtp给的口令)\nallError = \"###\"\n#网络连接测试---用来检测网站是否出现意外并停止运行\ndef webTest():\n url = \"http://119.45.211.210/\"\n try:\n status = urllib.request.urlopen(url).code\n print(status)\n except Exception as e:\n allError = allError + \"###webTestError:\" + e\n\n#发送邮件---发用邮件提醒管理员运行状况\ndef mail():\n res = str(nowTime)+\"---send ok\"\n try:\n emailListFile = open(\"emailList.json\", \"r\")\n adminMail = json.loads(emailListFile.read())\n my_userList = adminMail['adminMail'] # 收件人邮箱账号\n emailListFile.close()\n for i in my_userList:\n try:\n msg = MIMEText('填写邮件内容', 'plain', 'utf-8')\n msg['From'] = formataddr([\"发件人昵称\", my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号\n # 括号里的对应收件人邮箱昵称、收件人邮箱账号\n msg['To'] = formataddr([\"收件人昵称\", i])\n msg['Subject'] = \"邮件主题-测试\" # 邮件的主题,也可以说是标题\n\n server = smtplib.SMTP_SSL(\"smtp.qq.com\", 465) # 发件人邮箱中的SMTP服务器,端口是465\n server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码\n # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件\n server.sendmail(my_sender, [i, ], msg.as_string())\n server.quit() # 关闭连接\n except Exception as e: # 如果 try 中的语句没有执行,则会执行下面的 ret=False\n allError = allError + \"###sendmailError1(send):\" + e\n except Exception as e: # 如果 try 中的语句没有执行,则会执行下面的 ret=False\n allError = allError + \"###sendmailError2(other):\" + e\n return res\n\n\nmailres = mail()\nprint(mailres)\nprint(allError)\n\n\n\n\n\n\n","repo_name":"RelaxJH-DouZhiR/MissChild","sub_path":"steamsearch/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20295629815","text":"from flask import current_app, render_template, Blueprint\nfrom flask_security import login_required\n\nblueprint = Blueprint('users', __name__, url_prefix='/users')\n\n\n@blueprint.route('/profile')\n@login_required\ndef profile():\n \"\"\"return user profle.\"\"\"\n current_app.logger.debug(u'Get profile user.')\n return render_template('users/profile.html')\n","repo_name":"murilobsd/zeus","sub_path":"zeusproject/templates/app/users/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"28330990850","text":"import os, json\nimport pandas as pd\nfrom flask import Flask, flash, request, redirect, url_for, jsonify\nimport pypyodbc\nimport datetime\n\n\"\"\" get all users \"\"\"\ndef getAllUsers(conn):\n #returns pd dataframe\n sql_query = pd.read_sql_query('SELECT * from tbl_user', conn)\n \"\"\"\n split : columns, data objects with each being array\n records : standard json format\n \"\"\"\n return sql_query\n\ndef getUserByPhone(conn, json):\n #print(json)\n #returns pd dataframe\n queryString = \"\"\"\n Select [id],[username],[userDescription],[gender],[sexuality],\n [age],[email],[phone_number],[location_city],[location_x],[location_y] ,[date_of_birth] \n from tbl_user where phone_number = '{phone_number}' and password = '{password}'\n \"\"\".format(phone_number=json['phone_number'], password=json['password'])\n sql_query = pd.read_sql_query(queryString, conn)\n return sql_query\n\ndef getUserByUserId(conn, json):\n #print(json)\n #returns pd dataframe\n queryString = \"\"\"\n Select [id],[username],[userDescription],[gender],[sexuality],\n [age],[email],[phone_number],[location_city],[location_x],[location_y] ,[date_of_birth] \n from tbl_user where id='{id}'\n \"\"\".format( id=json['id'] )\n sql_query = pd.read_sql_query(queryString, conn)\n return sql_query\n\ndef getAllUsersBySearchTerm(conn, json):\n _searchTerm=json['id']\n #print(json)\n #returns pd dataframe\n queryString = \"\"\"\n Select [id],[username],[userDescription],[gender],[sexuality],\n [age],[email],[phone_number],[location_city],[location_x],[location_y] ,[date_of_birth] \n from tbl_user \n where phone_number like '%{searchTerm}%' \n or username like '%{searchTerm}%'\n or userDescription like '%{searchTerm}%'\n \"\"\".format( searchTerm=_searchTerm )\n sql_query = pd.read_sql_query(queryString, conn)\n return sql_query\n\ndef checkUnique(conn, json):\n if( not 'userName' in json):\n _userName=\"\"\n else:\n _userName=json['userName']\n\n queryString = \"\"\"Select top 1 [id],[username],[userDescription],[gender],[sexuality] \n ,[age],[email],[phone_number],[location_city],[location_x],[location_y] ,[date_of_birth] \n from tbl_user where tbl_user.phone_number = '{phone_number}' or tbl_user.userName = '{userName}'\n \"\"\".format(phone_number=json['phone_number'], userName=_userName)\n sql_query = pd.read_sql_query(queryString, conn)\n return sql_query\n\n#insertUser\ndef insertUser(cursor, conn, json):\n try:\n queryString = \"\"\"insert into tbl_user(\n username, userDescription,gender,sexuality,age,email,phone_number,\n location_city,location_x,location_y, password) output INSERTED.ID\n values(\n '{username}', '{userDescription}', '{gender}', '{sexuality}', {age}, '{email}', '{phone_number}', \n '{location_city}', {location_x}, {location_y}, '{password}')\n \"\"\".format(\n username=json['userName'], userDescription=json['userDescription'], \n gender=json['gender'], sexuality=json['sexuality'], \n age=json['age'], email='__@__', \n phone_number=json['phone_number'], location_city='__@__', \n location_x=json['location_x'], location_y=json['location_y'], \n #date_of_birth=json['date_of_birth'], , '{date_of_birth}' ,date_of_birth\n password=json['password']\n )\n cursor.execute(queryString)\n insertId = cursor.fetchone()[0]\n conn.commit() \n return {'id':insertId, 'message':'success'}\n except pypyodbc.Error as e:\n print(\"An error has occured\")\n return {'id':'NA', 'message':'FAIL', 'Query':queryString, 'error':str(e)}\n\n#updateUser\ndef updateUserProfile(cursor, conn, json):\n \n queryString = \"\"\"update tbl_user set \n username = '{username}',\n age = {age},\n phone_number= '{phone_number}',\n password= '{password}'\n WHERE id= '{id}'\n \"\"\".format(\n username= json['username'], \n age= json['age'],\n phone_number=json['phone_number'], \n password= json['password'],\n id= json['id']\n )\n try:\n print(queryString)\n cursor.execute(queryString)\n conn.commit() \n return {'id':json['id'], 'message':'success'}\n except pypyodbc.ProgrammingError:\n print(\"An error has occured\")\n return {\"message\":\"False\"}\n\n#updateUserLocation\ndef updateUserLocation(cursor, conn, json):\n queryString = \"\"\"update tbl_user set \n tbl_user.location_x = {locationX}, \n tbl_user.location_y = {locationy} \n WHERE \n tbl_user.id= {id}\n \"\"\".format(\n locationX= json['locationx'], \n locationy= json['locationy'],\n id= json['id']\n )\n try:\n \n cursor.execute(queryString)\n conn.commit() \n return {'id':json['id'], 'message':'success'}\n except:\n print(\"An error has occured\")\n return {\"message\":\"FAIL\", 'query':queryString}\n\"\"\"================================================\nConversation, chat history section\n================================================\"\"\"\ndef getConversationList(cursor, conn, json):\n queryString = \"\"\" \n select u.id, u.userName, conv.msgCount, conv.converserId\n from(\n select count(coreConvers.conv_id) as msgCount, coreConvers.converserId\n from(\n SELECT [conv_id]\n ,(\n case when [fromUserId] = {userId}\n then [toUserId] \n else [fromUserId]\n end\n ) as converserId\n FROM [db_pop].[dbo].[tbl_chat_history]\n where [fromUserId] = {userId}\n or [toUserId]={userId}\n ) coreConvers\t\t\t\t\n group by coreConvers.converserId\n ) as conv\n left join tbl_user as u on u.id = conv.converserId \n\n \"\"\".format(\n userId= json['userId']\n )\n sql_query = pd.read_sql_query(queryString, conn)\n return sql_query\n\ndef getConversation(cursor, conn, json):\n queryString = \"\"\"\n SELECT conv_id,\n fromUserId,\n toUserId,\n message,\n time_stamp,\n CONVERT(VARCHAR(8), time_stamp, 108) as 'senttime'\n FROM [db_pop].[dbo].[tbl_chat_history]\n where [fromUserId] = {userId} and [toUserId]={fromUserId}\n \tor\t[fromUserId] = {fromUserId} and [toUserId]= {userId}\n \"\"\".format(\n fromUserId= json['fromUserId'],\n userId= json['userId'],\n )\n sql_query = pd.read_sql_query(queryString, conn)\n return sql_query\n\ndef getConversationLatest(cursor, conn, json):\n conversationid=''\n if('conv_id' in json ):\n conversationid = json['conv_id']\n else:\n conversationid=0\n queryString = \"\"\"\n SELECT conv_id,\n fromUserId,\n toUserId,\n message,\n time_stamp,\n CONVERT(VARCHAR(8), time_stamp, 108) as 'senttime'\n FROM [db_pop].[dbo].[tbl_chat_history]\n where ([fromUserId] = {userId} and [toUserId]={fromUserId}\n \tor\t[fromUserId] = {fromUserId} and [toUserId]= {userId})\n AND conv_id>{conv_Id}\n \"\"\".format(\n fromUserId= json['fromUserId'],\n userId= json['userId'],\n conv_Id = conversationid \n )\n sql_query = pd.read_sql_query(queryString, conn)\n return sql_query\n\ndef insertConversation(cursor, conn, json):\n queryString = \"\"\"\n insert into [db_pop].[dbo].[tbl_chat_history]\n ([toUserId],[fromUserId],[message])\n output INSERTED.conv_id\n values ({toUserId},{fromUserId},'{message}')\n \"\"\".format(\n fromUserId= json['fromUserId'], \n toUserId= json['toUserId'],\n message= json['message']\n )\n try: \n cursor.execute(queryString)\n insertId = cursor.fetchone()[0]\n print('INSERTID', insertId)\n conn.commit() \n return {'id':insertId, 'message':'success'}\n #return getConversation(cursor, conn, {'fromUserId': json['fromUserId'], 'userId' : json['toUserId']})\n except:\n print(\"An error has occured\")\n return {\"message\":\"FAIL\", 'query':queryString}\n","repo_name":"TheSagarPatil/POP_API_PY","sub_path":"controller_user.py","file_name":"controller_user.py","file_ext":"py","file_size_in_byte":8594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39293311129","text":"import argparse\nfrom app import app\nfrom config import config\n\n\ndef particularize_argument_parser():\n \"\"\"\n Provide all needed arguments for an argument parser\n :return: an argument parser with all needed arguments\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--config_section',\n type=str,\n dest='config_section',\n required=False,\n help='Config section to use. If none is provide, the default one will be used.',\n )\n return parser\n\n\ndef main():\n\n args = particularize_argument_parser().parse_args()\n\n if args.config_section:\n conf = config.Config('config.yaml', section=args.config_section)\n else:\n conf = config.Config('config.yaml')\n\n app.run(conf.WEBSERVER['HOST'], conf.WEBSERVER['PORT'], conf.WEBSERVER['DEBUG'])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"oannam/reddit_parser","sub_path":"web_api/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"35675150669","text":"from discord.ext import commands\nfrom discord_slash import SlashContext\nfrom discord_slash.cog_ext import cog_slash as slash\n\n\nclass ContributeCommand(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @slash(name='contribute',\n description='Display information about helping the development of the bot')\n async def contribute(self, ctx: SlashContext):\n await ctx.send('The bot is open-source. You can find the source code '\n '_[on its GitHub repository](https://github.com/martinmladenov/RankingBot/)_.\\n'\n 'Feel free to contribute by creating an issue or submitting a pull request!')\n\n\ndef setup(bot):\n bot.add_cog(ContributeCommand(bot))\n","repo_name":"martinmladenov/RankingBot","sub_path":"commands/contribute_command.py","file_name":"contribute_command.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"85"} +{"seq_id":"5311703208","text":"from warpz.kernel.universe import *\n\nimport numpy\n\nEPSILON = 10E-10\n\n\nclass Reservoir(Universe):\n def __init__(self, **kwargs):\n # initialize base signal\n super().__init__(**kwargs)\n\n def __call__(self, signals):\n # random flip\n for each in self.get_children():\n if isinstance(each, Matrix):\n yield Flip(target=each)\n\n\nclass Matrix(Agent):\n def __init__(self, size, j=0.30, **kwargs):\n # grid size\n self.l = size\n\n # interaction (units of kT)\n self.j = j\n\n # initialize base agent\n super().__init__(**kwargs)\n\n # spin sites\n self.material = numpy.random.randint(2, size=(self.l, self.l))\n self.material[self.material == 0] = -1\n\n # energy of the matrix\n self.energy = self.get_energy() - self.get_min_energy()\n\n def get_energy_for_site(self, i, j, spin):\n energy = -self.j * spin * (self.material[i, (j - 1) % self.l] +\n self.material[i, (j + 1) % self.l] +\n self.material[(i - 1) % self.l, j] +\n self.material[(i + 1) % self.l, j])\n\n return energy\n\n def get_energy(self):\n right_shift, up_shift = numpy.zeros((self.l, self.l), dtype=int), numpy.zeros((self.l, self.l), dtype=int)\n\n right_shift[:, 0] = self.material[:, self.l - 1]\n right_shift[:, 1:self.l] = self.material[:, 0:(self.l - 1)]\n\n up_shift[self.l - 1, :] = self.material[0, :]\n up_shift[0:(self.l - 1), :] = self.material[1:self.l, :]\n\n return -self.j * (sum(sum(numpy.multiply(right_shift, self.material))) +\n sum(sum(numpy.multiply(up_shift, self.material))))\n\n def get_min_energy(self):\n return -self.j * 2 * (self.l * self.l)\n\n def get_energy_after_flip(self, i, j):\n return self.energy - \\\n self.get_energy_for_site(i, j, self.material[i, j]) + \\\n self.get_energy_for_site(i, j, (-1) * self.material[i, j])\n\n def get_magnetic_order(self):\n up = sum(sum((self.material * 1) == 1))\n sites = self.l * self.l\n\n return (2 * up - sites) / sites\n\n\nclass Flip(Signal):\n def __init__(self, **kwargs):\n # initialize base signal\n super().__init__(**kwargs)\n\n def __call__(self, matrix: Matrix):\n # choose some random site\n i, j = numpy.random.randint(0, matrix.l), numpy.random.randint(0, matrix.l)\n\n # get energy delta after flip\n energy_after_flip = matrix.get_energy_after_flip(i, j)\n delta_energy = energy_after_flip - matrix.energy\n\n # metropolis algorithm for state acceptance\n if delta_energy < 0 or numpy.random.random() < math.exp(-delta_energy):\n # toggle spin\n matrix.material[i, j] = (-1) * matrix.material[i, j]\n\n # update matrix energy\n matrix.energy = energy_after_flip\n\n\ndef main():\n print(\"[+] ising (with metropolis)\")\n\n # initialize matrix\n matrix = Matrix(size=50, j=1.00)\n reservoir = Reservoir()\n\n # interaction constant\n print(\"[-] interaction = \", matrix.j)\n\n # add matrix\n reservoir.add(matrix)\n\n flips, steps = 0, 5000000\n energy, magnetic_order = 0, 0\n for k in range(1, steps):\n # run system\n reservoir.run()\n\n # tally observables\n energy += matrix.energy\n magnetic_order += matrix.get_magnetic_order()\n\n if k % 10000 == 0:\n print(\"[+] step <\", k, \">\")\n print(f\"[=] magnetic order (average) : {magnetic_order / k:.2f}\")\n print(f\"[=] energy (average) : {energy / k:.2f}\")\n print(f\"[=] state magnetic order : {matrix.get_magnetic_order():.2f}\")\n print(f\"[=] state energy : {matrix.energy / k:.2e}\")\n print(f\"[=] schwifty : {reservoir.get_schwifties() / k:.2f}\")\n\n\nmain()\n","repo_name":"pellegre/warpz","sub_path":"models/boltzmann/ising_metropolis.py","file_name":"ising_metropolis.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2173909501","text":"# pip install openpyxl\nimport openpyxl as xl\nimport os, time\n\ninput_folder = os.path.join(\"input/\")\noutput_folder = os.path.join(\"output/\")\n\n\n\ndef fixTime(input_folder, output_folder, name, time_col, header_col, end_row, debug):\n \"\"\" Reads excel file and fixes the time in a column\n \"\"\"\n # Start row\n row = 5\n wb = xl.load_workbook(filename = input_folder + name, data_only=True)\n if debug: print(\"Fixing : \" + input_folder + name)\n for sheet in wb:\n while row < end_row:\n\n if len(str(sheet[header_col+str(row)].value)) == 0 or str(sheet[header_col+str(row)].value) == \"None\":\n row += 1\n continue\n else:\n if len(str(sheet[time_col+str(row)].value)) == 0 or str(sheet[time_col+str(row)].value) == \"None\":\n header = str(sheet[header_col+str(row)].value).replace(\" \", \"_\").replace(\".\", \"_\").replace(\"?\", \"_\").replace(\":\", \"_\")\n print(header)\n file = open(output_folder+header+\".srt\",\"w\")\n index = 1\n row += 2\n \n while sheet[time_col+str(row)].value != None:\n if len(str(sheet[time_col+str(row)].value).split(\" \")) > 1:\n sheet[time_col+str(row)].value = str(sheet[time_col+str(row)].value).split(\" \")[1]\n datas = str(sheet[time_col+str(row)].value).split(':')\n \n if len(datas) == 3:\n start_time = \"00:%s:%s,000\" % (datas[0].zfill(2), datas[1].zfill(2))\n if int(datas[1]) + 3 > 59:\n datas[0] = str(int(datas[0]) + 1)\n datas[1] = str((int(datas[1]) + 3) % 60)\n else:\n datas[1] = str(int(datas[1])+3)\n\n end_time = \"00:%s:%s,000\" % (datas[0].zfill(2), datas[1].zfill(2))\n file.write(str(index)+\"\\n\")\n file.write(start_time + \" --> \" + end_time +\"\\n\")\n file.write(str(sheet[header_col+str(row)].value)+\"\\n\\n\")\n index += 1\n row += 2\n file.close()\n\n \n\nif __name__ == \"__main__\":\n \"\"\" Check if file exists in input folder and does not exist in output folder,\n then converts it to with fixTime function and save it to output folder.\n \"\"\"\n # Start column\n time_col = 'B'\n # Header column\n header_col = 'C'\n \n # End row\n end_row = 1000\n\n \n if(len(os.listdir(input_folder)) > 0):\n\n inputs = os.listdir(input_folder)\n\n for i in inputs:\n\n if i.split(\".\")[-1:][0] == \"xlsx\":\n \n fixTime(input_folder, output_folder, i, time_col, header_col, end_row, True)\n\n\n","repo_name":"z00ze/fixTime","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"35788090489","text":"import gobject\nimport gtk\n\nimport ibus\n\nfrom tegakigtk.recognizer import SmartRecognizerWidget\n\nclass Engine(ibus.EngineBase):\n\n def __init__(self, bus, object_path):\n super(Engine, self).__init__(bus, object_path)\n self._window = None\n\n # See ibus.EngineBase for a list of overridable methods\n\n def enable(self):\n if not self._window:\n self._window = gtk.Window()\n self._window.set_title(\"Tegaki\")\n self._window.set_position(gtk.WIN_POS_CENTER_ALWAYS)\n self._window.set_accept_focus(False)\n rw = SmartRecognizerWidget()\n self._window.add(rw)\n\n self._window.show_all()\n\n self._window.connect(\"delete-event\", self._on_close)\n rw.connect(\"commit-string\", self._on_commit)\n\n def disable(self):\n if self._window:\n self._window.destroy()\n self._window = None\n\n def do_destroy(self):\n self.disable()\n super(ibus.EngineBase, self).do_destroy()\n\n def _on_close(self, *args):\n self.disable()\n\n def _on_commit(self, widget, string):\n self.commit_text(ibus.Text(string))\n\n","repo_name":"tegaki/tegaki","sub_path":"ibus-tegaki/engine/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":235,"dataset":"github-code","pt":"85"} +{"seq_id":"74805902678","text":"import cv2\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('source02.jpg',0)\nedges = cv2.Canny(img,50,200) # canny edge detector\n\nimg = cv2.merge((img,img,img)) # creat RGB image from grayscale\nimg2 = img.copy()\nimg2[edges == 255] = [255, 0, 0] # turn edges to red\n\nplt.subplot(121),plt.imshow(img)\nplt.title('Original Image'), plt.xticks([]), plt.yticks([])\nplt.subplot(122),plt.imshow(img2)\nplt.title('Edge Highlighted'), plt.xticks([]), plt.yticks([])\n\nplt.show()","repo_name":"jskim062/ow_project","sub_path":"edge.py","file_name":"edge.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13450916911","text":"### importing necessary libraries\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nimport glob\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom scipy.cluster.vq import vq\n\n\n### reading required train datasets\npath = \"/home/subarna/Documents/vr/MT2019514_MT2019523_MT2019079/Part2/CIFAR-10-images-master/train\"\nfilenames = glob.glob(path + \"/*\")\ndf_train = []\ndescriptor = []\n\nfor filename in filenames:\n clas_nams = glob.glob(filename + \"/*\")\n for clas_nam in clas_nams:\n try:\n imageID = filename[filename.rfind(\"/\") + 1:]\n img = cv2.imread(clas_nam)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n extractor = cv2.xfeatures2d.SIFT_create()\n keypoints, descriptors = extractor.detectAndCompute(img, None)\n descriptor.extend(descriptors)\n df_train.append((imageID,descriptors))\n except TypeError as e:\n print(e)\n\n### reading required test dataset\npath = \"/home/subarna/Documents/vr/MT2019514_MT2019523_MT2019079/Part2/CIFAR-10-images-master/test\"\nfilenames = glob.glob(path + \"/*\")\ndf_test = []\ndescriptor_test = []\nfor filename in filenames:\n clas_nams = glob.glob(filename + \"/*\")\n for clas_nam in clas_nams:\n try:\n imageID = filename[filename.rfind(\"/\") + 1:]\n img = cv2.imread(clas_nam)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n extractor = cv2.xfeatures2d.SIFT_create()\n keypoints, descriptors = extractor.detectAndCompute(img, None)\n descriptor_test.extend(descriptors)\n df_test.append((imageID,descriptors))\n except TypeError as e:\n print(e)\n\n\n\n### extracting our clusters and there centroids\nkmeans = KMeans(n_clusters = 40, random_state = 10)\nkmeans.fit(des_train)\ncluster = kmeans.cluster_centers_\n\n\n\n### Labelling class names\ndf_tr = pd.DataFrame(df_train)\ndf_te = pd.DataFrame(df_test)\nl = {'dog' : 0, 'automobile' : 1, 'bird' : 2, 'airplane' : 3, 'ship' : 4, 'truck' : 5, 'frog' : 6, 'horse' : 7, 'deer' : 8, 'cat' : 9}\ndf_tr[0] = [l[item] for item in df_tr[0]]\ndf_te[0] = [l[item] for item in df_te[0]]\n\n\n\n### getting train and test matrix using numpy\nx_test = df_train[0].to_numpy()\ny_test = df_test[0].to_numpy()\n\n\n\n### creating histogram using BoVW\ntrain_features = np.zeros((len(df_train), 40), \"float32\")\nfor i in range(0,len(df_train)):\n words, distance = vq(df_train[i][1],kmeans.cluster_centers_)\n for w in words:\n train_features[i][w] += 1\n\ntest_features = np.zeros((len(df_test), 40), \"float32\")\nfor i in range(0,len(df_test)):\n words, distance = vq(df_test[i][1],kmeans.cluster_centers_)\n for w in words:\n test_features[i][w] += 1\n\n\n\n### preproceesing train and test dataset \nfrom sklearn.preprocessing import StandardScaler\n#Perform Tf-Idf vectorization\nnbr_occurences = np.sum( (train_features > 0) * 1, axis = 0)\n# Calculating the number of occurrences\nidf = np.array(np.log((1.0*len(train_features)+1) / (1.0*nbr_occurences + 1)), 'float32')\n# Giving weight to one that occurs more frequently\n# Scaling the features\nstdSlr = StandardScaler().fit(train_features)\nim_features_train = stdSlr.transform(train_features)\n\nnbr_occurences = np.sum( (test_features > 0) * 1, axis = 0)\nidf = np.array(np.log((1.0*len(test_features)+1) / (1.0*nbr_occurences + 1)), 'float32')\nstdSlr = StandardScaler().fit(test_features)\nim_features_test = stdSlr.transform(test_features)\n\n\n### finally getting our train data and test data for our KNN model\nx_train = im_features_train\ny_train = im_features_test\n\n\n### finally training our KNN model\nmodel = KNeighborsClassifier(n_neighbors=9,n_jobs=-1)\nmodel.fit(x_train, x_test)\nacc = model.score(y_train, y_test)\nprint(\"Accuracy: {:.2f}%\".format(acc * 100))\n\n\n### VLAD extension of BoVW\nvlad_features = []\nfor i in range(len(df_train)):\n vlad_vector = np.zeros((40,128), \"float32\")\n words, distance = vq(df_train[i][1],kmeans.cluster_centers_)\n j=0\n for w in words:\n vlad_vector[w] = np.add(vlad_vector[w], np.subtract(df_train[i][1][j],kmeans.cluster_centers_[w]))\n j = j+1\n norm = np.linalg.norm(vlad_vector)\n vlad_vector= np.divide(vlad_vector,norm)\n vlad_vector= vlad_vector.flatten()\n vlad_features.append(vlad_vector)\n\nvlad_features_test=[]\nfor i in range(len(df_test)):\n vlad_vector = np.zeros((40,128), \"float32\")\n words, distance = vq(df_test[i][1],kmeans.cluster_centers_)\n j=0\n for w in words:\n vlad_vector[w] = np.add(vlad_vector[w], np.subtract(df_test[i][1][j],kmeans.cluster_centers_[w]))\n j = j+1\n norm = np.linalg.norm(vlad_vector)\n vlad_vector= np.divide(vlad_vector,norm)\n vlad_vector= vlad_vector.flatten()\n vlad_features_test.append(vlad_vector)\n\n\n\n### model training\nmodel = KNeighborsClassifier(n_neighbors=9,n_jobs=-1)\nmodel.fit(vlad_features, x_test)\nacc = model.score(vlad_features_test, y_test)\nprint(\"Accuracy: {:.2f}%\".format(acc * 100))\n","repo_name":"Subarna-kanti/Cifar-10-Image-Classification","sub_path":"BoW vs VLAD/Cifar10.py","file_name":"Cifar10.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"33625814524","text":"import pyupbit\nimport numpy as np\nimport boto3\nimport slack_sdk\n\n'''\ndef get_ror(k):\n df = pyupbit.get_ohlcv(\"KRW-ETH\", count=14)\n df['range'] = (df['high'] - df['low']) * k\n df['target'] = df['open'] + df['range'].shift(1)\n\n df['ror'] = np.where(df['high'] > df['target'],\n df['close'] / df['target'],\n 1)\n\n ror = df['ror'].cumprod()[-2]\n return ror'''\n \ndef get_ror(k):\n try:\n df = pyupbit.get_ohlcv(\"KRW-ETH\", count=14)\n #print(df)\n except Exception as e:\n print(\"Exception1 : \", e)\n \n try:\n df['range'] = (df['high'] - df['low']) * k\n #print(df)\n except Exception as e:\n print(\"Exception2 : \", e)\n \n try:\n df['target'] = df['open'] + df['range'].shift(1)\n #print(df)\n except Exception as e:\n print(\"Exception3 : \", e)\n try:\n df['ror'] = np.where(df['high'] > df['target'],\n df['close'] / df['target'],\n 1)\n #print(df)\n except Exception as e:\n print(\"Exception4 : \", e)\n \n ror = df['ror'].cumprod().iloc[-2]\n return ror\n\n\n\ndef update_dynamodb_table(bestk):\n print(\"start function : updating dynamoDB talbe\")\n dynamodb = boto3.client('dynamodb')\n \n # define the table name and the key of the item to be updated\n table_name = 'Table-ForEthauto-PROD-ethauto'\n item_key = {'env': {'S': 'PROD'}}\n \n # define the attribute to be updated and its new value\n attribute_name = 'k-value'\n new_value = bestk\n \n # update the item with the new attribute value\n try:\n response = dynamodb.update_item(\n TableName=table_name,\n Key=item_key,\n UpdateExpression='SET #attr = :val',\n ExpressionAttributeNames={'#attr': attribute_name},\n ExpressionAttributeValues={':val': {'N': str(new_value)}}\n )\n print(\"success : updating dynamoDB talbe\")\n except Exception as e:\n print(\"Exception : \", e)\n\n return response\n\ndef get_parameter_fromSSM() :\n print(\"start function : get_parameter_fromSSM\")\n ssm = boto3.client('ssm')\n\n parameters=['/ethauto/slack-token']\n ssm_para=list()\n\n for i in parameters:\n response = ssm.get_parameter(\n Name=i,\n WithDecryption=True\n )\n ssm_para.append(response['Parameter']['Value'])\n \n return ssm_para[0]\n\n\ndef handler(event, context):\n slack_token=get_parameter_fromSSM()\n client=slack_sdk.WebClient(token=slack_token)\n \n try:\n dict={}\n try:\n for k in np.arange(0.05, 1.0, 0.05):\n ror = get_ror(k)\n print(\"%.2f %f\" % (k, ror))\n if ror<1 :\n k=k*(-1)\n dict[k]=ror\n except :\n pass\n bestk=max(dict, key=dict.get)\n bestk=round(bestk, 2)\n \n \n result=update_dynamodb_table(bestk)\n\n client.chat_postMessage(channel='#ethauto-step',\n text='Lambda-Bestk: k-value: '+str(bestk))\n except Exception as e:\n client.chat_postMessage(channel='#ethauto-step',\n text='Lambda-Bestk: Exception : '+str(e))\n\n return result","repo_name":"cyaninn-entj/github-pyupbit-autotrade-with-aws-v2","sub_path":"LambdaFunction-BestK/lambda-bestK/lambda/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"632601367","text":"from pprint import pprint\n# import numpy as np\nimport ride\n\n\ndef read_task(file):\n data = dict()\n with open(file, 'r') as f:\n line = f.readline()\n split_line = line.split(' ')\n data['rows'] = int(split_line[0])\n data['columns'] = int(split_line[1])\n data['vehicles'] = int(split_line[2])\n data['rides'] = int(split_line[3])\n data['bonus'] = int(split_line[4])\n data['steps'] = int(split_line[5])\n rides = list()\n counter = 0\n for line in f:\n spl = line.split(' ')\n\n tmp_ride = ride.Ride(int(spl[0]), int(spl[1]), int(spl[2]), int(spl[3]), int(spl[4]), int(spl[5]), counter)\n rides.append(tmp_ride)\n counter += 1\n data['rides_list'] = rides\n return data\n\ndef generate_outputFiles(carList):\n file = open(\"Output/d_metropolis.out\",\"w\")\n for car in carList:\n carDetails = str(len(car.assigned_rides))\n\n for ride in car.assigned_rides:\n carDetails = carDetails + \" \"+ str(ride)\n file.write(str(carDetails) + \"\\n\")\n file.close()\n\n\n# print(read_task(\"Inputs/a_example.in\"))\n","repo_name":"gallifrei-hashcodle/pizzatask","sub_path":"in_out.py","file_name":"in_out.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"74813856276","text":"import os\nimport sys\nimport setuptools\nfrom setuptools.command.install import install\n\nCURRENT_DIR = os.getcwd()\nREQUIREMENTS = 'requirements.txt'\nrequires = [line.strip('\\n') for line in open(REQUIREMENTS).readlines()]\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nVERSION = \"1.0.1\"\n\n\nsetuptools.setup(\n name=\"Adversarials\",\n version=VERSION,\n author='Domnan Diretnan, Victor Afolabi',\n author_email=\"diretnandomnan@gmail.com, javafolabi@gmail.com\",\n description=\"easy wrapper for initializing several GAN networks in keras\",\n url=\"https://github.com/deven96/Simple_GAN\",\n packages=setuptools.find_packages(),\n install_requires=requires,\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n license=\"MIT\",\n keywords='keras GAN GANs networks adversarial',\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ),\n package_data={\n '': ['*.*'],\n },\n include_package_data=True,\n)\n","repo_name":"deven96/Simple_GAN","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"40070287869","text":"import copy\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport pytest\n\nfrom deepforest._binner import Binner, _find_binning_thresholds_per_feature\n\n\nkwargs = {\n \"n_bins\": 255,\n \"bin_subsample\": 2e5,\n \"bin_type\": \"percentile\",\n \"random_state\": 0,\n}\n\n\ndef test_find_binning_thresholds_regular_data():\n data = np.linspace(0, 10, 1001)\n\n # Percentile\n bin_thresholds = _find_binning_thresholds_per_feature(data, n_bins=10)\n assert_allclose(bin_thresholds, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n bin_thresholds = _find_binning_thresholds_per_feature(data, n_bins=5)\n assert_allclose(bin_thresholds, [2, 4, 6, 8])\n\n # Interval\n bin_thresholds = _find_binning_thresholds_per_feature(\n data, n_bins=10, bin_type=\"interval\"\n )\n assert_allclose(bin_thresholds, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n bin_thresholds = _find_binning_thresholds_per_feature(\n data, n_bins=5, bin_type=\"interval\"\n )\n assert_allclose(bin_thresholds, [2, 4, 6, 8])\n\n\ndef test_find_binning_thresholds_invalid_binner_type():\n data = np.linspace(0, 10, 1001)\n\n err_msg = \"Unknown binning type: unknown.\"\n with pytest.raises(ValueError, match=err_msg):\n _find_binning_thresholds_per_feature(\n data, n_bins=10, bin_type=\"unknown\"\n )\n\n\ndef test_find_binning_thresholds_invalid_data_shape():\n data = np.zeros((10, 2))\n\n with pytest.raises(RuntimeError) as execinfo:\n _find_binning_thresholds_per_feature(data, n_bins=10)\n assert \"Per-feature data should be of the shape\" in str(execinfo.value)\n\n\n@pytest.mark.parametrize(\n \"param\",\n [\n (0, {\"n_bins\": 1}),\n (1, {\"bin_subsample\": 0}),\n (2, {\"bin_type\": \"unknown\"}),\n ],\n)\ndef test_binner_invalid_params(param):\n data = np.linspace(0, 10, 1001)\n case_kwargs = copy.deepcopy(kwargs)\n case_kwargs.update(param[1])\n\n binner = Binner(**case_kwargs)\n\n with pytest.raises(ValueError) as excinfo:\n binner.fit(data)\n\n if param[0] == 0:\n assert \"should be in the range [2, 255]\" in str(excinfo.value)\n elif param[0] == 1:\n assert \"samples used to construct the Binner\" in str(excinfo.value)\n elif param[0] == 2:\n assert \"The type of binner should be one of\" in str(excinfo.value)\n\n\ndef test_binner_transform_before_fitting():\n data = np.linspace(0, 10, 1001)\n binner = Binner(**kwargs)\n\n err_msg = \"The binner has not been fitted yet when calling `transform`.\"\n with pytest.raises(RuntimeError, match=err_msg):\n binner.transform(data)\n","repo_name":"LAMDA-NJU/Deep-Forest","sub_path":"tests/test_binner.py","file_name":"test_binner.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":859,"dataset":"github-code","pt":"85"} +{"seq_id":"12158778102","text":"from turtle import Turtle, Screen\n\ntim = Turtle()\n\n# timmy_the_turtle.shapesize(stretch_len = 3, stretch_wid=2, outline = 2)\n# timmy_the_turtle.forward(200)\n# timmy_the_turtle.right(90)\n# timmy_the_turtle.forward(200)\n\n\n# for i in range(1,3):\n# tim.forward(200)\n# tim.right(360/3)\n# for i in range(1,5):\n# tim.forward(200)\n# tim.right(360/4)\n# for i in range(1,6):\n# tim.forward(200)\n# tim.right(360/5)\n# for i in range(1,7):\n# tim.forward(200)\n# tim.right(360/6)\n# for i in range(1,8):\n# tim.forward(200)\n# tim.right(360/7)\n# for i in range(1,9):\n# tim.forward(200)\n# tim.right(360/8)\n# for i in range(1,10):\n# tim.forward(200)\n# tim.right(360/9)\nstep = 3\nang = 2\n\n\ncolor = ['red','blue','yellow','brown','green','pink','blue','yellow','brown','green','pink']\n\n\n\nfor el in range(10):\n step += 1\n ang += 1\n for i in range(1, step):\n tim.forward(100)\n tim.right(360 / ang)\n tim.color(f'{color[i - 1]}')\n\n\nscreen = Screen()\nscreen.exitonclick()\n","repo_name":"vya4eslavtka4enko/_P_TURTLE_DRAW_","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31181414210","text":"# Third party\nfrom rest_framework.generics import get_object_or_404\n\n# Local\nfrom .models import Task\n\n\nclass TaskMixin:\n def dispatch(self, request, *args, **kwargs):\n task_id = kwargs.pop('task_id', None)\n self.task = get_object_or_404(Task, id=task_id)\n return super().dispatch(request, *args, **kwargs)\n","repo_name":"garciamendes/todo_tw_permissions","sub_path":"todo/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9618280065","text":"from __future__ import print_function\nimport subprocess as sp\n\n\ndef convert_tex_to_pdf(in_path, out_directory=\".\"):\n # type: (str, str) -> str\n try:\n sp.check_call([\"pdflatex\", \"-interaction=batchmode\", \"-output-directory\", out_directory, in_path])\n return True\n except sp.CalledProcessError as error:\n print(error.output)\n return False\n except OSError as error:\n print(error)\n print(\"This error error is most likely due to the fact that pdflatex is not installed.\\n\"\n \"Use the following commands to install it:\\n\"\n \" Ubuntu: sudo apt-get install texlive-latex-base texlive-latex-extra\\n\"\n \" OSX: brew cask install mactex (Warning: the space needed is >2GB)\")\n\n\nif __name__ == '__main__':\n convert_tex_to_pdf(\"../latex/equations.tex\", \"../latex\")\n","repo_name":"sylvaus/flasktest","sub_path":"python_utils/textopdf.py","file_name":"textopdf.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17652575694","text":"import os\nfrom os import listdir\nfrom os.path import isfile, join\n\nto_delete = ['.exe', '.bat']\nto_move = ['.zip']\n\ndef extensionIn(file_name, extension_list):\n\n\tfor extension in extension_list:\n\t\tif extension in file_name:\n\t\t\treturn True\n\n\treturn False\n\ndef main():\n\n\tdir = os.path.dirname(os.path.realpath(__file__))\n\tfiles = [f for f in listdir(dir) if isfile(join(dir, f))]\n\n\tif not os.path.isdir(dir + '/zip'):\n\t\tos.makedirs(dir + '/zip')\n\n\tfor file_name in files:\n\t\tif extensionIn(file_name, to_delete):\n\t\t\tos.remove(file_name)\n\t\t\tprint('deleting ' + file_name + '...')\n\t\telif shouldMove(file_name, to_move):\n\t\t\tos.rename(file_name, dir + '/zip/' + file_name)\n\t\t\tprint('moving ' + file_name + '...')\n\n\tprint('done!')\n\nif __name__ == '__main__':\n\tmain()","repo_name":"nicolasshak/downloads-cleaner","sub_path":"!cleaner.py","file_name":"!cleaner.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10222394883","text":"\n\"\"\"Need to make function to track mouse and return hex location and node location\"\"\"\n\n\nimport math\nfrom graphics import *\nimport time\nfrom random import seed\nfrom random import random\nfrom time import clock\n\nwinX=800\nwinY=800\nwin = GraphWin('Game Board', winX, winY)\n\ndef drwNodes(nodeDict, window):\n for count, node in enumerate(nodeDict):\n point=nodeDict[count+1].nodeCoordinate\n text=str(nodeDict[count+1].nodeID)\n\n writing=Text(Point(point[0],point[1]), text)\n writing.setSize(15)\n writing.setTextColor(\"black\")\n\n writing.draw(window)\n\ndef drwHex (points, hexID, centerPoint, tileType, pip,window):\n \n writing=Text(Point(centerPoint[0],centerPoint[1]), hexID+\" \"+str(pip))\n writing.setSize(15)\n writing.setTextColor(\"white\")\n\n p=[Point(i,j) for i,j in points]\n hexa=Polygon(p)\n\n if tileType=='brick':\n hexa.setFill('red')\n elif tileType=='sheep':\n hexa.setFill('green')\n elif tileType=='wheat':\n hexa.setFill('tan')\n elif tileType=='stone':\n hexa.setFill('gray')\n elif tileType=='wood':\n hexa.setFill('brown')\n elif tileType=='dessert':\n hexa.setFill('black')\n else :\n pass\n\n hexa.draw(window)\n writing.draw(window)\n\n\n \nclass node(object):\n nodePositions=[[],[]] ;\"[[nodeID1, nodeID2, etc],[coordinate1, coordinate2, etc]]\"\n nodeAmmount=0\n\n def __init__(self, hexAdjoining, nodeCoordinate):\n self.dupicate=False\n self.nodeCoordinate=nodeCoordinate\n self.nodeID=node.nodeAmmount+1\n self.hexesAdjoining=[hexAdjoining]\n \n \"print( self.nodeCoordinate)\"\n\n \"\"\"Checking for duplicates\"\"\"\n if node.nodePositions[1].count(nodeCoordinate)>0: \n self.dupicate=True\n i=node.nodePositions[1].index(nodeCoordinate)\n self.nodeID2Change=node.nodePositions[0][i]\n hexagon.nodeDict[self.nodeID2Change].hexesAdjoining+=[hexAdjoining]\n self.nodeID=str(self.nodeID2Change)+\"D\" \"\"\"D for dupicate\"\"\"\n node.nodePositions[0]+=[self.nodeID]\n \"\"\"print(self.nodeID)\n print(\"\\n\")\"\"\"\n node.nodePositions[1]+=[self.nodeCoordinate]\n\n return\n\n \"If it is not a duplicate, add to list\"\n \n \n node.nodePositions[0]+=[node.nodeAmmount+1]\n node.nodePositions[1]+=[self.nodeCoordinate]\n node.nodeAmmount+=1\n\nclass edge(object):\n\n \n def __init__(self,nodeID, nodeID1,nodeID2):\n \n self.coordinates=coordinates\n self.nodeID=nodeID\n self.nodePosition=nodePosition\n self.pieceStatus=[0,0]\n\n \n \n \nclass hexagon(object):\n centerPositions=[]\n inscribedRadius=.5\n circumscribedRadius=.5/math.cos(math.radians(30))\n halfSideLength=.5*math.tan(math.radians(30))\n nodes=[]\n vertexesGroupedByHexagon=[[None],[None]]\n vertexes=[]\n scale=80\n nodeDict={}\n\n \n\n def __init__(self,hexID, centerCoordinates, tileType, pipNumber):\n self.hexID=hexID\n self.centerCoordinates=[centerCoordinates[0],centerCoordinates[1]]\n self.tileType=tileType\n self.pipNumber=pipNumber\n hexagon.centerPositions.append(self.centerCoordinates)\n \n \"\"\"nw=north west, n=north etc\"\"\"\n\n\n self.nNodeCoordinates=[self.centerCoordinates[0], self.centerCoordinates[1]+hexagon.circumscribedRadius*hexagon.scale]\n self.neNodeCoordinates=[self.centerCoordinates[0]+hexagon.inscribedRadius*hexagon.scale, self.centerCoordinates[1]+hexagon.halfSideLength*hexagon.scale]\n self.seNodeCoordinates=[self.centerCoordinates[0]+hexagon.inscribedRadius*hexagon.scale, self.centerCoordinates[1]-hexagon.halfSideLength*hexagon.scale]\n self.sNodeCoordinates=[self.centerCoordinates[0], self.centerCoordinates[1]-hexagon.circumscribedRadius*hexagon.scale]\n self.swNodeCoordinates=[self.centerCoordinates[0]-hexagon.inscribedRadius*hexagon.scale, self.centerCoordinates[1]-hexagon.halfSideLength*hexagon.scale]\n self.nwNodeCoordinates=[self.centerCoordinates[0]-hexagon.inscribedRadius*hexagon.scale, self.centerCoordinates[1]+hexagon.halfSideLength*hexagon.scale]\n \n self.instanceVertexLocations=[self.nNodeCoordinates,self.neNodeCoordinates,self.seNodeCoordinates,self.sNodeCoordinates,self.swNodeCoordinates,self.nwNodeCoordinates]\n \n drwHex(self.instanceVertexLocations, self.hexID, self.centerCoordinates,tileType,pipNumber, win)\n \n for vertex in self.instanceVertexLocations:\n hexagon.vertexesGroupedByHexagon[0].append([self.hexID])\n hexagon.vertexesGroupedByHexagon[1].append([vertex])\n hexagon.nodeDict[len(hexagon.nodeDict)+1]=node(self.hexID, vertex)\n \"\"\"delete duplicate entries\"\"\"\n if hexagon.nodeDict[len(hexagon.nodeDict)].dupicate is True:\n del hexagon.nodeDict[len(hexagon.nodeDict)]\n\n \n\n\n \n\n\ndef tileColorAndPips(ammountTiles=[3,4,4,3,4,1], pips=[2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12]):\n \n def rand(arg):\n pass\n return random() \n \n seed(clock)\n pips.sort(key=rand)\n randomizedPips=pips\n randomizedPips+=[0]\n colors=['brick','sheep', 'wheat', 'stone', 'wood','dessert']\n randomizedColors=[]\n \n for count, ammount in enumerate(ammountTiles):\n randomizedColors=randomizedColors+[colors[count]]*ammount\n\n randomizedColors.sort(key=rand)\n\n colorsAndPips=[]\n i=0\n\n for color in randomizedColors:\n \n if color is not 'dessert':\n colorsAndPips+=[[color,randomizedPips[i]]]\n i+=1\n else:\n colorsAndPips+=[[color,0]]\n \n print(colorsAndPips) \n colorsAndPips=[[i for i,j in colorsAndPips],[j for i,j in colorsAndPips]]\n\n return colorsAndPips\n\n\n\n\n\nclass board(hexagon):\n \n centerLocationDict={}\n\n lowerHexAmmount=3\n midHexAmmount=5\n \n \n\n \n rows=(midHexAmmount-lowerHexAmmount)*2+1\n height=hexagon.circumscribedRadius*hexagon.scale+hexagon.halfSideLength*hexagon.scale*rows+hexagon.circumscribedRadius*hexagon.scale\n width=midHexAmmount*hexagon.inscribedRadius*2*hexagon.scale\n\n yCenter2CenterDistance=2*hexagon.inscribedRadius*math.sin(math.radians(60))*hexagon.scale\n xCenter2CenterDistance=2*hexagon.inscribedRadius*hexagon.scale\n\n def __init__(self):\n board.xWindowSize=winX\n board.yWindowSize=winY\n board.xMiddle=board.xWindowSize//2\n board.yMiddle=board.yWindowSize//2\n\n def neighborCenter(self,startLocation, xDir,yDir):\n \"\"\"xDir 1 for the right and -1 for left, yDir 1 for up and -1 for down\"\"\"\n self.startLocation=startLocation\n self.neighborCoordinates=[0,0]\n \n self.neighborCoordinates[1]=self.startLocation[1]+board.yCenter2CenterDistance*yDir\n self.neighborCoordinates[0]=self.startLocation[0]+board.xCenter2CenterDistance*xDir-yDir*.5*board.xCenter2CenterDistance\n\n return self.neighborCoordinates\n\n\n def makeBoard(self):\n \"\"\"Find all the hexagon locations and create hexagon classes for each\"\"\"\n\n \"\"\"Check to make sure the board will fit in the window\"\"\"\n if board.height>board.yWindowSize and board.width>board.xWindowSize:\n raise ValueError(\"your board is too wide and tall\")\n\n elif board.height>board.yWindowSize:\n raise ValueError(\"your board is too tall\")\n\n elif board.width>board.xWindowSize:\n raise ValueError(\"your board is too wide\")\n\n \"\"\"Find top left hex location - it will be our starting point for finding the rest\"\"\"\n self.startingCoordinates=[board.xMiddle,board.yMiddle]\n\n self.topLeftCoordinate=[self.startingCoordinates[0]-self.lowerHexAmmount*board.scale*board.inscribedRadius,\\\n self.startingCoordinates[1]+((board.rows-1)/2)*(board.yCenter2CenterDistance/2)]\n\n \"\"\"Find all the center locations of the tiles and save them to a dictonary\"\"\"\n self.column = self.lowerHexAmmount\n self.startPoint=self.topLeftCoordinate\n self.yDir=0\n self.xDir=1\n self.hexLocations=[]\n [self.tileColorList, self.pipList]=tileColorAndPips()\n\n abc=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n for i in range(self.rows):\n \n for p in range(self.column):\n self.startPoint=self.neighborCenter(self.startPoint, self.xDir,self.yDir)\n self.hexLocations+=[self.startPoint]\n self.yDir=0\n self.xDir=1\n\n self.yDir=-1\n\n if i < self.rows//2:\n self.xDir=-self.column\n self.column=self.column+1\n \n else:\n self.column=self.column-1\n self.xDir=-self.column\n\n print(\"\\n\"*2)\n for i,j in enumerate(self.hexLocations):\n \n board.centerLocationDict[i+1]=hexagon(abc[i],j,self.tileColorList[i], self.pipList[i])\n\n drwNodes(hexagon.nodeDict,win)\n\n'''def updateBoardImage\n a=hexagon(1, [50,50])\n d=a.instanceNodePositions()\n b=a.returnNodes()\n c=a.centerCoordinates\n e=[Point(k[0],k[1]) for k in a.instanceNodePositions()]\n\n drwHex(e, \"pass\",win)\n \n\n\n time.sleep(5) \n win.close'''\n\n \nprint(\"\\n\"*12)\na=board()\na.makeBoard()\nfor i in hexagon.nodeDict:\n print(hexagon.nodeDict[i].hexesAdjoining)\n\ntime.sleep(60)\n\n \n \n \n\n\nprint(\"\\n\"*6)\n\nprint(\"\\n\")\n\n","repo_name":"jaro6946/Cataan","sub_path":"cataan.py","file_name":"cataan.py","file_ext":"py","file_size_in_byte":9587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1003638448","text":"from datetime import datetime\nfrom blockchain import blockexplorer, exchangerates\nfrom django.conf import settings\n\napi_code=settings.BTC_BLOCKCHAIN_API_CODE\n\nclass Blockchain:\n def __init__(self, address=None):\n self.address = address\n self.expiry_period = settings.BTC_PRICE_UPDATE_INTERVAL\n\n def generate_test_transaction(self, invoices):\n import time, random, binascii, os\n t = {\n 'double_spend': False,\n 'block_height': random.randint(100000, 900000),\n 'time': int(time.time()),\n 'relayed_by': '0.0.0.0',\n 'hash': binascii.hexlify(os.urandom(16)),\n 'tx_index': random.randint(100000000, 900000000),\n 'ver': 1,\n 'size': random.randint(100, 900),\n 'inputs': [\n {\n 'prev_out': {\n 'n': 0,\n 'tx_index': random.randint(100000000, 900000000),\n 'value': float(invoices[0].crypto_due),\n 'type': None,\n 'script': \"q1w2e3r4\",\n },\n 'script': \"q1w2e3r4\",\n 'sequence': 0\n }\n ],\n 'out': [\n {\n 'n': 1,\n 'tx_index': random.randint(100000000, 900000000),\n 'spent': 0,\n 'addr': self.address,\n 'value': float(invoices[0].crypto_due),\n 'script': \"abcd1234\"\n }\n ]\n }\n transaction = blockexplorer.Transaction(t)\n return self.manage_transactions(invoices, [transaction])\n\n def get_transactions(self, invoices):\n tx_filter = blockexplorer.FilterType.ConfirmedOnly\n address = blockexplorer.get_address(self.address.public, filter=tx_filter, api_code=api_code)\n return self.manage_transactions(invoices, address.transactions)\n\n def manage_transactions(self, invoices, transactions):\n for t in transactions:\n timestamp = datetime.fromtimestamp(t.time)\n import pytz\n utc = pytz.UTC\n t.datetime= utc.localize(timestamp)\n txs = []\n for invoice in invoices:\n txs += [t for t in transactions if invoice.within_time_period(t.datetime)]\n for t in txs:\n t.total_received = sum([o.value for o in t.outputs if o.address == self.address])\n return transactions\n\n def convert_price_to_crypto(self, currency, price):\n return exchangerates.to_btc(currency, price)\n","repo_name":"primal100/CryptoVPN","sub_path":"cryptovpnapp/cryptos/btc.py","file_name":"btc.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27734039329","text":"import cv2, numpy as np\r\nfrom sklearn.cluster import KMeans\r\nfrom matplotlib import pyplot as plt\r\nper=[]\r\ncol=[]\r\ndef visualize_colors(cluster, centroids):\r\n # Get the number of different clusters, create histogram, and normalize\r\n labels = np.arange(0, len(np.unique(cluster.labels_)) + 1)\r\n (hist, _) = np.histogram(cluster.labels_, bins = labels)\r\n hist = hist.astype(\"float\")\r\n hist /= hist.sum()\r\n\r\n # Create frequency rect and iterate through each cluster's color and percentage\r\n rect = np.zeros((50, 300, 3), dtype=np.uint8)\r\n colors = sorted([(percent, color) for (percent, color) in zip(hist, centroids)])\r\n start = 0\r\n for (percent, color) in colors:\r\n print(color, \"{:0.2f}%\".format(percent * 100))\r\n end = start + (percent * 300)\r\n cv2.rectangle(rect, (int(start), 0), (int(end), 50),\\\r\n color.astype(\"uint8\").tolist(), -1)\r\n start = end\r\n per.append(\"{:0.2f}\".format(percent * 100))\r\n col.append(color/255)\r\n return rect\r\n\r\n# Load image and convert to a list of pixels\r\nimage = cv2.imread(r'C:\\Users\\Dell\\Desktop\\kr.jpg')\r\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\nplt.imshow(image)\r\nplt.show()\r\nreshape = image.reshape((image.shape[0] * image.shape[1], 3))\r\n\r\n# Find and display most dominant colors\r\ncluster = KMeans(n_clusters=5).fit(reshape)\r\nvisualize = visualize_colors(cluster, cluster.cluster_centers_)\r\nplt.imshow(visualize)\r\nplt.show()\r\n# print(per)\r\n# print(col)\r\n\r\nlab=['color 1','color 2','color 3','color 4','color 5']\r\nplt.title('Top 5 most prominent colours', fontsize = 24) \r\nplt.legend(lab, loc = 'upper right') \r\n\r\n\r\n\r\nexplode = (0, 0, 0, 0, 0.1) # only \"explode\" the 2nd slice (i.e. 'Hogs')\r\nplt.pie(per,explode=explode,colors=col,labels=lab,shadow=True)\r\nplt.tight_layout() \r\nplt.show()\r\n","repo_name":"DevanshD3/opencvprojects","sub_path":"finalass1.py","file_name":"finalass1.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"22358432104","text":"import sys\n\ndef main():\n if len(sys.argv) > 1:\n filename = sys.argv[1]\n else:\n filename = 'template.t'\n\n with open('output.json') as f:\n data = f.read()\n with open(filename) as f:\n template = f.read()\n text = template.replace('{{data}}', data)\n with open('index.html','w') as f:\n f.write(text)\n\nif __name__ == '__main__':\n main()\n","repo_name":"edkins/ea-classifier","sub_path":"make_html.py","file_name":"make_html.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7758815040","text":"import gettext\n\nfrom telegram.ext import Filters\n\nt = gettext.translation(\"pdf_bot\", localedir=\"locale\", languages=[\"en\"])\n_ = t.gettext\n\nTEXT_FILTER = Filters.text & ~Filters.command\n\n# Bot constants\nCHANNEL_NAME = \"pdf2botdev\"\nSET_LANG = \"set_lang\"\n\n# PDF file validation constants\nPDF_OK = 0\nPDF_INVALID_FORMAT = 1\nPDF_TOO_LARGE = 2\n\n# PDF file constants\nWAIT_DOC_TASK = 0\nWAIT_PHOTO_TASK = 1\nWAIT_CROP_TYPE = 2\nWAIT_CROP_PERCENT = 3\nWAIT_CROP_OFFSET = 4\nWAIT_DECRYPT_PW = 5\nWAIT_ENCRYPT_PW = 6\nWAIT_FILE_NAME = 7\nWAIT_ROTATE_DEGREE = 8\nWAIT_SPLIT_RANGE = 9\nWAIT_SCALE_TYPE = 10\nWAIT_SCALE_PERCENT = 11\nWAIT_SCALE_DIMENSION = 12\nWAIT_EXTRACT_PHOTO_TYPE = 13\nWAIT_TO_PHOTO_TYPE = 14\nWAIT_TEXT_TYPE = 15\n\n# Keyboard constants\nCANCEL = _(\"Cancel\")\nDONE = _(\"Done\")\nBACK = _(\"Back\")\nBY_PERCENT = _(\"By Percentage\")\nBY_SIZE = _(\"By Margin Size\")\nPREVIEW = _(\"Preview\")\nDECRYPT = _(\"Decrypt\")\nENCRYPT = _(\"Encrypt\")\nEXTRACT_PHOTO = _(\"Extract Photos\")\nTO_PHOTO = _(\"To Photos\")\nROTATE = _(\"Rotate\")\nSCALE = _(\"Scale\")\nSPLIT = _(\"Split\")\nBEAUTIFY = _(\"Beautify\")\nTO_PDF = _(\"To PDF\")\nRENAME = _(\"Rename\")\nCROP = _(\"Crop\")\nCOMPRESSED = _(\"Compressed\")\nPHOTOS = _(\"Photos\")\nREMOVE_LAST = _(\"Remove Last File\")\nTO_DIMENSIONS = _(\"To Dimensions\")\nEXTRACT_TEXT = _(\"Extract Text\")\nTEXT_MESSAGE = _(\"Text Message\")\nTEXT_FILE = _(\"Text File\")\nOCR = \"OCR\"\nCOMPRESS = _(\"Compress\")\n\n# Rotation constants\nROTATE_90 = \"90\"\nROTATE_180 = \"180\"\nROTATE_270 = \"270\"\n\n# User data constants\nPDF_INFO = \"pdf_info\"\n\n# Payment Constants\nPAYMENT = \"payment\"\nPAYMENT_PAYLOAD = \"payment_payload\"\nCURRENCY = \"USD\"\nPAYMENT_PARA = \"payment_para\"\nTHANKS = _(\"Say Thanks 😁 ($1)\")\nCOFFEE = _(\"Coffee ☕ ($3)\")\nBEER = _(\"Beer 🍺 ($5)\")\nMEAL = _(\"Meal 🍲 ($10)\")\nCUSTOM = _(\"Say Awesome 🤩 (Custom)\")\nPAYMENT_DICT = {THANKS: 1, COFFEE: 3, BEER: 5, MEAL: 10}\nCUSTOM_MSG = _(\"Send me the amount that you'll like to support PDF Bot\")\nWAIT_PAYMENT = 0\n\n# Datastore constants\nUSER = \"User\"\nLANGUAGE = \"language\"\n\n# Language constants\nLANGUAGES = {\n \"🇬🇧 English\": \"en\",\n \"🇭🇰 廣東話\": \"zh_HK\",\n \"🇹🇼 繁體中文\": \"zh_TW\",\n \"🇨🇳 简体中文\": \"zh_CN\",\n \"🇮🇹 Italiano\": \"it_IT\",\n \"🇦🇪 ٱلْعَرَبِيَّة‎\": \"ar_SA\",\n \"🇳🇱 Nederlands\": \"nl_NL\",\n \"🇧🇷 Português do Brasil\": \"pt_BR\",\n \"🇪🇸 español\": \"es_ES\",\n \"🇹🇷 Türkçe\": \"tr_TR\",\n \"🇮🇱 עברית\": \"he_IL\",\n \"🇷🇺 русский язык\": \"ru_RU\",\n \"🇫🇷 français\": \"fr_FR\",\n \"🇱🇰 සිංහල\": \"si_LK\",\n}\n","repo_name":"kmacprt/pdfbot","sub_path":"pdf_bot/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71286007318","text":"import sysv_ipc\nimport cv2\nimport numpy as np\nimport sys\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nfrom collections import defaultdict\nfrom io import StringIO\nimport matplotlib \nfrom PIL import Image\nimport struct\n\nimage_counter = 1\n\nclass BoundingBox():\n def __init__(self, coordinate_array, prediction, score):\n self.y_min = format(coordinate_array[0], '.4f')\n self.x_min = format(coordinate_array[1], '.4f')\n self.y_max = format(coordinate_array[2], '.4f')\n self.x_max = format(coordinate_array[3], '.4f')\n self.prediction = int(prediction)\n self.score = format(score, '.4f')\n def description(self):\n return self.y_min + \":\" + self.x_min + \":\" + self.y_max + \":\" + self.x_max + \":\" + str(self.prediction) + \":\" + self.score + \"-\" \n\n# This is needed since the notebook is stored in the object_detection folder.\nsys.path.append(\"..\")\nfrom object_detection.utils import ops as utils_ops\n\nif tf.__version__ < '1.4.0':\n raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')\n\n# This is needed to display the images.\n# %matplotlib inline\n\nfrom utils import label_map_util\nfrom utils import visualization_utils as vis_util\n\n# What model to download.\nMODEL_NAME = '29_05_exported_model_v1/'\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n# List of the ngs that is used to add correct label for each box.\nPATH_TO_LABELS = os.path.join('../', 'object-detection.pbtxt')\n\nNUM_CLASSES = 1\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n# For the sake of simplicity we will use only 2 images:\n# image1.jpg\n# image2.jpg\n# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.\n# Size, in inches, of the output images.\nIMAGE_SIZE = (12, 8)\n\n# init state\nimage_shared_memory_id = 12345666\nimage_shared_memory = sysv_ipc.SharedMemory(image_shared_memory_id)\n\nimage_ready_shared_memory_id = 1234567\nimage_ready_shared_memory = sysv_ipc.SharedMemory(image_ready_shared_memory_id)\n\nbounding_boxes_ready_shared_memory_id = 12345678\nbounding_boxes_ready_shared_memory = sysv_ipc.SharedMemory(bounding_boxes_ready_shared_memory_id)\n\nbounding_boxes_shared_memory_id = 12345678910\nbounding_boxes_shared_memory = sysv_ipc.SharedMemory(bounding_boxes_shared_memory_id)\n\nbounding_boxes_string_size_shared_memory_id = 1234566677\nbounding_boxes_string_size_shared_memory = sysv_ipc.SharedMemory(bounding_boxes_string_size_shared_memory_id)\n\ndef read_image():\n # Read value from shared memory\n memory_value = image_shared_memory.read()\n # create bytesarray to hold image_data\n file_bytes = np.asarray(bytearray(memory_value), dtype=np.uint8)\n image = file_bytes.reshape((300, 300, 3))\n return image\n\ndef wait_for_image():\n # read shared memory for the value\n is_image_ready = int.from_bytes(image_ready_shared_memory.read(), byteorder=sys.byteorder)\n while is_image_ready != 1:\n is_image_ready = int.from_bytes(image_ready_shared_memory.read(), byteorder=sys.byteorder)\n return\n\ndef write_bounding_boxes_to_shared_memory(bounding_boxes):\n bounding_boxes_shared_memory.write(bounding_boxes)\n\ndef set_bounding_boxes_ready_flag(status):\n bounding_boxes_ready_shared_memory.write((status).to_bytes(4, byteorder=sys.byteorder))\n\ndef set_image_ready_flag(status):\n image_ready_shared_memory.write((status).to_bytes(4, byteorder=sys.byteorder))\n\ndef write_bounding_boxes_string_size_to_shared_memory(size):\n bounding_boxes_string_size_shared_memory.write(struct.pack('i', size))\n\ndef display_image(image):\n cv2.imshow('image', image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n return\n\ndef object_detection(image_np, detection_graph, sess):\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n # Actual detection.\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n bounding_boxes = \"\"\n for i in range(len(scores[0])):\n if scores[0][i] > 0.5:\n bounding_box = BoundingBox(boxes[0][i], classes[0][i], scores[0][i])\n bounding_boxes += bounding_box.description()\n # Visualization of the results of a detection.\n print(bounding_boxes)\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n cv2.imwrite('logImages/' + str(image_counter) + '.jpg',image_np)\n image_counter += 1\n return (image_np, bounding_boxes)\n\n# run this process indefinetly\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n while True:\n wait_for_image()\n image = read_image()\n (image_od, bounding_boxes) = object_detection(image, detection_graph, sess)\n # display_image(image_od)\n write_bounding_boxes_to_shared_memory(bounding_boxes)\n print(\"bounding box string size is: \" + str(sys.getsizeof(bounding_boxes)))\n write_bounding_boxes_string_size_to_shared_memory(sys.getsizeof(bounding_boxes))\n set_bounding_boxes_ready_flag(1)\n set_image_ready_flag(0)","repo_name":"bsjurs1/Tiny-Overseer","sub_path":"Back end/server/object_detection_engine.py","file_name":"object_detection_engine.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13707959691","text":"#!/usr/bin/env python3\nfrom unittest import TestCase, main\n\nimport numpy as np\nimport torch\n\nfrom mdn_metric.metrics import VerificationMetrics\n\n\nclass TestVerificationMetrics(TestCase):\n def test_simple(self):\n \"\"\"Test metrics in simple cases.\"\"\"\n fpr = 1 / 3\n labels = [0, 0, 1, 0, 1, 1, 0, 1, 1, 1]\n # Correct = T T T F T T F T T T.\n confidences = [0.5, 0.5, 0.5, 0.1, 0.5, 0.5, 0.9, 0.5, 0.5, 1.0]\n scores = np.arange(len(labels))\n permutation = np.arange(len(labels)) # np.random.permutation(len(labels))\n labels = np.array(labels)[permutation]\n confidences = np.array(confidences)[permutation]\n scores = scores[permutation]\n evaluator = VerificationMetrics(config={\"fpr\": fpr})\n evaluator.update(torch.from_numpy(scores), torch.from_numpy(labels), torch.from_numpy(confidences))\n pr, max_accuracy, auc, tpr, fpr, eer, confidence_auroc, confidence_aupr, confidence_aurcc = evaluator.compute()\n self.assertAlmostEqual(pr, 6 / 10)\n self.assertAlmostEqual(max_accuracy, 0.8)\n # No easy way to compute AUC.\n self.assertAlmostEqual(fpr, 1 / 4)\n self.assertAlmostEqual(tpr, 5 / 6)\n self.assertAlmostEqual(eer, 1 - 0.5 * (5 / 6 + 3 / 4))\n self.assertAlmostEqual(confidence_auroc, 1 / 8 / 2 + 1 / 2)\n self.assertAlmostEqual(confidence_aupr, 1 / 8 + 7 / 8 * (1 / 2 + 8 / 9) / 2)\n self.assertAlmostEqual(confidence_aurcc, 0.1 * (1 / 2 + 1 / 3 + 1 / 4 + 1 / 5 + 1 / 6 + 1 / 7 + 1 / 8 + 1 / 9 + 2 / 10 / 2))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ivan-chai/exact","sub_path":"mdn-metric/tests/metrics/test_verification.py","file_name":"test_verification.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"17903332188","text":"from worf.tests.helpers import ApiTest\nfrom worf.models import User, AccessToken\nfrom worf.settings import settings\nfrom worf.tests.fixtures import super_user, normal_user\nimport requests\n\n\nclass TestEMailVerification(ApiTest):\n fixtures = [{\"normal_user\": normal_user}]\n\n def test_email_change(self):\n \"\"\"\n Check e-mail change flow\n \"\"\"\n self.session.add(self.normal_user)\n\n response = self.authenticated_post(\n url=\"/change-email\",\n user=self.normal_user,\n json={\"email\": \"foomanchu@usa.gov\"},\n )\n assert response.status_code == 200\n\n self.session.refresh(self.normal_user)\n assert self.normal_user.email_change_code is not None\n\n email = self.test_queue.get(True, timeout=2.0)\n assert email[\"type\"] == \"email\"\n\n message = email[\"data\"]\n assert message[\"from\"] == settings.get(\"smtp.from\")\n assert message[\"to\"] == self.normal_user.new_email\n\n for part in message.walk():\n text = part.get_payload(decode=True)\n if not text:\n continue\n # make sure the code is included in the e-mail\n assert text.decode(\"utf-8\").find(self.normal_user.email_change_code) != -1\n\n # unauthenticated requests should not work\n response = requests.put(\n self.url(\"/change-email\"), json={\"code\": self.normal_user.email_change_code}\n )\n\n assert response.status_code == 401\n\n # the wrong code should not work\n response = self.authenticated_put(\n url=\"/change-email\",\n user=self.normal_user,\n json={\"code\": \"1234567890123456\"},\n )\n\n assert response.status_code == 404\n\n old_email = self.normal_user.email\n\n # with an authorized user and the correct code it should work\n response = self.authenticated_put(\n url=\"/change-email\",\n user=self.normal_user,\n json={\"code\": self.normal_user.email_change_code},\n )\n\n assert response.status_code == 200\n\n # make sure a notification is sent out about the email change\n email = self.test_queue.get(True, timeout=2.0)\n assert email[\"type\"] == \"email\"\n message = email[\"data\"]\n # make sure it goes to the OLD address\n assert message[\"To\"] == old_email\n\n # the code shouldn't be usable more than once\n response = self.authenticated_put(\n url=\"/change-email\",\n user=self.normal_user,\n json={\"code\": self.normal_user.email_change_code},\n )\n\n assert response.status_code == 404\n","repo_name":"worf-dev/worf","sub_path":"tests/api/v1/test_email_change.py","file_name":"test_email_change.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5665166348","text":"import csv\nfrom datetime import datetime\nimport argparse\n\n\nclass TransformApplicationLifecycle:\n\n def __init__(self,\n in_file_name='input.csv',\n out_file_name='output.csv',\n id_column='UniqueID',\n string_column='string_agg',\n forced_headers=None):\n \"\"\"\n Constructor method. This will set some object variables that we will need in the transformation\n :param in_file_name: Input file name/path\n :param out_file_name: Output file name/path\n :param id_column: Header of the column that contains the id\n :param string_column: Header of the column that contains the string that we will need to process\n :param forced_headers: If we know beforehand the headers that will be created, and we need them in that order\n \"\"\"\n self.in_file_name = in_file_name\n self.out_file_name = out_file_name\n self.id_column = id_column\n self.string_column = string_column\n self.forced_headers = forced_headers\n self.headers = [self.id_column] # This will hold all possible column names. We know that id_column will be one.\n self.data = [] # each element of the list will be a dictionary with the column name as the key\n # We create the result list (this will hold the \"final\" result) with the headers\n self.result = [self.headers]\n\n\n @staticmethod\n def unique_column_name(columns, name):\n \"\"\"\n This method is related with the Transformation class itself, so it should stay inside it as a static method.\n Finds repeated names and returns a unique name (by adding a counter at the end of the name)\n Note: This would be a good candidate to create a different class/object to hold and manage unique names\n :param columns: Current rows dictionary (to find repeated column names)\n :param name: The name that we need to find a unique name for\n :return: a string with a unique name\n \"\"\"\n # If name not in row_columns yet, set it to 0\n # otherwise, increase by 1\n columns[name] = columns.get(name, -1) + 1\n return f'{name}_{columns[name]}'\n\n def fetch_data(self):\n with open(self.in_file_name, newline='') as csvfile:\n csvreader = csv.DictReader(csvfile, delimiter=',')\n for row in csvreader:\n # This will hold the existing headers in this row, to handle the cases where the same name appears more than once\n row_columns = {}\n id_value = row[self.id_column]\n data_row = {self.id_column: id_value}\n string_value = row[self.string_column]\n # Next, we use a list comprehension to get the headers and respective values in a list of tuples\n # Given an input like: 'column1]value1|column2]value2|column1]value3'\n # We get as a result: [(column1,value1),(column2,value2),(column1,value3)]\n row_raw_values = [(i.split(']')[0], i.split(']')[1]) for i in string_value.split('|')]\n # We than need to convert [(column1,value1),(column2,value2),(column1,value3)]\n # To the final: [{column1_0: value1},{column2_0: value2},{column1_1: value3}]\n for i in row_raw_values:\n column_name = self.unique_column_name(row_columns, i[0])\n value = i[1] + ':00' # Adding ':00' so that we can read the timestamp more easily\n # Process the timestamp string to the required output format\n value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f%z').strftime('%b %d %Y, %H:%M:%S')\n # Add this column_name / value to the current row\n data_row[column_name] = value\n # Add column_name to headers\n if column_name not in self.headers: # This is ok as long as the dataset is fairly small\n self.headers.append(column_name)\n self.data.append(data_row)\n\n def transform(self):\n # Are we forcing the header list?\n if self.forced_headers is not None:\n # Make sure that in the forced_headers we have the same headers that we found in the data\n if sorted(self.forced_headers) != sorted(self.headers):\n raise Exception('Forced headers are not the same as the headers found on the data.')\n self.headers = self.forced_headers\n self.result = [self.headers]\n # Add all rows to self.result\n for row in self.data:\n new_row = {i: row.get(i, '') for i in self.headers}\n new_row_iter = [new_row[i] for i in new_row]\n self.result.append(new_row_iter)\n\n def output_result(self):\n with open(self.out_file_name, 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerows(self.result)\n\n\ndef eval_forced_headers(forced_headers_str):\n \"\"\"\n Expects either a Null or a valid Python expression of a list of strings. Throws a SyntaxError Exception otherwise.\n :param forced_headers_str: A string that should contain a valid Python expression of a list of strings\n :return: A valid python object, that should be a list of strings\n \"\"\"\n if not forced_headers_str:\n return None\n forced_headers = eval(forced_headers_str)\n return forced_headers\n\n\ndef main():\n # Fetch (optional) arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_file_name',\n required=False,\n help='Input file name (or full path)',\n default='CC Application Lifecycle.csv',\n type=str)\n parser.add_argument('--out_file_name',\n required=False,\n help='Output file name (or full path)',\n default='result.csv',\n type=str)\n parser.add_argument('--header',\n required=False,\n help='A string representing a valid Python of a list of strings. This will force a given list '\n 'of headers and therefore is only useful if we already know the columns and want to set a '\n 'given order. See Readme.md for an example of how to use this argument.',\n default='',\n type=str)\n args = parser.parse_args()\n # Process the header argument\n forced_headers_str = args.header\n forced_headers_str = (\"['UniqueID','REGISTERED_0','ACKNOWLEDGED_0','APPROVED_0','REACKNOWLEDGED_0','CLOSED_0', \"\n \"'APPOINTMENT_SCHEDULED_0','REJECTED_0','ON_HOLD_0','BLOCKED_0','TERMINATE_0','INITIATED_0', \"\n \"'APPROVED_1','ON_HOLD_1','INITIATED_1','REGISTERED_1','BLOCKED_1','CLOSED_1','APPROVED_2']\")\n forced_headers = eval_forced_headers(forced_headers_str)\n transformation = TransformApplicationLifecycle(in_file_name=args.in_file_name,\n out_file_name=args.out_file_name,\n forced_headers=forced_headers)\n # Read the data\n transformation.fetch_data()\n # Process it\n transformation.transform()\n # Output the result\n transformation.output_result()\n # I have opted to have these methods being called outside the class constructor method as that makes testing just a\n # bit easier to write and understand.\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"josemrsantos/recognise_bank","sub_path":"task_1/t_application_lifecycle.py","file_name":"t_application_lifecycle.py","file_ext":"py","file_size_in_byte":7631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26613221410","text":"# Vanilla MLP\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\nclass MLP(object):\n def __init__(self, rng, input_x, dim_layers, activation, keep_prob, name):\n \"\"\"\n feed forward network that is usually used as encoder/decoder\n :param rng: random seed for initialization\n :param input_x: input tensor (batch_size * dim)\n :param dim_layers: list of int values for dim\n :param activation: list of activation functions\n :param keep_prob: keep prob\n :param name: name\n \"\"\"\n self.name = name\n\n \"\"\"rng\"\"\"\n self.initialRNG = rng\n\n \"\"\"input\"\"\"\n self.input = input_x\n\n \"\"\"dropout\"\"\"\n self.keep_prob = keep_prob\n\n \"\"\"\"NN structure\"\"\"\n self.dim_layers = dim_layers\n self.activation = activation\n self.num_layer = len(activation)\n \"\"\"Build NN\"\"\"\n self.buildNN()\n\n def buildNN(self, initialzer=tf.keras.initializers.glorot_normal):\n assert self.num_layer + 1 == len(self.dim_layers)\n self.W = []\n self.b = []\n for i in range(self.num_layer):\n weights = tf.get_variable(self.name + \"W%0i\" % i, shape=[self.dim_layers[i + 1], self.dim_layers[i]],\n initializer=initialzer)\n bias = tf.Variable(tf.zeros((self.dim_layers[i + 1], 1), tf.float32), name=self.name + 'b%0i' % i)\n self.W.append(weights)\n self.b.append(bias)\n H = tf.transpose(self.input)\n for i in range(self.num_layer):\n H = tf.nn.dropout(H, keep_prob=self.keep_prob)\n H = tf.matmul(self.W[i], H) + self.b[i]\n if self.activation[i] != 0:\n if self.activation[i] == tf.nn.softmax:\n H = self.activation[i](H, axis=0)\n else:\n H = self.activation[i](H)\n self.output = tf.transpose(H)\n\n def saveNN(self, sess, path):\n for i in range(len(self.W)):\n sess.run(self.W[i]).tofile(path + '_w%0i.bin' % i)\n sess.run(self.b[i]).tofile(path + '_b%0i.bin' % i)\n","repo_name":"sebastianstarke/AI4Animation","sub_path":"AI4Animation/SIGGRAPH_Asia_2019/TensorFlow/NSM/Lib_Opt/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":7032,"dataset":"github-code","pt":"85"} +{"seq_id":"20557724749","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport sys\nimport torch\n\n\nfrom . import backend_registry\nfrom .constants import DEFAULT_RPC_TIMEOUT, DEFAULT_NUM_SEND_RECV_THREADS\n\n\ndef is_available():\n return sys.version_info >= (3, 0) and hasattr(torch._C, \"_rpc_init\")\n\n\nif is_available() and not torch._C._rpc_init():\n raise RuntimeError(\"Failed to initialize torch.distributed.rpc\")\n\n\nif is_available():\n from .api import _init_rpc\n from .api import * # noqa: F401\n import torch.distributed.autograd\n\n def init_model_parallel(\n self_name,\n backend=backend_registry.BackendType.PROCESS_GROUP,\n init_method=None,\n self_rank=-1,\n worker_name_to_id=None,\n num_send_recv_threads=DEFAULT_NUM_SEND_RECV_THREADS,\n rpc_timeout=DEFAULT_RPC_TIMEOUT,\n ):\n r\"\"\"\n Initializes model parallel primitives such as the local rpc agent\n and distributed autograd.\n\n Initializes the local RPC agent which immediately makes the current\n process ready to send and receive RPCs. The caller needs to make\n sure the specified backend is properly intialized before calling\n this method. For example, to use ``pg`` (ProcessGroup) backend,\n ``init_process_group`` must be invoked prior to this method.\n\n Arguments:\n backend (Enum): type of RPC backend implementation.\n Currently, process group backend is the only\n available backend implementation. (default:\n ``RpcBackend.PROCESS_GROUP``).\n self_name (str): a globally unique name of this node. (e.g.,\n ``Trainer3``, ``ParameterServer2``, ``Master``,\n ``Worker1``) Name can only contain number, alphabet,\n underscore, and/or dash, and must be shorter than\n 128 characters.\n self_rank (int): a globally unique id/rank of this node.\n init_method(str): backend specific init arguments.\n num_send_recv_threads(int): Number of threads for send/recv work.\n rpc_timeout (datetime.timedelta): Timeout for RPCs. Defaults to 10 seconds.\n \"\"\"\n # Rendezvous.\n world_size = len(worker_name_to_id)\n rendezvous_iterator = torch.distributed.rendezvous(\n init_method, rank=self_rank, world_size=world_size\n )\n store, _, _ = next(rendezvous_iterator)\n\n # Initialize RPC.\n _init_rpc(\n backend,\n store,\n self_name,\n self_rank,\n worker_name_to_id,\n num_send_recv_threads,\n rpc_timeout,\n )\n\n # Initialize Autograd.\n torch.distributed.autograd._init(api._agent.get_worker_info().id)\n","repo_name":"MostafaSalem/pytorch","sub_path":"torch/distributed/rpc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"85"} +{"seq_id":"12426384508","text":"from bacpypes.core import deferred,run\nfrom bacpypes.local.device import LocalDeviceObject\nfrom bacpypes.app import BIPSimpleApplication\nfrom bacpypes.apdu import ReadPropertyRequest,ReadPropertyACK,WritePropertyRequest\nfrom bacpypes.iocb import IOCB\nfrom bacpypes.primitivedata import Null, Atomic, Boolean, Unsigned, Integer, \\\n Real, Double, OctetString, CharacterString, BitString, Date, Time, ObjectIdentifier,Tag\nfrom bacpypes.constructeddata import Array, Any, AnyAtomic,ArrayOf\nfrom bacpypes.object import get_datatype \nfrom bacpypes.pdu import Address,RemoteStation\nimport time\nclass BacnetApp(BIPSimpleApplication):\n def __init__(self,*args,**kwarg):\n self.userdata=None\n device=LocalDeviceObject(vendorIdentifier=47808,objectIdentifier=47808)\n print('BacnetAppInit',*args,**kwarg)\n BIPSimpleApplication.__init__(self,device,*args,**kwarg)\n #time.sleep(0.8)#等待bac run\n self.whoisback=None\n self.who_is({})\n #self.i_am()\n def do_IAmRequest(self,apdu):\n print('iam',apdu.iAmDeviceIdentifier)\n device=dict(\n bacnetid=\"%s:%s\"%(apdu.iAmDeviceIdentifier[0],apdu.iAmDeviceIdentifier[1]),\n address=list(apdu.pduSource.addrTuple)#[apdu.pduSource.addrNet,[d for d in apdu.pduSource.addrAddr]],\n )\n if self.userdata is not None:\n self.userdata.append(device)\n if self.whoisback:\n self.whoisback(device)\n else:\n pass\n #self.read(device['address'],device['bacnetid'],'objectList',device)\n #self.read(device['address'],device['bacnetid'],'objectList',device if self.whoisback is None else self.whoisback)\n def who_is(self,config,back=None):\n #self.i_am()\n print('whoIs',config)\n self.userdata=[]\n self.whoisback=back\n BIPSimpleApplication.who_is(self,\n low_limit=config.get('lowlimits',0),\n high_limit=config.get('highlimits',10000)\n )\n return self.userdata\n def read(self,pduSource,obj_id,key,device):\n #function.log('request',pduSource,obj_id,key,device)\n if isinstance(obj_id,str):\n obj_id=obj_id.split(':')\n obj_id[1]=int(obj_id[1])\n if isinstance(pduSource,str):\n pduSource=pduSource.split(':')\n pduSource[1]=int(pduSource[1])\n request=ReadPropertyRequest(\n objectIdentifier=tuple(obj_id),\n propertyIdentifier=key,\n #destination=RemoteStation(pduSource[0] or 0,bytearray(pduSource[1]))\n destination=Address(tuple(pduSource))\n )\n iocb = IOCB(request) \n iocb.context=device,pduSource,key,obj_id\n iocb.add_callback(self.readBack)\n self.request_io(iocb)\n def readBack(self,iocb):\n apdu=iocb.ioResponse\n if not isinstance(apdu, ReadPropertyACK):\n #self.read(iocb.context[0]['address'],iocb.context[0]['bacnetid'],'objectList',iocb.context[0])\n return\n if iocb.context[1]=='objectList':\n value=apdu.propertyValue.cast_out(ArrayOf(ObjectIdentifier))\n value=[\"%s:%s\"%(v[0],v[1]) for v in value]\n else:\n datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)\n if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):\n if apdu.propertyArrayIndex == 0:\n value = apdu.propertyValue.cast_out(Unsigned)\n else:\n value = apdu.propertyValue.cast_out(datatype.subtype)\n else:\n value = apdu.propertyValue.cast_out(datatype)\n if isinstance(iocb.context[0],dict):\n iocb.context[0][iocb.context[1]]=value\n else:\n iocb.context[0](value,*iocb.context[1:])\n #function.log('resulttest1',id(iocb.context[0]),iocb.context[0])\n def writeValue(self,addr,obj_id,prop_id,value,indx=None,priority=None):\n if isinstance(obj_id,str):\n obj_id=obj_id.split(':')\n obj_id[1]=int(obj_id[1])\n addr=Address(tuple(addr))\n datatype = get_datatype(obj_id[0],prop_id)\n if datatype is None:return\n if (value == 'null'):\n value = Null()\n elif issubclass(datatype, AnyAtomic):\n dtype, dvalue = value.split(':', 1)\n datatype = {\n 'b': Boolean,\n 'u': lambda x: Unsigned(int(x)),\n 'i': lambda x: Integer(int(x)),\n 'r': lambda x: Real(float(x)),\n 'd': lambda x: Double(float(x)),\n 'o': OctetString,\n 'c': CharacterString,\n 'bs': BitString,\n 'date': Date,\n 'time': Time,\n 'id': ObjectIdentifier,\n }[dtype]\n value = datatype(dvalue)\n elif issubclass(datatype, Atomic):\n if datatype is Integer:\n value = int(value)\n elif datatype is Real:\n value = float(value)\n elif datatype is Unsigned:\n value = int(value)\n value = datatype(value)\n elif issubclass(datatype, Array) and (indx is not None):\n if indx == 0:\n value = Integer(value)\n elif issubclass(datatype.subtype, Atomic):\n value = datatype.subtype(value)\n elif not isinstance(value, datatype.subtype):\n raise TypeError(\"invalid result datatype, expecting %s\" % (datatype.subtype.__name__,))\n elif not isinstance(value, datatype):\n raise TypeError(\"invalid result datatype, expecting %s\" % (datatype.__name__,))\n # build a request\n request = WritePropertyRequest(\n objectIdentifier=tuple(obj_id),\n propertyIdentifier=prop_id,\n destination=addr\n )\n # save the value\n request.propertyValue = Any()\n request.propertyValue.cast_in(value)\n if indx is not None:\n request.propertyArrayIndex = indx\n if priority is not None:\n request.priority = priority\n iocb = IOCB(request)\n self.request_io(iocb)\nif __name__=='__main__':\n import time\n import _thread\n print('bac')\n app=BacnetApp(('0.0.0.0',47808))\n tmp={}\n def loop():\n time.sleep(1)\n app.writeValue([\"192.168.1.35\",47808],\"analogInput:2\",\"presentValue\",5)\n app.read([\"192.168.1.35\",47808],\"analogInput:2\",\"presentValue\",tmp)\n time.sleep(2) \n print(app.userdata,tmp)\n def readojlist(*args):\n print('readojlist',*args)\n def whoisback(device):\n app.read(device['address'],device['bacnetid'],\"objectList\",readojlist)\n print('whoisback',device)\n\n def loop2():\n app.who_is({},whoisback)\n loop2()\n #_thread.start_new_thread(loop,())\n run()\n \n","repo_name":"hdqlife/blink","sub_path":"app/bLink/client/common/bac.py","file_name":"bac.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31571289531","text":"\"\"\"Script for training a diffusion model on MNIST data.\"\"\"\nimport click\nimport pytorch_lightning as pl\nimport torch\nfrom aim.pytorch_lightning import AimLogger\nfrom data import create_dataloaders, load_data\nfrom model import DhariwalUNet\nfrom pytorch_lightning.callbacks import ModelCheckpoint\n\nfrom diffusion.denoisers import KarrasDenoiser, KarrasOptimalDenoiser\nfrom diffusion.training import (\n WEIGHTING_SCHEMES,\n DiffusionDatasetWrapper,\n DiffusionModel,\n EMAWarmupSchedule,\n KarrasLossFn,\n LogUniformSigmaSampler,\n)\n\n\n@click.command()\n@click.option(\"--batch_size\", default=256, help=\"Training batch size.\")\n@click.option(\"--lr\", default=2e-4, help=\"Learning rate.\")\n@click.option(\"--loss_weighting\", default=\"min-snr-5\", help=\"Name of the loss weighting scheme.\")\n@click.option(\"--matmul-precision\", default=\"medium\", help=\"Precision of float32 matmul ops.\")\n@click.option(\"--n_workers\", default=8, help=\"Number of workers for data loading.\")\n@click.option(\"--n_epochs\", default=250, help=\"Number of training epochs.\")\n@click.option(\"--n_gpus\", default=2, help=\"Number of GPUs to train on.\")\n@click.option(\"--sigma_data\", default=0.6, help=\"Average variance of the data.\")\n@click.option(\"--seed\", default=42, help=\"Random seed.\")\ndef main(\n batch_size, lr, loss_weighting, matmul_precision, n_workers, n_epochs, n_gpus, sigma_data, seed\n):\n torch.set_float32_matmul_precision(matmul_precision)\n pl.seed_everything(seed)\n\n # Load data.\n train_dataset, val_dataset, test_dataset = load_data()\n train_dataset = DiffusionDatasetWrapper(train_dataset, fixed_noise=False)\n val_dataset = DiffusionDatasetWrapper(val_dataset, fixed_noise=True)\n test_dataset = DiffusionDatasetWrapper(test_dataset, fixed_noise=True)\n\n # Create dataloaders.\n train_loader, val_loader, test_loader = create_dataloaders(\n train_dataset, val_dataset, test_dataset, batch_size=batch_size, num_workers=n_workers\n )\n\n # Instantiate and compile diffusion model.\n sigma_data = 0.6\n optimizer_cls = torch.optim.Adam\n optimizer_kwargs = {\"lr\": lr}\n lr_scheduler_cls = torch.optim.lr_scheduler.ReduceLROnPlateau\n lr_scheduler_kwargs = {\"mode\": \"min\", \"factor\": 0.5, \"patience\": 5, \"min_lr\": 1e-6}\n\n unet = DhariwalUNet(\n img_resolution=28,\n in_channels=1,\n out_channels=1,\n model_channels=64,\n channel_mult=[1, 2, 3],\n channel_mult_emb=4,\n num_blocks=1,\n attn_resolutions=[],\n dropout=0.0,\n label_dropout=0,\n )\n model = KarrasDenoiser(model=unet, sigma_data=sigma_data)\n loss_fn = KarrasLossFn()\n loss_weight_fn = WEIGHTING_SCHEMES[loss_weighting]\n sigma_sampler = LogUniformSigmaSampler(min_value=1e-3, max_value=1e1)\n ema_schedule = EMAWarmupSchedule(inv_gamma=1.0, power=0.9)\n diffusion = DiffusionModel(\n model=model,\n loss_fn=loss_fn,\n loss_weight_fn=loss_weight_fn,\n sigma_sampler=sigma_sampler,\n ema_schedule=ema_schedule,\n optimizer_cls=optimizer_cls,\n optimizer_kwargs=optimizer_kwargs,\n lr_scheduler_cls=lr_scheduler_cls,\n lr_scheduler_kwargs=lr_scheduler_kwargs,\n )\n diffusion.setup_validation(\n validation_sigmas=[1e-3, 1e-2, 1e-1, 1e0],\n # validation_optimal_denoiser=KarrasOptimalDenoiser(val_loader, sigma_data),\n )\n\n device = \"cuda\"\n aim_logger = AimLogger(\n experiment=\"MNIST-diffusion\",\n train_metric_prefix=\"train/\",\n test_metric_prefix=\"test/\",\n val_metric_prefix=\"val/\",\n )\n callback = ModelCheckpoint(\n dirpath=\"checkpoints\",\n monitor=\"val/loss\",\n mode=\"min\",\n save_top_k=1,\n save_last=True,\n )\n trainer = pl.Trainer(\n accelerator=device,\n devices=n_gpus,\n strategy=\"ddp_find_unused_parameters_true\",\n precision=\"16-mixed\",\n max_epochs=n_epochs,\n gradient_clip_val=0.1,\n log_every_n_steps=16,\n logger=aim_logger,\n callbacks=[callback],\n )\n trainer.fit(diffusion, train_loader, val_loader)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alshedivat/diffusion-playground","sub_path":"playground/mnist/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10936347783","text":"import pandas as pd\nimport os\nimport glob\nimport psycopg2\nfrom sql_queries import *\n\ndef process_data(cur, con, filepath, func):\n \"\"\"\n Driver function to load data from songs and event logs files into postgreSQL\n :param cur: a database cursor reference\n :param con: database connection reference\n :param filepath : parent directory where the file exist\n :param func = function to call\n :return:\n \"\"\"\n all_files = list()\n for root, dirs, files, in os.walk(filepath):\n files = glob.glob(os.path.join(root, \"*.json\"))\n for f in files:\n all_files.append(os.path.abspath(f))\n # get total number of files found\n num_files = len(all_files)\n print(\"{} files found in {}\".format( num_files, filepath))\n for i, datafile in enumerate(all_files,1):\n func(cur, datafile)\n con.commit()\n print(\"{}/{} file processed\".format(i, num_files))\n\n\ndef process_song_file(cur, datafile):\n \"\"\"\n\n :param cur: connection to database\n :param datafile: list contains filepath\n \"\"\"\n df = pd.DataFrame([pd.read_json(datafile, typ='series', convert_dates=False)])\n\n for value in df.values:\n num_songs, artist_id, artist_latitude, artist_longitude, artist_location, artist_name, song_id, title, duration, year = value\n\n # insert into table artist\n artists_data = (artist_id, artist_name, artist_location, artist_latitude, artist_longitude)\n cur.execute(artist_table_insert, artists_data)\n\n\n # insert into table song\n song_data = (song_id, title, artist_id, year, duration)\n cur.execute(song_table_insert, song_data)\n print(f\"Records inserted for files {datafile}\")\n\n\ndef process_log_file(cur, datafile):\n \"\"\"\n\n :param cur: connection to database\n :param datafile: list contains filepath\n \"\"\"\n # open log file\n df = pd.read_json(datafile,lines= True)\n df.columns = [ c.lower() for c in df.columns]\n\n # filter by next song action\n df = df[df['page']=='NextSong'].astype({'ts': 'datetime64[ms]'})\n\n #convert timestamp column to datetime\n t = pd.Series(df['ts'], index = df.index)\n # insert time data records\n column_labels = [\"timestamp\", \"hour\", \"day\", \"weekofyear\", \"month\", \"year\", \"weekday\"]\n time_data = []\n for data in t:\n time_data.append([data, data.hour, data.day, data.weekofyear, data.month, data.year, data.day_name()])\n\n time_df = pd.DataFrame.from_records(data=time_data, columns=column_labels)\n\n for i, row in time_df.iterrows():\n cur.execute(time_table_insert, list(row))\n\n # load user tables\n user_df = df[['userid','firstname', 'lastname','gender','level']]\n\n for i, row in user_df.iterrows():\n # insert user tables\n cur.execute(user_table_insert,list(row))\n\n # insert songplay records\n for index, row in df.iterrows():\n cur.execute(song_select,(row.song, row.artist, row.length))\n result = cur.fetchone()\n if result:\n songid,artistid= result\n else:\n songid, artistid= None, None\n\n # insert songplay record\n songplay_data =(row.ts,row.userid, row.level, songid,artistid, row.sessionid, row.location, row.useragent)\n cur.execute(songplay_table_insert, songplay_data)\n\n\ndef main():\n \"\"\"\n function for loading song and log data into postgres database\n \"\"\"\n con = psycopg2.connect(host='127.0.0.1', dbname='sparkifydb', user='postgres', password='juhari123')\n cur = con.cursor()\n\n process_data(cur,con, filepath='data/song_data', func= process_song_file)\n process_data(cur, con, filepath='data/log_data', func=process_log_file)\n\n con.close()\n\nif __name__ == \"__main__\":\n main()\n print(\"Finished Processing !!\")\n\n\n\n\n\n\n\n\n","repo_name":"trijuhari/Data-Modelling-Postgres","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18935210897","text":"import math\nimport numpy as np\nimport paddle\nimport paddle.nn as nn\nfrom paddle.regularizer import L1Decay, L2Decay\nfrom paddle import ParamAttr\nfrom TransformerEncoder import TransformerEncoder, FeedForward\nfrom resnet18 import ResNet18\n\nweight_attr_1 = ParamAttr(initializer = nn.initializer.XavierNormal(), regularizer = L2Decay(0.005))\nbias_attr_1 = ParamAttr(initializer = nn.initializer.XavierNormal(), regularizer = L2Decay(0.005))\n\n\nclass MyNet(paddle.nn.Layer):\n\n def __init__(self, length, dropout = 0.1):\n super(MyNet, self).__init__()\n self.length = length\n self.window_len = 2 * self.length + 1\n self.conv_shape = 1\n\n self.fe_seq = nn.Sequential(\n TransformerEncoder(6, 6, 60, 6, 50, dropout),\n ResNet18(1, 60),\n paddle.nn.Dropout(dropout)\n )\n self.fe_dssp = nn.Sequential(\n TransformerEncoder(6, 6, 14, 2, 50, dropout),\n ResNet18(1, 14),\n paddle.nn.Dropout(dropout)\n )\n self.fe_cc = nn.Sequential(\n TransformerEncoder(6, 6, 28, 4, 50, dropout),\n ResNet18(1, 28),\n paddle.nn.Dropout(dropout)\n )\n self.relu1 = paddle.nn.ReLU()\n self.relu2 = paddle.nn.ReLU()\n self.fc11 = paddle.nn.Linear(102, 64, weight_attr=weight_attr_1, bias_attr=bias_attr_1)\n self.fc12 = paddle.nn.Linear(64, 32, weight_attr=weight_attr_1, bias_attr=bias_attr_1)\n self.fc13 = paddle.nn.Linear(32, 1, weight_attr=weight_attr_1, bias_attr=bias_attr_1)\n \n def forward(self, inputs):\n #20, 20, 20, 20, 14, 28\n pssm = inputs[:, :, 0:20] + inputs[:, :, 60: 80]\n hmm = inputs[:, :, 20:40] + inputs[:, :, 60: 80]\n raw_protein = inputs[:, :, 40: 60] + inputs[:, :, 60: 80]\n dssp = inputs[:, :, 80:94]\n cc = inputs[:, :, 94:122]\n \n seq = paddle.concat([pssm, hmm, raw_protein], axis = -1)\n # 11, 20\n seq_feature = self.fe_seq(seq)\n dssp_feature = self.fe_dssp(dssp)\n cc_feature = self.fe_cc(cc)\n\n out = paddle.concat([seq_feature, dssp_feature, cc_feature], axis=-1)\n out = self.relu1(self.fc11(out))\n out = self.relu2(self.fc12(out))\n out = self.fc13(out)\n return out\n","repo_name":"llwcool/SSPPI","sub_path":"MyNet.py","file_name":"MyNet.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"11665440072","text":"'''\nCreated on Jul 6, 2018\n\n@author: agutierrez\n'''\nimport numpy\n\nfrom madmex.lcc.transform import TransformBase\n\n\ndef _spatial_covariance(X, h):\n '''\n This method computes the spatial covariance for an image. This is, the covariance of an\n image with itself, but shifted by an amount specified with h.\n '''\n X_mean = numpy.average(X, axis=(1,2))\n X_shifted = numpy.roll(numpy.roll(X, h[1], axis=1), h[0], axis=2)\n bands = X.shape[0]\n pixels = X.shape[1] * X.shape[2]\n X_centered = (X - X_mean[:,numpy.newaxis,numpy.newaxis]).reshape(bands, pixels)\n X_shifted_centered = (X_shifted - X_mean[:,numpy.newaxis,numpy.newaxis]).reshape(bands, pixels)\n C = numpy.matmul(X_centered, X_shifted_centered.T) / (pixels - 1)\n return C\n\n\nclass Transform(TransformBase):\n '''Antares implementation of MAF transformation\n\n This transform maximizes the autocorrelation for the image. The bands are\n order by autocorrelation with the first band having the maximum autocorrelation\n and subjected to be uncorrelated with the other bands.\n This process is useful in the sense that it improves the spatial coherence\n of the IR-MAD transform.\n\n '''\n def __init__(self, X, shift=(1, 1)):\n '''Instantiate MAF transform class\n\n Args:\n shift (tuple): A vector that represents the amount that the image will be\n shifted before calculating the correlation with itself.\n '''\n super().__init__(X)\n self.h = numpy.array(shift)\n\n\n def transform(self):\n '''Computes the Maximum Autocorrelation Factor (MAF) transform.\n\n Return:\n np.ndarray: Transformed array\n '''\n sigma = _spatial_covariance(self.X, numpy.array((0,0)))\n gamma = 2 * sigma - _spatial_covariance(self.X, self.h) - _spatial_covariance(self.X, -self.h)\n lower = numpy.linalg.cholesky(sigma)\n lower_inverse = numpy.linalg.inv(lower)\n eig_problem = numpy.matmul(numpy.matmul(lower_inverse, gamma), lower_inverse.T)\n eig_values, eig_vectors = numpy.linalg.eig(eig_problem)\n sort_index = eig_values.argsort()\n vector = eig_vectors[:, sort_index]\n M = numpy.matmul(vector.T, self.X.reshape(self.bands, self.rows * self.cols))\n return M.reshape(self.bands, self.rows, self.cols)\n","repo_name":"CONABIO/antares3","sub_path":"madmex/lcc/transform/maf.py","file_name":"maf.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"1699794313","text":"class Solution(object):\n def nextPermutation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n if len(nums) >= 2:\n for idx in range(len(nums)-1, 0, -1):\n if nums[idx] > nums[idx-1]:\n for i in range(len(nums)-1, idx-1, -1):\n if nums[i] > nums[idx-1]:\n nums[i], nums[idx-1] = nums[idx-1], nums[i]\n break\n nums[idx:] = reversed(nums[idx:])\n return\n nums[:] = reversed(nums[:])","repo_name":"coolmich/py-leetcode","sub_path":"solu/31|Next Permutation.py","file_name":"31|Next Permutation.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"30348025314","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import get_object_or_404, render, redirect, render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth import logout, login, authenticate\nfrom django.contrib.auth.forms import UserCreationForm\nfrom users.forms import PhoneNumberForm, UserUpdateForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import PermissionDenied\nfrom users.models import PhoneNumber\nfrom django.utils import timezone\nfrom leagues.forms import LeagueForm\n\nimport pdb\n\ndef logout_view(request):\n logout(request)\n return render(request, 'leagues/home_page.html', {'form': UserCreationForm,})\n\ndef register(request):\n if request.method != 'POST':\n form = UserCreationForm()\n else:\n form = UserCreationForm(data=request.POST)\n\n if form.is_valid():\n new_user = form.save()\n authenticated_user = authenticate(username=new_user.username,\n password=request.POST['password1'])\n login(request, authenticated_user)\n return HttpResponseRedirect(reverse('leagues:leagues_index'))\n\n context = {'form': form}\n return render(request, 'users/register.html', context)\n\n@login_required\ndef update_account(request, user_id):\n user = get_object_or_404(User, pk=user_id)\n\n if request.user.is_authenticated() and request.user.id == user.id:\n form = UserUpdateForm(request.POST or None, instance=user)\n\n context = {\n 'user': user,\n 'form': form,\n }\n \n if form.is_valid():\n form.save()\n\n return render(request, 'users/account.html', context)\n else:\n raise PermissionDenied\n\n@login_required\ndef create_or_update_phone_number(request):\n form_class = PhoneNumberForm\n user = get_object_or_404(User, pk=request.user.id)\n if request.method == \"POST\":\n form = form_class(request.POST, request.FILES)\n if form.is_valid():\n try:\n old_number = PhoneNumber.objects.get(user=user)\n new_number = form['number'].value()\n old_number.number = str(new_number)\n old_number.twilio_formatted_number = format_twilio_number(str(new_number))\n old_number.created_date = timezone.now()\n old_number.is_valid_phone_number = old_number.is_valid_number()\n old_number.save()\n except PhoneNumber.DoesNotExist:\n phone_number = form.save(commit=False)\n phone_number.user = user\n phone_number.twilio_formatted_number = format_twilio_number(phone_number.number)\n phone_number.created_date = timezone.now()\n phone_number.is_valid_phone_number = phone_number.is_valid_number()\n phone_number.save()\n return render(request, 'users/account.html', {'user': user, 'form': UserUpdateForm(request.POST or None, instance=user),})\n\n context = {\n\t\t'form': form_class,\n\t}\n return render(request, 'phone_numbers/update_phone_number.html', context)\n\ndef format_twilio_number(number):\n return '+1' + number","repo_name":"Jabronious/CloudRoni","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8040743086","text":"print(\"\"\"*********\r\nHESAP MAKİNASI PROGRAMI\r\n\r\nİşlemler;\r\n\r\n1.toplama işlemi\r\n\r\n2.çıkarma işlemi\r\n\r\n3.çarpma işlemi\r\n\r\n4.bölme işlemi\r\n*********\r\n\"\"\")\r\n\r\na=int(input(\"1. sayıyı giriniz:\"))\r\nb=int(input(\"2. sayıyı giriniz:\"))\r\n\r\nişlem=int(input(\"Yapmak istediginiz işlemi tuşlayınız:\"))\r\n\r\nif işlem == 1:\r\n print(\" {} ile {} nın toplamı {} dır\".format(a,b,a+b))\r\nelif işlem ==2:\r\n print(\" {} ile {} nın farkı {} dır\".format(a,b,a-b))\r\nelif işlem == 3:\r\n print(\" {} ile {} nın carpımı {} dır\".format(a,b,a*b))\r\nelif işlem == 4:\r\n print(\" {} ile {} nın bölümü {} dır\".format(a,b,a/b))\r\nelse:\r\n print(\"Geçersiz işlem\")\r\n\r\n","repo_name":"Beytullahzor7/Python-Applications","sub_path":"Hesap makinası.py","file_name":"Hesap makinası.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7568500137","text":"# Word puzzle driver\n# Assumes word_list.txt file of one word per line\nimport string\n\ndef get_word_list():\n \"\"\" Return a list of words from a word_list.txt file . \"\"\"\n data_file = open(\"3eslWordList.txt\",\"r\")\n word_list = [] # start with an empty word list\n for word in data_file: # for every word (line) in the file\n # strip off end−of−line characters and make each word lowercase\n # then append the word to the word list\n word_list.append(word.strip().lower())\n data_file.close()\n return word_list\n\ndef puzzle(word_list):\n \"\"\"Finds an eight-letter word resulting from adding two pairs of doubled\n letters to the word 'rate.'\"\"\"\n letters = \"rate\"\n \n for word in word_list:\n if len(word)==8:\n copy_str = word\n another_str = '' # Compose a string used to determine if the\n # letters r,a,t,e appears in sequence\n for i, ch in enumerate(word):\n # Remove the letters r,a,t,e from a copy of the original word\n if ch in letters:\n another_str+=ch\n copy_str = copy_str[:i]+copy_str[i+1:]\n # Compare whats left from removing the letter r,a,t,e and\n # see if the order in which r,a,t,e appears in the word is the\n # same as it appears in the variable letters\n if copy_str[0]==copy_str[1] and copy_str[2]==copy_str[3] \\\n and another_str==letters:\n print(word)\n \nword_list = get_word_list()\npuzzle(word_list)\n","repo_name":"Pshypher/tpocup","sub_path":"ch07/projects/proj_01/proj_01l.py","file_name":"proj_01l.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73840707476","text":"import numpy as np\nfrom PIL import ImageGrab\nimport cv2\nfrom PyKeyboard import PressKey, ReleaseKey, W, A, S, D\nimport time\nfrom Constants import VERTICES\nfrom statistics import mean\n\n\ndef roi(image, vertices):\n mask = np.zeros_like(image)\n cv2.fillPoly(mask, vertices, 255)\n masked = cv2.bitwise_and(image, mask)\n return masked\n\n\ndef draw_lines(processed_img, lines, color):\n try:\n for line in lines:\n coordinates = line[0]\n cv2.line(processed_img,\n (coordinates[0], coordinates[1]), (coordinates[2], coordinates[3]),\n color,\n 3)\n except:\n pass\n return processed_img\n\n\ndef myMouseListener(event, x, y, flags, param):\n global mouseX, mouseY\n if event == cv2.EVENT_LBUTTONDBLCLK:\n mouseX, mouseY = x, y\n print(mouseX, mouseY)\n # cv2.putText(new_screen, f\"{mouseX},{mouseY}\", (780, 580), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)\n # cv2.circle(img,(x,y),100,(255,0,0),-1)\n\n\ndef process_img(original_image):\n color_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)\n processed_img = cv2.Canny(processed_img, threshold1=120, threshold2=300)\n\n processed_img = cv2.GaussianBlur(processed_img, (5, 5), 0)\n\n vertices = np.array(VERTICES)\n processed_img = roi(processed_img, [vertices])\n\n minLineLength = 100\n maxLineGap = 5\n lines = cv2.HoughLinesP(processed_img, 1, np.pi / 180, 180, np.array([]), minLineLength, maxLineGap)\n # processed_img = draw_lines(color_img, lines, [0, 255, 0])\n\n m1, m2 = 0, 0\n try:\n print(\"jihk\")\n l1, l2, m1, m2 = draw_lanes(lines)\n cv2.line(color_img, (l1[0], l1[1]), (l1[2], l1[3]), [0, 255, 0], 3)\n cv2.line(color_img, (l2[0], l2[1]), (l2[2], l2[3]), [0, 255, 0], 3)\n except Exception as e:\n print(str(e))\n pass\n\n return color_img, m1, m2\n\n\ndef draw_lanes(lines):\n try:\n ys = []\n print(enumerate(lines))\n for i in lines:\n ys += [i[0][1], i[0][3]]\n # for y_cord in i:\n # ys += [y_cord[1], y_cord[3]]\n\n min_y = min(ys)\n max_y = 600\n new_lines = []\n line_dict = {}\n\n for idx, i in enumerate(lines):\n for xyxy in i:\n x_coords = (xyxy[0], xyxy[2])\n y_coords = (xyxy[1], xyxy[3])\n A = np.vstack([x_coords, np.ones(len(x_coords))]).T\n m, b = np.linalg.lstsq(A, y_coords)[0]\n\n x1 = (min_y - b) / m\n x2 = (max_y - b) / m\n\n line_dict[idx] = [m, b, [int(x1), min_y, int(x2), max_y]]\n new_lines.append([int(x1), min_y, int(x2), max_y])\n final_lanes = {}\n\n for idx in line_dict:\n final_lanes_copy = final_lanes.copy()\n m = line_dict[idx][0]\n b = line_dict[idx][1]\n line = line_dict[idx][2]\n\n if len(final_lanes) == 0:\n final_lanes[m] = [[m, b, line]]\n\n else:\n found_copy = False\n\n for other_ms in final_lanes_copy:\n\n if not found_copy:\n if abs(other_ms * 1.2) > abs(m) > abs(other_ms * 0.8):\n if abs(final_lanes_copy[other_ms][0][1] * 1.2) > abs(b) > abs(\n final_lanes_copy[other_ms][0][1] * 0.8):\n final_lanes[other_ms].append([m, b, line])\n found_copy = True\n break\n else:\n final_lanes[m] = [[m, b, line]]\n\n line_counter = {}\n\n for lanes in final_lanes:\n line_counter[lanes] = len(final_lanes[lanes])\n\n top_lanes = sorted(line_counter.items(), key=lambda item: item[1])[::-1][:2]\n\n lane1_id = top_lanes[0][0]\n lane2_id = top_lanes[1][0]\n\n l1_x1, l1_y1, l1_x2, l1_y2 = average_lane(final_lanes[lane1_id])\n l2_x1, l2_y1, l2_x2, l2_y2 = average_lane(final_lanes[lane2_id])\n\n return [l1_x1, l1_y1, l1_x2, l1_y2], [l2_x1, l2_y1, l2_x2, l2_y2], lane1_id, lane2_id\n\n except Exception as e:\n print(str(e))\n\n\ndef average_lane(lane_data):\n x1s = []\n y1s = []\n x2s = []\n y2s = []\n for data in lane_data:\n x1s.append(data[2][0])\n y1s.append(data[2][1])\n x2s.append(data[2][2])\n y2s.append(data[2][3])\n return int(mean(x1s)), int(mean(y1s)), int(mean(x2s)), int(mean(y2s))\n\n\nfor i in list(range(4))[::-1]:\n print(i + 1)\n time.sleep(1)\n\n\n# print('Gas')\n# PressKey(W)\n# time.sleep(3)\n# print('Release Gas pedal')\n# ReleaseKey(W)\n\ndef straight():\n PressKey(W)\n ReleaseKey(A)\n ReleaseKey(D)\n ReleaseKey(W)\n\n\ndef left():\n ReleaseKey(W)\n PressKey(A)\n ReleaseKey(D)\n ReleaseKey(A)\n\n\ndef right():\n ReleaseKey(W)\n PressKey(D)\n ReleaseKey(A)\n ReleaseKey(D)\n\n\ndef slowdown():\n ReleaseKey(W)\n ReleaseKey(A)\n ReleaseKey(D)\n\n\nwhile True:\n global new_screen\n screen = np.array(ImageGrab.grab(bbox=(0, 40, 800, 600)))\n new_screen, m1, m2 = process_img(screen)\n\n cv2.imshow('window2', new_screen)\n # cv2.setMouseCallback('window2', myMouseListener)\n\n if m1 < 0 and m2 < 0:\n right()\n elif m1 > 0 and m2 > 0:\n left()\n else:\n straight()\n\n\n # cv2.imshow('window', cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n","repo_name":"Clay-CL/python-auto-nfs","sub_path":"screen_grab.py","file_name":"screen_grab.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"16407173013","text":"#Boa:Frame:Frame1\r\n\r\nimport MySQLdb\r\nimport wx #MainKamus, framenotebook, KamusJepang, Tentangprogram, Bantuan\r\nimport wx.lib.analogclock\r\nimport wx.lib.masked.timectrl\r\nimport wx.lib.masked.textctrl\r\n\r\nconn=MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\")\r\ncur = conn.cursor()\r\n\r\n\r\ndef create(parent):\r\n return Frame1(parent)\r\n\r\n[wxID_FRAME1, wxID_FRAME1ANALOGCLOCK1, wxID_FRAME1BITMAPBUTTON16, \r\n wxID_FRAME1BTN_1, wxID_FRAME1BTN_2, wxID_FRAME1BTN_3, wxID_FRAME1BTN_4, \r\n wxID_FRAME1BTN_HAPUSIG, wxID_FRAME1BTN_HAPUSIND, wxID_FRAME1BTN_HAPUSPY, \r\n wxID_FRAME1BTN_HOME, wxID_FRAME1BTN_KIRIM, wxID_FRAME1BTN_REFLES, \r\n wxID_FRAME1BTN_TAMBAHIG, wxID_FRAME1BTN_TAMBAHIND, wxID_FRAME1BTN_TAMBAHPY, \r\n wxID_FRAME1BTN_UPDATEIG, wxID_FRAME1BTN_UPDATEIND, wxID_FRAME1BTN_UPDATEPY, \r\n wxID_FRAME1LC_IG, wxID_FRAME1LC_IND, wxID_FRAME1LC_KS, wxID_FRAME1LC_PY, \r\n wxID_FRAME1LC_TANYA, wxID_FRAME1NOTEBOOK1, wxID_FRAME1NOTEBOOK2, \r\n wxID_FRAME1NOTEBOOK3, wxID_FRAME1NOTEBOOK4, wxID_FRAME1PANEL1, \r\n wxID_FRAME1PANEL2, wxID_FRAME1PANEL3, wxID_FRAME1PANEL4, wxID_FRAME1PANEL5, \r\n wxID_FRAME1PANEL6, wxID_FRAME1PANEL7, wxID_FRAME1PANEL8, wxID_FRAME1PANEL9, \r\n wxID_FRAME1STATICBOX1, wxID_FRAME1STATICBOX2, wxID_FRAME1STATICLINE1, \r\n wxID_FRAME1STATICLINE10, wxID_FRAME1STATICLINE2, wxID_FRAME1STATICLINE3, \r\n wxID_FRAME1STATICLINE4, wxID_FRAME1STATICLINE5, wxID_FRAME1STATICLINE6, \r\n wxID_FRAME1STATICLINE7, wxID_FRAME1STATICLINE8, wxID_FRAME1STATICLINE9, \r\n wxID_FRAME1STATICTEXT1, wxID_FRAME1STATICTEXT2, wxID_FRAME1STATICTEXT3, \r\n wxID_FRAME1STATICTEXT5, wxID_FRAME1TXT_BALAS, wxID_FRAME1TXT_ID, \r\n wxID_FRAME1TXT_ID_IG, wxID_FRAME1TXT_ID_IND, wxID_FRAME1TXT_KOSAKATAIG, \r\n wxID_FRAME1TXT_KOSAKATAIND, wxID_FRAME1TXT_KOSAKATAPY, \r\n wxID_FRAME1TXT_NAMA_KS, wxID_FRAME1TXT_PENGERTIANIG, \r\n wxID_FRAME1TXT_PENGERTIANIND, wxID_FRAME1TXT_PENGERTIANPY, \r\n wxID_FRAME1TXT_SAMPLEIG, wxID_FRAME1TXT_SAMPLEIND, wxID_FRAME1TXT_SAMPLEPY, \r\n wxID_FRAME1TXT_SARAN_KS, \r\n] = [wx.NewId() for _init_ctrls in range(68)]\r\n\r\nclass Frame1(wx.Frame):\r\n def _init_coll_lc_py_Columns(self, parent):\r\n # generated method, don't edit\r\n\r\n parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,\r\n heading='Kosataka', width=400)\r\n\r\n def _init_coll_notebook2_Pages(self, parent):\r\n # generated method, don't edit\r\n\r\n parent.AddPage(imageId=-1, page=self.panel6, select=True,\r\n text='Pengertian')\r\n parent.AddPage(imageId=-1, page=self.panel7, select=False,\r\n text='Sample')\r\n\r\n def _init_coll_lc_ks_Columns(self, parent):\r\n # generated method, don't edit\r\n\r\n parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT, heading='Nama',\r\n width=100)\r\n parent.InsertColumn(col=1, format=wx.LIST_FORMAT_LEFT,\r\n heading='Kritik Dan Saran', width=500)\r\n\r\n def _init_coll_lc_tanya_Columns(self, parent):\r\n # generated method, don't edit\r\n\r\n parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,\r\n heading='Pertanyaan', width=600)\r\n\r\n def _init_coll_lc_ig_Columns(self, parent):\r\n # generated method, don't edit\r\n\r\n parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,\r\n heading='Kosakata', width=400)\r\n\r\n def _init_coll_notebook1_Pages(self, parent):\r\n # generated method, don't edit\r\n\r\n parent.AddPage(imageId=-1, page=self.panel2, select=True,\r\n text='Admin Kamus Python')\r\n parent.AddPage(imageId=-1, page=self.panel3, select=False,\r\n text='Admin Kamus indonesia')\r\n parent.AddPage(imageId=-1, page=self.panel4, select=False,\r\n text='Admin Kamus inggris')\r\n parent.AddPage(imageId=-1, page=self.panel5, select=False,\r\n text='Admin Tentang / Bantuan')\r\n\r\n def _init_coll_lc_ind_Columns(self, parent):\r\n # generated method, don't edit\r\n\r\n parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,\r\n heading='Kosakata', width=400)\r\n\r\n def _init_ctrls(self, prnt):\r\n # generated method, don't edit\r\n wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,\r\n pos=wx.Point(-8, -8), size=wx.Size(1296, 776),\r\n style=wx.DEFAULT_FRAME_STYLE, title='Admin')\r\n self.SetClientSize(wx.Size(1280, 738))\r\n\r\n self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,\r\n pos=wx.Point(0, 0), size=wx.Size(1280, 738),\r\n style=wx.TAB_TRAVERSAL)\r\n\r\n self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,\r\n label='Administrator', name='staticText1', parent=self.panel1,\r\n pos=wx.Point(16, 0), size=wx.Size(507, 71), style=0)\r\n self.staticText1.SetFont(wx.Font(48, wx.SWISS, wx.NORMAL, wx.BOLD,\r\n False, 'Algerian'))\r\n\r\n self.notebook1 = wx.Notebook(id=wxID_FRAME1NOTEBOOK1, name='notebook1',\r\n parent=self.panel1, pos=wx.Point(0, 72), size=wx.Size(1272, 648),\r\n style=0)\r\n self.notebook1.SetFont(wx.Font(10, wx.SWISS, wx.ITALIC, wx.NORMAL,\r\n False, 'Terminal'))\r\n self.notebook1.SetBackgroundColour(wx.Colour(75, 75, 75))\r\n\r\n self.panel2 = wx.Panel(id=wxID_FRAME1PANEL2, name='panel2',\r\n parent=self.notebook1, pos=wx.Point(0, 0), size=wx.Size(1264,\r\n 622), style=wx.TAB_TRAVERSAL)\r\n self.panel2.SetBackgroundColour(wx.Colour(0, 0, 0))\r\n\r\n self.panel3 = wx.Panel(id=wxID_FRAME1PANEL3, name='panel3',\r\n parent=self.notebook1, pos=wx.Point(0, 0), size=wx.Size(1264,\r\n 622), style=wx.TAB_TRAVERSAL)\r\n self.panel3.SetBackgroundColour(wx.Colour(0, 0, 0))\r\n\r\n self.panel4 = wx.Panel(id=wxID_FRAME1PANEL4, name='panel4',\r\n parent=self.notebook1, pos=wx.Point(0, 0), size=wx.Size(1264,\r\n 622), style=wx.TAB_TRAVERSAL)\r\n self.panel4.SetBackgroundColour(wx.Colour(15, 15, 15))\r\n\r\n self.panel5 = wx.Panel(id=wxID_FRAME1PANEL5, name='panel5',\r\n parent=self.notebook1, pos=wx.Point(0, 0), size=wx.Size(1264,\r\n 622), style=wx.TAB_TRAVERSAL)\r\n self.panel5.SetBackgroundColour(wx.Colour(64, 128, 128))\r\n\r\n self.notebook2 = wx.Notebook(id=wxID_FRAME1NOTEBOOK2, name='notebook2',\r\n parent=self.panel2, pos=wx.Point(80, 48), size=wx.Size(1120, 528),\r\n style=wx.RAISED_BORDER | wx.NB_LEFT)\r\n self.notebook2.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False,\r\n 'Tahoma'))\r\n\r\n self.panel6 = wx.Panel(id=wxID_FRAME1PANEL6, name='panel6',\r\n parent=self.notebook2, pos=wx.Point(0, 0), size=wx.Size(1090,\r\n 520), style=wx.TAB_TRAVERSAL)\r\n self.panel6.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n\r\n self.panel7 = wx.Panel(id=wxID_FRAME1PANEL7, name='panel7',\r\n parent=self.notebook2, pos=wx.Point(0, 0), size=wx.Size(1090,\r\n 520), style=wx.TAB_TRAVERSAL)\r\n\r\n self.staticLine1 = wx.StaticLine(id=wxID_FRAME1STATICLINE1,\r\n name='staticLine1', parent=self.panel2, pos=wx.Point(56, 24),\r\n size=wx.Size(1168, 2), style=0)\r\n\r\n self.staticLine2 = wx.StaticLine(id=wxID_FRAME1STATICLINE2,\r\n name='staticLine2', parent=self.panel2, pos=wx.Point(1224, 24),\r\n size=wx.Size(1, 576), style=0)\r\n\r\n self.staticLine3 = wx.StaticLine(id=wxID_FRAME1STATICLINE3,\r\n name='staticLine3', parent=self.panel2, pos=wx.Point(56, 24),\r\n size=wx.Size(1, 576), style=0)\r\n\r\n self.staticLine4 = wx.StaticLine(id=wxID_FRAME1STATICLINE4,\r\n name='staticLine4', parent=self.panel2, pos=wx.Point(56, 600),\r\n size=wx.Size(1168, 2), style=0)\r\n\r\n self.analogClock1 = wx.lib.analogclock.analogclock.AnalogClock(id=wxID_FRAME1ANALOGCLOCK1,\r\n name='analogClock1', parent=self.panel1, pos=wx.Point(1064, 0),\r\n size=wx.Size(208, 80), style=0)\r\n\r\n self.txt_kosakatapy = wx.TextCtrl(id=wxID_FRAME1TXT_KOSAKATAPY,\r\n name='txt_kosakatapy', parent=self.panel6, pos=wx.Point(8, 24),\r\n size=wx.Size(504, 40), style=0, value='')\r\n self.txt_kosakatapy.SetFont(wx.Font(16, wx.SWISS, wx.NORMAL, wx.NORMAL,\r\n False, 'Copperplate Gothic Bold'))\r\n self.txt_kosakatapy.SetToolTipString('Cari Kosakata')\r\n self.txt_kosakatapy.SetEditable(True)\r\n self.txt_kosakatapy.SetHelpText('fuyuyf]\\\\')\r\n self.txt_kosakatapy.Bind(wx.EVT_TEXT, self.OnTxt_kosakatapyText,\r\n id=wxID_FRAME1TXT_KOSAKATAPY)\r\n\r\n self.txt_pengertianpy = wx.TextCtrl(id=wxID_FRAME1TXT_PENGERTIANPY,\r\n name='txt_pengertianpy', parent=self.panel6, pos=wx.Point(8, 128),\r\n size=wx.Size(776, 384), style=wx.TE_MULTILINE, value='')\r\n self.txt_pengertianpy.SetEditable(True)\r\n\r\n self.lc_py = wx.ListCtrl(id=wxID_FRAME1LC_PY, name='lc_py',\r\n parent=self.panel6, pos=wx.Point(808, 16), size=wx.Size(264, 496),\r\n style=wx.LC_REPORT)\r\n self._init_coll_lc_py_Columns(self.lc_py)\r\n self.lc_py.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnLc_pyListItemSelected,\r\n id=wxID_FRAME1LC_PY)\r\n\r\n self.staticLine5 = wx.StaticLine(id=wxID_FRAME1STATICLINE5,\r\n name='staticLine5', parent=self.panel6, pos=wx.Point(8, 96),\r\n size=wx.Size(776, 2), style=0)\r\n\r\n self.staticLine6 = wx.StaticLine(id=wxID_FRAME1STATICLINE6,\r\n name='staticLine6', parent=self.panel6, pos=wx.Point(795, 16),\r\n size=wx.Size(1, 496), style=0)\r\n\r\n self.btn_tambahpy = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon tambah.jpg',\r\n wx.BITMAP_TYPE_JPEG), id=wxID_FRAME1BTN_TAMBAHPY,\r\n name='btn_tambahpy', parent=self.panel6, pos=wx.Point(616, 32),\r\n size=wx.Size(88, 48), style=wx.BU_AUTODRAW)\r\n self.btn_tambahpy.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_tambahpy.Bind(wx.EVT_BUTTON, self.OnBtn_tambahpyButton,\r\n id=wxID_FRAME1BTN_TAMBAHPY)\r\n\r\n self.btn_updatepy = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon refles.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BTN_UPDATEPY,\r\n name='btn_updatepy', parent=self.panel6, pos=wx.Point(528, 32),\r\n size=wx.Size(88, 48), style=wx.BU_AUTODRAW)\r\n self.btn_updatepy.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_updatepy.Bind(wx.EVT_BUTTON, self.OnBtn_updatepyButton,\r\n id=wxID_FRAME1BTN_UPDATEPY)\r\n\r\n self.btn_hapuspy = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon hapus.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BTN_HAPUSPY,\r\n name='btn_hapuspy', parent=self.panel6, pos=wx.Point(704, 32),\r\n size=wx.Size(80, 48), style=wx.BU_AUTODRAW)\r\n self.btn_hapuspy.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_hapuspy.Bind(wx.EVT_BUTTON, self.OnBtn_hapuspyButton,\r\n id=wxID_FRAME1BTN_HAPUSPY)\r\n\r\n self.txt_samplepy = wx.TextCtrl(id=wxID_FRAME1TXT_SAMPLEPY,\r\n name='txt_samplepy', parent=self.panel7, pos=wx.Point(16, 8),\r\n size=wx.Size(1056, 496), style=wx.TE_MULTILINE, value='')\r\n\r\n self.notebook3 = wx.Notebook(id=wxID_FRAME1NOTEBOOK3, name='notebook3',\r\n parent=self.panel3, pos=wx.Point(48, 32), size=wx.Size(1160, 568),\r\n style=0)\r\n\r\n self.panel8 = wx.Panel(id=wxID_FRAME1PANEL8, name='panel8',\r\n parent=self.notebook3, pos=wx.Point(8, 8), size=wx.Size(1144,\r\n 552), style=wx.TAB_TRAVERSAL)\r\n self.panel8.SetBackgroundColour(wx.Colour(255, 157, 157))\r\n\r\n self.txt_pengertianind = wx.TextCtrl(id=wxID_FRAME1TXT_PENGERTIANIND,\r\n name='txt_pengertianind', parent=self.panel8, pos=wx.Point(8, 48),\r\n size=wx.Size(816, 248), style=wx.TE_MULTILINE, value='')\r\n\r\n self.txt_sampleind = wx.TextCtrl(id=wxID_FRAME1TXT_SAMPLEIND,\r\n name='txt_sampleind', parent=self.panel8, pos=wx.Point(8, 304),\r\n size=wx.Size(816, 240), style=wx.TE_MULTILINE, value='')\r\n\r\n self.lc_ind = wx.ListCtrl(id=wxID_FRAME1LC_IND, name='lc_ind',\r\n parent=self.panel8, pos=wx.Point(840, 72), size=wx.Size(296, 472),\r\n style=wx.LC_REPORT)\r\n self._init_coll_lc_ind_Columns(self.lc_ind)\r\n self.lc_ind.Bind(wx.EVT_LIST_ITEM_SELECTED,\r\n self.OnLc_indListItemSelected, id=wxID_FRAME1LC_IND)\r\n\r\n self.staticLine8 = wx.StaticLine(id=wxID_FRAME1STATICLINE8,\r\n name='staticLine8', parent=self.panel8, pos=wx.Point(832, 64),\r\n size=wx.Size(1, 472), style=0)\r\n\r\n self.btn_tambahind = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon tambah.jpg',\r\n wx.BITMAP_TYPE_JPEG), id=wxID_FRAME1BTN_TAMBAHIND,\r\n name='btn_tambahind', parent=self.panel8, pos=wx.Point(856, 8),\r\n size=wx.Size(72, 48), style=wx.BU_AUTODRAW)\r\n self.btn_tambahind.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_tambahind.Bind(wx.EVT_BUTTON, self.OnBtn_tambahindButton,\r\n id=wxID_FRAME1BTN_TAMBAHIND)\r\n\r\n self.btn_hapusind = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon hapus.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BTN_HAPUSIND,\r\n name='btn_hapusind', parent=self.panel8, pos=wx.Point(952, 8),\r\n size=wx.Size(72, 48), style=wx.BU_AUTODRAW)\r\n self.btn_hapusind.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_hapusind.Bind(wx.EVT_BUTTON, self.OnBtn_hapusindButton,\r\n id=wxID_FRAME1BTN_HAPUSIND)\r\n\r\n self.btn_updateind = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon refles.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BTN_UPDATEIND,\r\n name='btn_updateind', parent=self.panel8, pos=wx.Point(1048, 8),\r\n size=wx.Size(72, 48), style=wx.BU_AUTODRAW)\r\n self.btn_updateind.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_updateind.Bind(wx.EVT_BUTTON, self.OnBtn_updateindButton,\r\n id=wxID_FRAME1BTN_UPDATEIND)\r\n\r\n self.notebook4 = wx.Notebook(id=wxID_FRAME1NOTEBOOK4, name='notebook4',\r\n parent=self.panel4, pos=wx.Point(80, 8), size=wx.Size(1096, 608),\r\n style=wx.RAISED_BORDER)\r\n\r\n self.panel9 = wx.Panel(id=wxID_FRAME1PANEL9, name='panel9',\r\n parent=self.notebook4, pos=wx.Point(8, 8), size=wx.Size(1072,\r\n 584), style=wx.TAB_TRAVERSAL)\r\n self.panel9.SetBackgroundColour(wx.Colour(13, 13, 255))\r\n\r\n self.txt_pengertianig = wx.TextCtrl(id=wxID_FRAME1TXT_PENGERTIANIG,\r\n name='txt_pengertianig', parent=self.panel9, pos=wx.Point(8, 48),\r\n size=wx.Size(760, 264), style=wx.TE_MULTILINE, value='')\r\n\r\n self.txt_sampleig = wx.TextCtrl(id=wxID_FRAME1TXT_SAMPLEIG,\r\n name='txt_sampleig', parent=self.panel9, pos=wx.Point(8, 320),\r\n size=wx.Size(760, 256), style=wx.TE_MULTILINE, value='')\r\n\r\n self.lc_ig = wx.ListCtrl(id=wxID_FRAME1LC_IG, name='lc_ig',\r\n parent=self.panel9, pos=wx.Point(784, 72), size=wx.Size(280, 504),\r\n style=wx.LC_REPORT)\r\n self._init_coll_lc_ig_Columns(self.lc_ig)\r\n self.lc_ig.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnLc_igListItemSelected,\r\n id=wxID_FRAME1LC_IG)\r\n\r\n self.staticLine9 = wx.StaticLine(id=wxID_FRAME1STATICLINE9,\r\n name='staticLine9', parent=self.panel9, pos=wx.Point(776, 64),\r\n size=wx.Size(288, 2), style=0)\r\n\r\n self.staticLine10 = wx.StaticLine(id=wxID_FRAME1STATICLINE10,\r\n name='staticLine10', parent=self.panel9, pos=wx.Point(776, 64),\r\n size=wx.Size(1, 512), style=0)\r\n\r\n self.btn_tambahig = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon tambah.jpg',\r\n wx.BITMAP_TYPE_JPEG), id=wxID_FRAME1BTN_TAMBAHIG,\r\n name='btn_tambahig', parent=self.panel9, pos=wx.Point(792, 8),\r\n size=wx.Size(72, 48), style=wx.BU_AUTODRAW)\r\n self.btn_tambahig.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_tambahig.Bind(wx.EVT_BUTTON, self.OnBtn_tambahigButton,\r\n id=wxID_FRAME1BTN_TAMBAHIG)\r\n\r\n self.btn_hapusig = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon hapus.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BTN_HAPUSIG,\r\n name='btn_hapusig', parent=self.panel9, pos=wx.Point(888, 8),\r\n size=wx.Size(72, 48), style=wx.BU_AUTODRAW)\r\n self.btn_hapusig.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_hapusig.Bind(wx.EVT_BUTTON, self.OnBtn_hapusigButton,\r\n id=wxID_FRAME1BTN_HAPUSIG)\r\n\r\n self.btn_updateig = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon refles.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BTN_UPDATEIG,\r\n name='btn_updateig', parent=self.panel9, pos=wx.Point(984, 8),\r\n size=wx.Size(72, 48), style=wx.BU_AUTODRAW)\r\n self.btn_updateig.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_updateig.Bind(wx.EVT_BUTTON, self.OnBtn_updateigButton,\r\n id=wxID_FRAME1BTN_UPDATEIG)\r\n\r\n self.staticBox1 = wx.StaticBox(id=wxID_FRAME1STATICBOX1,\r\n label='Kritik Dan Saran', name='staticBox1', parent=self.panel5,\r\n pos=wx.Point(16, 16), size=wx.Size(600, 592), style=0)\r\n self.staticBox1.SetBackgroundColour(wx.Colour(64, 128, 128))\r\n\r\n self.staticBox2 = wx.StaticBox(id=wxID_FRAME1STATICBOX2,\r\n label='Pertanyaan User', name='staticBox2', parent=self.panel5,\r\n pos=wx.Point(672, 16), size=wx.Size(576, 592), style=0)\r\n\r\n self.txt_nama_ks = wx.TextCtrl(id=wxID_FRAME1TXT_NAMA_KS,\r\n name='txt_nama_ks', parent=self.panel5, pos=wx.Point(160, 72),\r\n size=wx.Size(256, 24), style=0, value='')\r\n\r\n self.lc_ks = wx.ListCtrl(id=wxID_FRAME1LC_KS, name='lc_ks',\r\n parent=self.panel5, pos=wx.Point(24, 344), size=wx.Size(584, 256),\r\n style=wx.LC_REPORT)\r\n self._init_coll_lc_ks_Columns(self.lc_ks)\r\n self.lc_ks.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnLc_ksListItemSelected,\r\n id=wxID_FRAME1LC_KS)\r\n\r\n self.txt_saran_ks = wx.TextCtrl(id=wxID_FRAME1TXT_SARAN_KS,\r\n name='txt_saran_ks', parent=self.panel5, pos=wx.Point(24, 144),\r\n size=wx.Size(576, 176), style=wx.TE_MULTILINE, value='')\r\n\r\n self.staticText2 = wx.StaticText(id=wxID_FRAME1STATICTEXT2,\r\n label='Nama', name='staticText2', parent=self.panel5,\r\n pos=wx.Point(272, 48), size=wx.Size(32, 12), style=0)\r\n\r\n self.staticText3 = wx.StaticText(id=wxID_FRAME1STATICTEXT3,\r\n label='Kritik Dan Saran', name='staticText3', parent=self.panel5,\r\n pos=wx.Point(224, 128), size=wx.Size(144, 12), style=0)\r\n\r\n self.txt_balas = wx.TextCtrl(id=wxID_FRAME1TXT_BALAS, name='txt_balas',\r\n parent=self.panel5, pos=wx.Point(680, 80), size=wx.Size(560, 160),\r\n style=wx.TE_MULTILINE, value='')\r\n\r\n self.staticText5 = wx.StaticText(id=wxID_FRAME1STATICTEXT5,\r\n label='Balas', name='staticText5', parent=self.panel5,\r\n pos=wx.Point(928, 48), size=wx.Size(65, 16), style=0)\r\n self.staticText5.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, True,\r\n 'Terminal'))\r\n\r\n self.btn_kirim = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon kirim.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BTN_KIRIM, name='btn_kirim',\r\n parent=self.panel5, pos=wx.Point(1120, 248), size=wx.Size(88, 48),\r\n style=wx.BU_AUTODRAW)\r\n self.btn_kirim.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_kirim.Bind(wx.EVT_BUTTON, self.OnBtn_kirimButton,\r\n id=wxID_FRAME1BTN_KIRIM)\r\n\r\n self.bitmapButton16 = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/icon bersih.png',\r\n wx.BITMAP_TYPE_PNG), id=wxID_FRAME1BITMAPBUTTON16,\r\n name='bitmapButton16', parent=self.panel5, pos=wx.Point(704, 248),\r\n size=wx.Size(104, 48), style=wx.BU_AUTODRAW)\r\n self.bitmapButton16.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n\r\n self.staticLine7 = wx.StaticLine(id=wxID_FRAME1STATICLINE7,\r\n name='staticLine7', parent=self.panel8, pos=wx.Point(832, 64),\r\n size=wx.Size(304, 2), style=0)\r\n\r\n self.txt_kosakataind = wx.TextCtrl(id=wxID_FRAME1TXT_KOSAKATAIND,\r\n name='txt_kosakataind', parent=self.panel8, pos=wx.Point(8, 8),\r\n size=wx.Size(800, 32), style=0, value='')\r\n self.txt_kosakataind.SetToolTipString('Cari & Tambah Kosakata')\r\n self.txt_kosakataind.Bind(wx.EVT_TEXT, self.OnTxt_kosakataindText,\r\n id=wxID_FRAME1TXT_KOSAKATAIND)\r\n\r\n self.txt_kosakataig = wx.TextCtrl(id=wxID_FRAME1TXT_KOSAKATAIG,\r\n name='txt_kosakataig', parent=self.panel9, pos=wx.Point(8, 8),\r\n size=wx.Size(744, 32), style=0, value='')\r\n self.txt_kosakataig.SetToolTipString('Cari & Tambah Kosakata')\r\n self.txt_kosakataig.Bind(wx.EVT_TEXT, self.OnTxt_kosakataigText,\r\n id=wxID_FRAME1TXT_KOSAKATAIG)\r\n\r\n self.txt_id = wx.TextCtrl(id=wxID_FRAME1TXT_ID, name='txt_id',\r\n parent=self.panel2, pos=wx.Point(1080, -32), size=wx.Size(100,\r\n 20), style=0, value='')\r\n\r\n self.txt_id_ind = wx.TextCtrl(id=wxID_FRAME1TXT_ID_IND,\r\n name='txt_id_ind', parent=self.panel8, pos=wx.Point(1032, -32),\r\n size=wx.Size(100, 20), style=0, value='')\r\n\r\n self.txt_id_ig = wx.TextCtrl(id=wxID_FRAME1TXT_ID_IG, name='txt_id_ig',\r\n parent=self.panel9, pos=wx.Point(960, -32), size=wx.Size(100, 20),\r\n style=0, value='')\r\n\r\n self.lc_tanya = wx.ListCtrl(id=wxID_FRAME1LC_TANYA, name='lc_tanya',\r\n parent=self.panel5, pos=wx.Point(680, 304), size=wx.Size(560,\r\n 296), style=wx.LC_REPORT)\r\n self._init_coll_lc_tanya_Columns(self.lc_tanya)\r\n\r\n self.btn_refles = wx.Button(id=wxID_FRAME1BTN_REFLES, label='Refles',\r\n name='btn_refles', parent=self.panel5, pos=wx.Point(616, 264),\r\n size=wx.Size(56, 32), style=0)\r\n self.btn_refles.SetFont(wx.Font(9, wx.SWISS, wx.ITALIC, wx.NORMAL,\r\n False, 'Arial Narrow'))\r\n self.btn_refles.Bind(wx.EVT_BUTTON, self.OnBtn_reflesButton,\r\n id=wxID_FRAME1BTN_REFLES)\r\n\r\n self.btn_home = wx.BitmapButton(bitmap=wx.Bitmap(u'gambar/home5.jpg',\r\n wx.BITMAP_TYPE_JPEG), id=wxID_FRAME1BTN_HOME, name='btn_home',\r\n parent=self.panel1, pos=wx.Point(536, 0), size=wx.Size(72, 72),\r\n style=wx.BU_AUTODRAW)\r\n self.btn_home.SetToolTipString('Buka MainKamus')\r\n self.btn_home.SetBackgroundColour(wx.Colour(255, 255, 255))\r\n self.btn_home.Bind(wx.EVT_BUTTON, self.OnBtn_homeButton,\r\n id=wxID_FRAME1BTN_HOME)\r\n\r\n self.btn_1 = wx.Button(id=wxID_FRAME1BTN_1, label='??', name='btn_1',\r\n parent=self.panel5, pos=wx.Point(616, 88), size=wx.Size(56, 23),\r\n style=0)\r\n self.btn_1.SetToolTipString('+-+-+-+-+-+-+-+-')\r\n self.btn_1.Bind(wx.EVT_BUTTON, self.OnBtn_1Button, id=wxID_FRAME1BTN_1)\r\n\r\n self.btn_2 = wx.Button(id=wxID_FRAME1BTN_2, label='!!', name='btn_2',\r\n parent=self.panel5, pos=wx.Point(616, 152), size=wx.Size(56, 24),\r\n style=0)\r\n self.btn_2.SetToolTipString('#############')\r\n self.btn_2.Bind(wx.EVT_BUTTON, self.OnBtn_2Button, id=wxID_FRAME1BTN_2)\r\n\r\n self.btn_3 = wx.Button(id=wxID_FRAME1BTN_3, label='@T@', name='btn_3',\r\n parent=self.panel5, pos=wx.Point(616, 344), size=wx.Size(56, 23),\r\n style=0)\r\n self.btn_3.SetToolTipString('{{}}')\r\n self.btn_3.Bind(wx.EVT_BUTTON, self.OnBtn_3Button, id=wxID_FRAME1BTN_3)\r\n\r\n self.btn_4 = wx.Button(id=wxID_FRAME1BTN_4, label='^B^', name='btn_4',\r\n parent=self.panel5, pos=wx.Point(616, 408), size=wx.Size(56, 23),\r\n style=0)\r\n self.btn_4.SetToolTipString('\"\"')\r\n self.btn_4.Bind(wx.EVT_BUTTON, self.OnBtn_4Button, id=wxID_FRAME1BTN_4)\r\n\r\n self._init_coll_notebook1_Pages(self.notebook1)\r\n self._init_coll_notebook2_Pages(self.notebook2)\r\n\r\n def __init__(self, parent):\r\n self._init_ctrls(parent)\r\n self.tampil_py()\r\n self.tampil_indo()\r\n self.tampil_inggris()\r\n self.tampil_ks()\r\n self.tampil_bantuan()\r\n\r\n\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n#*****************************Coding Kamus Python*************************************#\r\n\r\n \r\n def tampil_py(self):\r\n self.lc_py.DeleteAllItems()\r\n sql = \"select * from kms_python ORDER BY kosakata\"\r\n cur.execute(sql)\r\n hasil = cur.fetchall()\r\n j = self.lc_py.GetItemCount()\r\n for i in hasil:\r\n self.lc_py.InsertStringItem(j,\"%s\"%i[1])\r\n \r\n def objeck_pdans(self):\r\n sql = \"select * from kms_python where kosakata = '%s'\"%(self.txt_id.GetValue())\r\n cur.execute(sql)\r\n \r\n hasil = cur.fetchone()\r\n \r\n self.txt_pengertianpy.SetValue(hasil[2]) \r\n \r\n self.txt_samplepy.SetValue(hasil[3])\r\n \r\n def bersih(self):\r\n self.txt_kosakatapy.SetValue(\"\")\r\n self.txt_pengertianpy.SetValue(\"\")\r\n self.txt_samplepy.SetValue(\"\")\r\n self.txt_id.SetValue(\"\")\r\n self.txt_kosakatapy.SetFocus()\r\n\r\n def OnBtn_tambahpyButton(self, event):\r\n if self.txt_kosakatapy.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text kosakata masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n elif self.txt_pengertianpy.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text pengertian masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n \r\n elif self.txt_samplepy.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text sample masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n \r\n else:\r\n sql = \"insert into kms_python values ('%s','%s','%s','%s')\"\\\r\n %(self.txt_id.GetValue(),self.txt_kosakatapy.GetValue(),self.txt_pengertianpy.GetValue(),\\\r\n self.txt_samplepy.GetValue())\r\n cur.execute(sql)\r\n conn.commit()\r\n self.pesan=wx.MessageDialog(self,\"Berhasil Menambahkan kata ke database\",\"Succes\",wx.OK)\r\n self.pesan.ShowModal()\r\n self.bersih()\r\n self.tampil_py()\r\n \r\n \r\n def OnBtn_hapuspyButton(self, event):\r\n if self.txt_id.GetValue()==\"\":\r\n self.pesan=wx.MessageDialog(self,\"Silahkan pilih dahulu Yang Akan Dihapus\",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n else:\r\n sql = \"select * from kms_python where kosakata = '%s'\" %(self.txt_id.GetValue())\r\n cur.execute(sql)\r\n hasil=cur.fetchone()\r\n if cur.rowcount > 0:\r\n tanya = wx.MessageDialog(self,\"Yakin Ingin Menghapus\",style=wx.YES_NO)\r\n if tanya.ShowModal()==wx.ID_YES:\r\n sql = \"delete from kms_python where kosakata = '%s'\"%(self.txt_id.GetValue())\r\n cur.execute(sql)\r\n conn.commit()\r\n self.tampil_py()\r\n self.bersih()\r\n self.pesan=wx.MessageDialog(self,\"Data Berhasil Dihapus\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n else:\r\n self.pesan=wx.MessageDialog(self,\"Data Yang Mau Dihapus Tidak Ada Di DATABASE\",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n\r\n def OnBtn_updatepyButton(self, event):\r\n self.tampil_py()\r\n self.bersih()\r\n\r\n def OnLc_pyListItemSelected(self, event):\r\n a = event.m_itemIndex\r\n b = self.lc_py.GetItem(a,0).GetText()\r\n self.txt_id.SetValue(b)\r\n self.objeck_pdans()\r\n\r\n def bersih_py(self):\r\n self.txt_pengertianpy.SetValue(\"\")\r\n self.txt_samplepy.SetValue(\"\")\r\n\r\n def OnTxt_kosakatapyText(self, event):\r\n self.lc_py.DeleteAllItems()\r\n cari = self.txt_kosakatapy.GetValue()\r\n cur.execute( \"select * from kms_python where kosakata LIKE '%%%s%%'\"%(cari))\r\n \r\n hasil = cur.fetchall()\r\n k = self.lc_py.GetItemCount()\r\n for i in hasil:\r\n self.lc_py.InsertStringItem(k,\"%s\"%i[1])\r\n k= k + 1\r\n self.bersih_py()\r\n \r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n#***********************************Coding Kamus Indo*************************************#\r\n \r\n def tampil_indo(self):\r\n self.lc_ind.DeleteAllItems()\r\n sql = \"select * from kms_indo ORDER BY kosakata_ind\"\r\n cur.execute(sql)\r\n hasil = cur.fetchall()\r\n j = self.lc_ind.GetItemCount()\r\n for i in hasil:\r\n self.lc_ind.InsertStringItem(j,\"%s\"%i[1])\r\n \r\n def bersih_indo(self):\r\n self.txt_kosakataind.SetValue(\"\")\r\n self.txt_pengertianind.SetValue(\"\")\r\n self.txt_sampleind.SetValue(\"\")\r\n self.txt_id_ind.SetValue(\"\")\r\n self.txt_kosakataind.SetFocus()\r\n \r\n \r\n def objeckind_pdans(self):\r\n sql = \"select * from kms_indo where kosakata_ind = '%s'\"%(self.txt_id_ind.GetValue())\r\n cur.execute(sql)\r\n \r\n hasil = cur.fetchone()\r\n \r\n self.txt_pengertianind.SetValue(hasil[2]) \r\n \r\n self.txt_sampleind.SetValue(hasil[3])\r\n \r\n def OnBtn_tambahindButton(self, event):\r\n if self.txt_kosakataind.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text kosakata masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n elif self.txt_pengertianind.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text pengertian masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n \r\n elif self.txt_sampleind.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text sample masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n \r\n else:\r\n sql = \"insert into kms_indo values ('%s','%s','%s','%s')\"\\\r\n %(self.txt_id_ind.GetValue(),self.txt_kosakataind.GetValue(),self.txt_pengertianind.GetValue(),\\\r\n self.txt_sampleind.GetValue())\r\n cur.execute(sql)\r\n conn.commit()\r\n self.pesan=wx.MessageDialog(self,\"Berhasil Menambahkan kata ke database\",\"Succes\",wx.OK)\r\n self.pesan.ShowModal()\r\n self.bersih_indo()\r\n self.tampil_indo()\r\n\r\n def OnBtn_hapusindButton(self, event):\r\n if self.txt_id_ind.GetValue()==\"\":\r\n self.pesan=wx.MessageDialog(self,\"Silahkan pilih dahulu Yang Akan Dihapus\",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n else:\r\n sql = \"select * from kms_indo where kosakata_ind = '%s'\" %(self.txt_id_ind.GetValue())\r\n cur.execute(sql)\r\n hasil=cur.fetchone()\r\n if cur.rowcount > 0:\r\n tanya = wx.MessageDialog(self,\"Yakin Ingin Menghapus\",style=wx.YES_NO)\r\n if tanya.ShowModal()==wx.ID_YES:\r\n sql = \"delete from kms_indo where kosakata_ind = '%s'\"%(self.txt_id_ind.GetValue())\r\n cur.execute(sql)\r\n conn.commit()\r\n self.tampil_indo()\r\n self.bersih_indo()\r\n self.pesan=wx.MessageDialog(self,\"Data Berhasil Dihapus\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n else:\r\n self.pesan=wx.MessageDialog(self,\"Data Yang Mau Dihapus Tidak Ada Di DATABASE\",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n\r\n\r\n def OnBtn_updateindButton(self, event):\r\n self.tampil_indo()\r\n self.bersih_indo()\r\n\r\n def OnLc_indListItemSelected(self, event):\r\n a = event.m_itemIndex\r\n b = self.lc_ind.GetItem(a,0).GetText()\r\n self.txt_id_ind.SetValue(b)\r\n self.objeckind_pdans()\r\n \r\n def bersih_ind2(self):\r\n self.txt_pengertianind.SetValue(\"\")\r\n self.txt_sampleind.SetValue(\"\")\r\n\r\n def OnTxt_kosakataindText(self, event):\r\n self.lc_ind.DeleteAllItems()\r\n cari = self.txt_kosakataind.GetValue()\r\n cur.execute( \"select * from kms_indo where kosakata_ind LIKE '%%%s%%'\"%(cari))\r\n \r\n hasil = cur.fetchall()\r\n k = self.lc_ind.GetItemCount()\r\n for i in hasil:\r\n self.lc_ind.InsertStringItem(k,\"%s\"%i[1])\r\n k= k + 1\r\n self.bersih_ind2()\r\n \r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n#*********************************Coding Kamus Inggris************************************#\r\n \r\n def tampil_inggris(self):\r\n self.lc_ig.DeleteAllItems()\r\n sql = \"select * from kms_ingg ORDER BY kosakata_ingg\"\r\n cur.execute(sql)\r\n hasil = cur.fetchall()\r\n j = self.lc_ig.GetItemCount()\r\n for i in hasil:\r\n self.lc_ig.InsertStringItem(j,\"%s\"%i[1])\r\n \r\n def bersih_inggris(self):\r\n self.txt_kosakataig.SetValue(\"\")\r\n self.txt_pengertianig.SetValue(\"\")\r\n self.txt_sampleig.SetValue(\"\")\r\n self.txt_id_ig.SetValue(\"\")\r\n self.txt_kosakataig.SetFocus()\r\n \r\n \r\n def objeckig_pdans(self):\r\n sql = \"select * from kms_ingg where kosakata_ingg = '%s'\"%(self.txt_id_ig.GetValue())\r\n cur.execute(sql)\r\n \r\n hasil = cur.fetchone()\r\n \r\n self.txt_pengertianig.SetValue(hasil[2]) \r\n \r\n self.txt_sampleig.SetValue(hasil[3])\r\n\r\n\r\n def OnBtn_tambahigButton(self, event):\r\n if self.txt_kosakataig.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text kosakata masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n elif self.txt_pengertianig.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text pengertian masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n \r\n elif self.txt_sampleig.GetValue() == \"\":\r\n self.pesan=wx.MessageDialog(self,\"Text sample masih kosong\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n \r\n else:\r\n sql = \"insert into kms_ingg values ('%s','%s','%s','%s')\"\\\r\n %(self.txt_id_ig.GetValue(),self.txt_kosakataig.GetValue(),self.txt_pengertianig.GetValue(),\\\r\n self.txt_sampleig.GetValue())\r\n cur.execute(sql)\r\n conn.commit()\r\n self.pesan=wx.MessageDialog(self,\"Berhasil Menambahkan kata ke database\",\"Succes\",wx.OK)\r\n self.pesan.ShowModal()\r\n self.bersih_inggris()\r\n self.tampil_inggris()\r\n\r\n def OnBtn_hapusigButton(self, event):\r\n if self.txt_id_ig.GetValue()==\"\":\r\n self.pesan=wx.MessageDialog(self,\"Silahkan pilih dahulu Yang Akan Dihapus\",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n else:\r\n sql = \"select * from kms_ingg where kosakata_ingg = '%s'\" %(self.txt_id_ig.GetValue())\r\n cur.execute(sql)\r\n hasil=cur.fetchone()\r\n if cur.rowcount > 0:\r\n tanya = wx.MessageDialog(self,\"Yakin Ingin Menghapus\",style=wx.YES_NO)\r\n if tanya.ShowModal()==wx.ID_YES:\r\n sql = \"delete from kms_ingg where kosakata_ingg = '%s'\"%(self.txt_id_ig.GetValue())\r\n cur.execute(sql)\r\n conn.commit()\r\n self.tampil_inggris()\r\n self.bersih_inggris()\r\n self.pesan=wx.MessageDialog(self,\"Data Berhasil Dihapus\",\"Info\",wx.OK)\r\n self.pesan.ShowModal()\r\n else:\r\n self.pesan=wx.MessageDialog(self,\"Data Yang Mau Dihapus Tidak Ada Di DATABASE\",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n\r\n def OnBtn_updateigButton(self, event):\r\n self.tampil_inggris()\r\n self.bersih_inggris()\r\n\r\n def OnLc_igListItemSelected(self, event):\r\n a = event.m_itemIndex\r\n b = self.lc_ig.GetItem(a,0).GetText()\r\n self.txt_id_ig.SetValue(b)\r\n self.objeckig_pdans()\r\n \r\n def bersih_inggris2(self):\r\n self.txt_pengertianig.SetValue(\"\")\r\n self.txt_sampleig.SetValue(\"\")\r\n\r\n def OnTxt_kosakataigText(self, event):\r\n self.lc_ig.DeleteAllItems()\r\n cari = self.txt_kosakataig.GetValue()\r\n cur.execute( \"select * from kms_ingg where kosakata_ingg LIKE '%%%s%%'\"%(cari))\r\n \r\n hasil = cur.fetchall()\r\n k = self.lc_ig.GetItemCount()\r\n for i in hasil:\r\n self.lc_ig.InsertStringItem(k,\"%s\"%i[1])\r\n k= k + 1\r\n self.bersih_inggris2()\r\n \r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n#******************************Coding Menu Saran Dan Bantuan******************************#\r\n \r\n def tampil_ks(self):\r\n sql = \"select * from tentangprogram\"\r\n cur.execute(sql)\r\n hasil=cur.fetchall()\r\n k = self.lc_ks.GetItemCount()\r\n for i in hasil:\r\n self.lc_ks.InsertStringItem(k,\"%s\"%i[0])\r\n self.lc_ks.SetStringItem(k,1,\"%s\"%i[1])\r\n \r\n k = k+1\r\n\r\n def OnLc_ksListItemSelected(self, event):\r\n no_baris = event.m_itemIndex\r\n \r\n nama = self.lc_ks.GetItem(no_baris,0).GetText()\r\n ks = self.lc_ks.GetItem(no_baris,1).GetText()\r\n \r\n self.txt_nama_ks.SetValue(nama)\r\n self.txt_saran_ks.SetValue(ks)\r\n\r\n def tampil_bantuan(self):\r\n sql = \"select * from pertanyaan\"\r\n cur.execute(sql)\r\n hasil=cur.fetchall()\r\n k = self.lc_tanya.GetItemCount()\r\n for i in hasil:\r\n self.lc_tanya.InsertStringItem(k,\"%s\"%i[0])\r\n \r\n k = k+1\r\n\r\n def OnBtn_kirimButton(self, event):\r\n if self.txt_balas.GetValue()== \"\":\r\n self.pesan = wx.MessageDialog(self,\"Anda Belum Memberi Balasan\",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n \r\n else:\r\n sql = \"insert into balasan values \\\r\n ('%s')\"%(self.txt_balas.GetValue())\r\n cur.execute(sql)\r\n conn.commit()\r\n self.pesan = wx.MessageDialog(self,\"Balasan Anda Sudah Terkirim \",\"Informasi\",wx.OK)\r\n self.pesan.ShowModal()\r\n self.txt_balas.SetValue(\"\")\r\n self.txt_balas.SetFocus()\r\n\r\n def OnBtn_reflesButton(self, event):\r\n self.txt_nama_ks.SetValue(\"\")\r\n self.txt_saran_ks.SetValue(\"\")\r\n self.txt_balas.SetValue(\"\")\r\n self.txt_balas.SetFocus()\r\n\r\n def OnBtn_homeButton(self, event):\r\n self.main = MainKamus.create(None)\r\n self.main.Show()\r\n\r\n def OnBtn_1Button(self, event):\r\n self.main = framenotebook.create(None)\r\n self.main.Show()\r\n \r\n def OnBtn_2Button(self, event):\r\n self.main = KamusJepang.create(None)\r\n self.main.Show()\r\n \r\n\r\n def OnBtn_3Button(self, event):\r\n self.main = Tentangprogram.create(None)\r\n self.main.Show()\r\n \r\n\r\n def OnBtn_4Button(self, event):\r\n self.main = Bantuan.create(None)\r\n self.main.Show()\r\n \r\n\r\n \r\n\r\n","repo_name":"jhnsdsmnkpys/kamus","sub_path":"Administrator.py","file_name":"Administrator.py","file_ext":"py","file_size_in_byte":39858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"43044118006","text":"from __future__ import print_function\nimport optparse\nimport random\nimport tempfile\nimport subprocess;\n\ndef writeConfig(f, options):\n f.write('n %s\\n' % options.num_nodes)\n f.write('m %s\\n' % options.num_edges)\n f.write('a %s\\n' % options.a)\n f.write('b %s\\n' % options.b)\n f.write('c %s\\n' % options.c)\n f.write('d %s\\n' % options.d)\n f.write('MAX_WEIGHT %s\\n' % options.max_weight)\n f.write('MIN_WEIGHT %s\\n' % options.min_weight)\n f.write('SELF_LOOPS 0\\n')\n f.write('STORE_IN_MEMORY 0\\n')\n f.write('SORT_EDGELISTS 0\\n')\n f.write('SORT_TYPE 1\\n')\n f.write('WRITE_TO_FILE 1\\n')\n f.flush()\n\n\ndef main(GTgraph, output, options):\n with tempfile.NamedTemporaryFile(delete=False) as f:\n writeConfig(f, options)\n subprocess.check_call([GTgraph, '-c', f.name, '-o', output])\n\n\nif __name__ == '__main__':\n usage = 'usage: %prog [options] '\n parser = optparse.OptionParser(usage=usage)\n parser.add_option('-n', '--num-nodes', dest=\"num_nodes\", action='store', help='Number of nodes.')\n parser.add_option('-m', '--num-edges', dest=\"num_edges\", action='store', help='Number of edges.')\n parser.add_option('-a', '--param-a', dest=\"a\", action='store', default='0.45', help='Parameter a of rmat.')\n parser.add_option('-b', '--param-b', dest=\"b\", action='store', default='0.15', help='Parameter b of rmat.')\n parser.add_option('-c', '--param-c', dest=\"c\", action='store', default='0.15', help='Parameter c of rmat.')\n parser.add_option('-d', '--param-d', dest=\"d\", action='store', default='0.25', help='Parameter d of rmat.')\n parser.add_option('--max-weight', dest=\"max_weight\",\n default=100, action='store',\n help='edge weights are uniformly selected from integers between [min-weight, max-weight].')\n parser.add_option('--min-weight', dest=\"min_weight\",\n default=0, action='store',\n help='edge weights are uniformly selected from integers between [min-weight, max-weight].')\n\n (options, args) = parser.parse_args()\n if not options.num_nodes:\n parser.error('missing num nodes')\n if not options.num_edges:\n parser.error('missing num edges')\n if len(args) != 2:\n parser.error('missing required arguments')\n main(args[0], args[1], options)\n","repo_name":"PJK/comm-avoiding-cuts-cc","sub_path":"lib/galois/tools/generators/rmat.py","file_name":"rmat.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"23029355834","text":"\"\"\"\nThis module illustrates how to retrieve the top-10 items with highest rating\nprediction. We first train an SVD algorithm on the MovieLens dataset, and then\npredict all the ratings for the pairs (user, item) that are not in the training\nset. We then retrieve the top-10 prediction for each user.\n\"\"\"\n\nfrom collections import defaultdict\n\nfrom surprise import Dataset, SVD\n\n\ndef get_top_n(predictions, n=10):\n \"\"\"Return the top-N recommendation for each user from a set of predictions.\n\n Args:\n predictions(list of Prediction objects): The list of predictions, as\n returned by the test method of an algorithm.\n n(int): The number of recommendation to output for each user. Default\n is 10.\n\n Returns:\n A dict where keys are user (raw) ids and values are lists of tuples:\n [(raw item id, rating estimation), ...] of size n.\n \"\"\"\n\n # First map the predictions to each user.\n top_n = defaultdict(list)\n for uid, iid, true_r, est, _ in predictions:\n top_n[uid].append((iid, est))\n\n # Then sort the predictions for each user and retrieve the k highest ones.\n for uid, user_ratings in top_n.items():\n user_ratings.sort(key=lambda x: x[1], reverse=True)\n top_n[uid] = user_ratings[:n]\n\n return top_n\n\n\n# First train an SVD algorithm on the movielens dataset.\ndata = Dataset.load_builtin(\"ml-100k\")\ntrainset = data.build_full_trainset()\nalgo = SVD()\nalgo.fit(trainset)\n\n# Than predict ratings for all pairs (u, i) that are NOT in the training set.\ntestset = trainset.build_anti_testset()\npredictions = algo.test(testset)\n\ntop_n = get_top_n(predictions, n=10)\n\n# Print the recommended items for each user\nfor uid, user_ratings in top_n.items():\n print(uid, [iid for (iid, _) in user_ratings])\n","repo_name":"NicolasHug/Surprise","sub_path":"examples/top_n_recommendations.py","file_name":"top_n_recommendations.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","stars":6035,"dataset":"github-code","pt":"85"} +{"seq_id":"72967568279","text":"\"\"\"Distance functions\"\"\"\nimport numpy as np\nfrom numba import njit\n\n\n@njit\ndef dist4D(x: np.ndarray, y: np.ndarray, P: float=np.pi*2)->float:\n \"\"\"Distance function for 4D data. It is the L2 norm. \n Difference in time is taken as the minimum difference between two time points within one period. \n\n Args:\n x (np.ndarray): 1D array; [x, y, z, t]\n y (np.ndarray): 1D array; [x, y, z, t]\n P (float): time period \n\n Returns:\n float: LET distance.\n \"\"\"\n ds = np.linalg.norm(x[:3] - y[:3], ord=2)\n dt = np.abs(x[3] % P - y[3] % P)\n if dt > P / 2:\n dt = P - dt\n return np.sqrt(ds**2 + dt**2)","repo_name":"kentotomita/trajectory-clustering","sub_path":"src/dist.py","file_name":"dist.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"75128312918","text":"'''\r\n输入两个链表,找出他们的第一个公共节点\r\n'''\r\nclass Solution:\r\n def FindFirstCommonNode(self, pHead1, pHead2):\r\n p1, p2 = pHead1, pHead2\r\n while p1 != p2:\r\n p1 = p1.next if p1 else pHead2\r\n p2 = p2.next if p2 else pHead1\r\n return p1","repo_name":"Xw-Jia/Sword_Points_To_Offer","sub_path":"36_两个链表的第一个公共节点.py","file_name":"36_两个链表的第一个公共节点.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"29401503077","text":"#!/usr/bin/env python\nimport roslib\nimport sys\nimport rospy\nimport actionlib\nimport control_msgs.msg\nimport controller_manager_msgs.srv\nimport trajectory_msgs.msg\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Int8\n\n\n\n\nclass BaseMoveCBA(object):\n\tdef __init__(self, wait=0.0):\n\t\t# initialize action client\n\t\trospy.Subscriber(\"/CBA_cmd_int\", Int8, self.intcallback)\n\t\tself.cli = actionlib.SimpleActionClient('/hsrb/omni_base_controller/follow_joint_trajectory', control_msgs.msg.FollowJointTrajectoryAction)\n\t\t# wait for the action server to establish connection\n\t\tself.goal = control_msgs.msg.FollowJointTrajectoryGoal()\n\t\tself.traj = trajectory_msgs.msg.JointTrajectory()\n\t\tself.traj.joint_names = [\"odom_x\", \"odom_y\", \"odom_t\"]\n\t\tself.p = trajectory_msgs.msg.JointTrajectoryPoint()\n\t\tself.p.positions = [1, 0, 0.8]\n\t\tself.p.velocities = [0, 0, 0]\n\t\tself.p.time_from_start = rospy.Time(9)\n\t\tself.traj.points = [self.p]\n\t\tself.goal.trajectory = self.traj\n\t\tself.cli.wait_for_server()\n\n\n\tdef listener(self,wait=0.0):\n\t\t\n\t\t# make sure the controller is running\n\t\trospy.wait_for_service('/hsrb/controller_manager/list_controllers')\n\t\tself.list_controllers = rospy.ServiceProxy('/hsrb/controller_manager/list_controllers', controller_manager_msgs.srv.ListControllers)\n\t\trunning = False\n\t\twhile running == False:\n\t\t rospy.sleep(0.1)\n\t\t for c in self.list_controllers().controller:\n\t\t if c.name == 'omni_base_controller' and c.state == 'running':\n\t\t running = True\n\n\t\trospy.spin() \n\t\t# fill ROS message\n\t\t\n\n\tdef intcallback(self, data):\n\t\trospy.loginfo(rospy.get_caller_id()+\"I heard %d\",data.data)\n\t \n\t # command = data.data\n\t\tif data.data == 1:\n\t\t self.p.positions = [0, 0, 0.0]\n\t\t self.p.velocities = [1, 0, 0]\n\t\telif data.data == 2:\n\t\t self.p.positions = [0, 0, 0.0]\n\t\t self.p.velocities = [0, 1, 0]\n \t# elif data.data == 3:\n\t # \tself.p.positions = [0, 0, 0]\n\t # \tself.p.velocities = [0, 0, 1.0]\n\t\telse:\n\t\t self.p.positions = [1, 1, 0.0]\n\t\t self.p.velocities = [0, 0, 0]\n\t\tself.traj.points = [self.p]\n\t\tself.goal.trajectory = self.traj\n\n\t# send message to the action server\n\t\tself.cli.send_goal(self.goal)\n\n\t# wait for the action server to complete the order\n\t\tself.cli.wait_for_result()\n\n\n\n\n\n\n# # send message to the action server\n# cli.send_goal(goal)\n\n# # wait for the action server to complete the order\n# cli.wait_for_result()\nif __name__ == '__main__':\n rospy.init_node('test')\n CBA_GUI_BASE = BaseMoveCBA(float(sys.argv[1]) if len(sys.argv) > 1 else 0.0)\n CBA_GUI_BASE.listener()","repo_name":"ssteveminq/teaching_social_navigation","sub_path":"navi_functions/classifier_hsr/scripts/omni_actionlib.py","file_name":"omni_actionlib.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39187889856","text":"# Python is a dynamically interpreted language\n# This means the datatype will be set at runtime \n\n#Text Type\n# String\nx = str(\"Universe\") \n\n# Numeric Type\n# Integer\nx = int(20)\n\n#float\nx = float(8.5)\n\n#complex number\nx = complex(1j)\n\n\n# Sequence Type\n# list\nx = list((\"Car\",\"Plane\",\"Tank\",\"Boat\"))\n\n# tuple\nx = tuple((\"Car\",\"Airplane\",\"Tank\",\"Boat\"))\n\n# range\nx = range(6)\n\n\n# Set Types\n# set\nx = set((\"Car\",\"Airplane\",\"Tank\",\"Boat\"))\n\n# frozenset\nx = frozenset((\"Car\",\"Airplane\",\"Tank\",\"Boat\"))\n\n\n# Mapping Type\n# dict\nx = dict(tankname = \"Merkava\", airplane = \"Dornier\")\n\n\n# Boolean Type\n# bool\nx = bool(2)\n\n\n# Binary Types\n# bytes\nx = bytes(128)\n\n# bytearray\nx = bytearray(10)\n\n# memoryview\nx = memoryview(bytes(8))","repo_name":"Sorayal/Coding_Dojo_Python","sub_path":"Practice_1/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16791197505","text":"import pygame\nfrom portal import PortalController\nfrom pygame.sprite import Sprite\nfrom sounds import Sounds\nfrom imagerect import ImageRect\n\n\nclass Pacman(Sprite):\n audio = 0\n yellow = (255, 255, 0)\n\n def __init__(self, screen, maze):\n super().__init__()\n self.screen = screen\n self.maze = maze\n self.dead = False\n self.direction = None\n self.event_map = {pygame.KEYDOWN: self.move, pygame.KEYUP: self.reset_movement}\n self.input_map = {pygame.K_UP: self.move_up, pygame.K_LEFT: self.move_left,\n pygame.K_DOWN: self.move_down, pygame.K_RIGHT: self.move_right,\n pygame.K_q: self.blue_portal, pygame.K_w: self.orange_portal}\n\n\n self.sound_manager = Sounds(sound_files=['pacman-pellet-eat.wav', 'pacman-fruit-eat.wav',\n 'pacman-killed.wav', 'pacman-portal.wav'],\n keys=['eat', 'fruit', 'dead', 'portal'],\n channel=Pacman.audio)\n\n self.death_frames = ImageRect('pacman-death.png', sheet=True, pos_offsets=[(0, 0, 32, 32),\n (32, 0, 32, 32),\n (0, 32, 32, 32),\n (32, 32, 32, 32),\n (0, 64, 32, 32),\n (32, 64, 32, 32)],\n resize=(self.maze.block_size, self.maze.block_size),\n animation_delay=150, repeat=False)\n\n self.pacmanx = ImageRect('pacman-horiz.png', sheet=True, pos_offsets=[(0, 0, 32, 32),\n (32, 0, 32, 32),\n (0, 32, 32, 32),\n (32, 32, 32, 32),\n (0, 64, 32, 32)],\n resize=(self.maze.block_size, self.maze.block_size),\n reversible=True)\n self.pacmany = ImageRect('pacman-vert.png', sheet=True, pos_offsets=[(0, 0, 32, 32),\n (32, 0, 32, 32),\n (0, 32, 32, 32),\n (32, 32, 32, 32),\n (0, 64, 32, 32)],\n resize=(self.maze.block_size, self.maze.block_size),\n reversible=True)\n self.spawn_set = self.maze.player_spawn[1]\n self.flip_mo = {'use_horiz': True, 'h_flip': False, 'v_flip': False}\n self.movement = False\n self.image, self.rect = self.pacmanx.get_image()\n self.portals = PortalController(screen, self, maze)\n\n\n def blue_portal(self):\n self.portals.fire_blue()\n\n def orange_portal(self):\n self.portals.fire_orange()\n\n def respawn(self):\n self.dead = False\n self.image, _ = self.pacmanx.get_image()\n self.death_frames.image_index = 0\n\n def eat(self):\n score = 0\n fruit_count = 0\n ppellet = None\n collision = pygame.sprite.spritecollideany(self, self.maze.pellets)\n if collision:\n collision.kill()\n score += 10\n self.sound_manager.play('eat')\n collision = pygame.sprite.spritecollideany(self, self.maze.fruits)\n if collision:\n collision.kill()\n score += (100 + (fruit_count * 200))\n fruit_count += 1\n self.sound_manager.play('fruit')\n collision = pygame.sprite.spritecollideany(self, self.maze.power_pellets)\n if collision:\n collision.kill()\n score += 50\n ppellet = True\n self.sound_manager.play('eat')\n return score, fruit_count, ppellet\n\n def reset(self):\n self.rect.centerx, self.rect.centery = self.spawn_set\n\n def change_direction(self, event):\n if event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT):\n self.moving = False\n\n def get_nearest_col(self):\n return (self.rect.x - (self.screen.get_width() // 5)) // self.maze.block_size\n\n def get_nearest_row(self):\n return (self.rect.y - (self.screen.get_height() // 12)) // self.maze.block_size\n\n def set_death(self):\n self.sound_manager.play('dead')\n self.dead = True\n self.image, _ = self.death_frames.get_image()\n\n def reset_portals(self):\n self.portals.clear_portals()\n\n def move(self, event):\n if event.key in self.input_map:\n self.input_map[event.key]()\n\n def move_up(self):\n if self.direction != 'u':\n self.direction = 'u'\n if self.flip_mo['v_flip']:\n self.pacmany.flip(False, True)\n self.flip_mo['v_flip'] = False\n self.flip_mo['use_horiz'] = False\n self.moving = True\n\n def move_left(self):\n if self.direction != 'l':\n self.direction = 'l'\n if not self.flip_mo['h_flip']:\n self.pacmanx.flip()\n self.flip_mo['h_flip'] = True\n self.flip_mo['use_horiz'] = True\n self.moving = True\n\n def move_down(self):\n if self.direction != 'd':\n self.direction = 'd'\n if not self.flip_mo['v_flip']:\n self.pacmany.flip(x_bool=False, y_bool=True)\n self.flip_mo['v_flip'] = True\n self.flip_mo['use_horiz'] = False\n self.movement = True\n\n def move_right(self):\n if self.direction != 'r':\n self.direction = 'r'\n if self.flip_mo['h_flip']:\n self.pacmanx.flip()\n self.flip_mo['h_flip'] = False\n self.flip_mo['use_horiz'] = True\n self.movement = True\n\n def reset_movement(self, event):\n if event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT):\n self.movement = False\n\n def blit(self):\n self.portals.blit()\n self.screen.blit(self.image, self.rect)\n","repo_name":"ThePastorOfPurity/Pacman_Portal","sub_path":"pacman.py","file_name":"pacman.py","file_ext":"py","file_size_in_byte":6731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30323549002","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"pychonk\",\n version=\"0.0.4\",\n author=\"Andy Thomas Woods\",\n author_email=\"andytwoods@gmail.com\",\n description=\"ranked disk-space used by each of your installed packages\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/andytwoods/pychonk\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3',\n entry_points={\n \"console_scripts\": [\n \"chonk=src.pychonk:chonk\",\n ]\n },\n)\n","repo_name":"andytwoods/pychonk","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16327320361","text":"# -*- coding: utf-8 -*-\n# -*- Channel Pelisplus -*-\n# -*- Created for Alfa-addon -*-\n# -*- By the Alfa Develop Group -*-\n\nimport sys\nPY3 = False\nif sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int\n\nif PY3:\n import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo\nelse:\n import urlparse # Usamos el nativo de PY2 que es más rápido\n\nimport re, base64\n\nfrom modules import autoplay\nfrom channels import filtertools\nfrom core import httptools\nfrom core import jsontools\nfrom core import scrapertools\nfrom core import servertools\nfrom core import tmdb\nfrom core.item import Item\nfrom platformcode import config, logger\nfrom channelselector import get_thumb\nfrom lib import generictools\n\nIDIOMAS = {'latino': 'LAT', 'castellano': 'CAST', 'subtitulado': 'VOSE'}\nlist_language = list(IDIOMAS.values())\n\nlist_quality = []\n\nlist_servers = [\n 'directo',\n 'vidlox',\n 'fembed',\n 'uqload',\n 'gounlimited',\n 'fastplay',\n 'mixdrop',\n 'mystream'\n ]\n\ncanonical = {\n 'channel': 'pelisplus', \n 'host': config.get_setting(\"current_host\", 'pelisplus', default=''), \n 'host_alt': [\"https://pelisplus.lat\"], \n 'host_black_list': [\"https://home.pelisplus.lat/\", \n \"https://pelisplus.mov/\", \"https://pelisplus.ninja/\", \"https://www.pelisplus.lat/\", \n \"https://www.pelisplus.me/\", \"https://pelisplushd.net/\",\"https://pelisplushd.to/\"], \n 'CF': False, 'CF_test': False, 'alfa_s': True\n }\nhost = canonical['host'] or canonical['host_alt'][0]\npatron_domain = '(?:http.*\\:)?\\/\\/(?:.*ww[^\\.]*)?\\.?(?:[^\\.]+\\.)?([\\w|\\-]+\\.\\w+)(?:\\/|\\?|$)'\ndomain = scrapertools.find_single_match(host, patron_domain)\n\n\ndef mainlist(item):\n logger.info()\n \n autoplay.init(item.channel, list_servers, list_quality)\n\n itemlist = list()\n\n itemlist.append(Item(channel=item.channel, title=\"Peliculas\", action=\"sub_menu\", url_todas = \"listado-peliculas\", \n url_populares = \"/tendencias/dia\",\n thumbnail=get_thumb('movies', auto=True)))\n\n itemlist.append(Item(channel=item.channel, title=\"Series\", action=\"sub_menu\", url_todas = \"listado-series\",\n thumbnail=get_thumb('tvshows', auto=True)))\n\n itemlist.append(Item(channel=item.channel, title=\"Anime\", action=\"sub_menu\", url_todas =\"ver-animes\",\n thumbnail=get_thumb('anime', auto=True)))\n\n itemlist.append(Item(channel=item.channel, title=\"Doramas\", action=\"list_all\", url=host + \"doramas\",\n content=\"serie\", thumbnail=get_thumb('doramas', auto=True)))\n\n itemlist.append(Item(channel=item.channel, title=\"Buscar\", action=\"search\", url=host + '?s=',\n thumbnail=get_thumb('search', auto=True)))\n\n autoplay.show_option(item.channel, itemlist)\n\n return itemlist\n\n\ndef sub_menu(item):\n logger.info()\n itemlist = list()\n\n if item.title.lower() == \"anime\":\n content = item.title.lower()\n item.title = \"Animes\"\n else:\n content = item.title.lower()[:-1]\n\n itemlist.append(Item(channel=item.channel, title=\"Todas\", action=\"list_all\", url=host + item.url_todas,\n thumbnail=get_thumb('all', auto=True)))\n\n if item.title.lower() == \"peliculas\":\n itemlist.append(Item(channel=item.channel, title=\"Ultimos populares\", action=\"list_all\",\n url=host + item.url_todas + item.url_populares,\n thumbnail=get_thumb('more watched', auto=True), type=content))\n itemlist.append(Item(channel=item.channel, title=\"Peliculas estreno\", action=\"list_all\",\n url=host + item.url_todas + '/estrenos',\n thumbnail=get_thumb('more watched', auto=True), type=content))\n itemlist.append(Item(channel=item.channel, title=\"Generos\", action=\"section\",\n thumbnail=get_thumb('genres', auto=True), type=content))\n elif item.title.lower() == \"series\":\n itemlist.append(Item(channel=item.channel, title=\"Ultimos estrenos\", action=\"list_all\",\n url=host + 'series-de-estreno', thumbnail=get_thumb('more watched', auto=True), type=content))\n itemlist.append(Item(channel=item.channel, title=\"Mas Vistas\", action=\"list_all\",\n url=host + 'series-populares', thumbnail=get_thumb('more watched', auto=True), type=content))\n return itemlist\n\n\ndef list_all(item):\n logger.info()\n itemlist = list()\n\n data = httptools.downloadpage(item.url).data\n bloque = scrapertools.find_single_match(data, '(?is)card-body.*?Page navigation example')\n patron = '(?is)')\n #next_page = scrapertools.find_single_match(data, '.*?]*href=\"([^\"]+)\"')\n next_page = scrapertools.find_single_match(data, '.*?>\", url=next_page, action='list_all'))\n except:\n pass\n\n return itemlist\n\n\ndef seasons(item):\n logger.info()\n\n itemlist = list()\n data = httptools.downloadpage(item.url).data\n patron = 'data-toggle=\"tab\"[^>]*.?[^<]+([^<])+'\n infoLabels = item.infoLabels\n matches = scrapertools.find_multiple_matches(data, patron)\n \n for title in matches:\n title = \"Temporada \" + title\n infoLabels[\"season\"] = scrapertools.find_single_match(title, \"Temporada (\\d+)\")\n itemlist.append(Item(channel=item.channel, title=title, url=item.url, action='episodesxseasons',\n infoLabels=infoLabels, contentType='season'))\n tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)\n\n if config.get_videolibrary_support() and len(itemlist) > 0:\n itemlist.append(\n Item(channel=item.channel, title='[COLOR yellow]Añadir esta serie a la videoteca[/COLOR]', url=item.url,\n action=\"add_serie_to_library\", extra=\"episodios\", contentSerieName=item.contentSerieName))\n\n return itemlist\n\n\ndef episodios(item):\n logger.info()\n itemlist = []\n templist = seasons(item)\n for tempitem in templist:\n itemlist += episodesxseasons(tempitem)\n\n return itemlist\n\n\ndef episodesxseasons(item):\n logger.info()\n data = httptools.downloadpage(item.url).data\n itemlist = list()\n infoLabels = item.infoLabels\n season = infoLabels[\"season\"]\n patron = '(%sepisodio.*?temporada-%s[^\"]+).*?' %(host, item.contentSeason)\n patron += 'btn-block\">([^<]+)'\n matches = scrapertools.find_multiple_matches(data, patron)\n if not matches:\n patron = '(%sepisodio/.*?%sx[^\"]+).*?' %(host, item.contentSeason)\n patron += 'btn-block\">([^<]+)'\n matches = scrapertools.find_multiple_matches(data, patron)\n if not matches:\n return itemlist\n\n for url, episodio in matches:\n epi_num = scrapertools.find_single_match(episodio, \"E(\\d+)\")\n epi_name = scrapertools.find_single_match(episodio, \":([^$]+)\")\n infoLabels['episode'] = epi_num\n title = '%sx%s - %s' % (season, epi_num, epi_name.strip())\n\n itemlist.append(Item(channel=item.channel, title=title, url=url, action='findvideos', infoLabels=infoLabels, contentType='episode'))\n\n tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)\n\n return itemlist\n\n\ndef section(item):\n logger.info()\n itemlist = list()\n data = httptools.downloadpage(host).data\n bloque = scrapertools.find_single_match(data, \"Generos(.*?)side-nav-header\")\n patron = ''\n patron += '([^<]+)'\n matches = scrapertools.find_multiple_matches(bloque, patron)\n for url, title in matches:\n itemlist.append(Item(channel=item.channel, url=host + url, title=title, action='list_all', type=item.type))\n\n return itemlist\n\n\ndef findvideos(item):\n logger.info()\n\n itemlist = list()\n\n data = httptools.downloadpage(item.url, forced_proxy_opt='ProxyCF', canonical=canonical)\n \n json = scrapertools.find_single_match(data.data, '(?is)type=\"application/json\">(.*?)')\n \n \n json1 = jsontools.load(json)[\"props\"][\"pageProps\"][\"thisMovie\"][\"videos\"]\n\n for idioma in json1:\n for videos in json1[idioma]:\n url = videos[\"result\"]\n \n if u\"player.php\" in url:\n data = httptools.downloadpage(url).data\n url = scrapertools.find_single_match(data, \"var url = '([^']+)'\")\n itemlist.append(Item(channel=item.channel, title='%s [%s]', url=url, action='play', language=idioma,\n infoLabels=item.infoLabels))\n \n\n itemlist = servertools.get_servers_itemlist(itemlist, lambda i: i.title % (i.server.capitalize(), i.language))\n\n # Requerido para FilterTools\n\n itemlist = filtertools.get_links(itemlist, item, list_language)\n\n # Requerido para AutoPlay\n\n autoplay.start(itemlist, item)\n\n if item.contentType == 'movie':\n if config.get_videolibrary_support() and len(itemlist) > 0 and item.extra != 'findvideos':\n itemlist.append(Item(channel=item.channel,\n title='[COLOR yellow]Añadir esta pelicula a la videoteca[/COLOR]',\n url=item.url,\n action=\"add_pelicula_to_library\",\n extra=\"findvideos\",\n contentTitle=item.contentTitle))\n return itemlist\n\n\ndef play(item):\n logger.info()\n if \"cinestart\" in item.url:\n id = scrapertools.find_single_match(item.url, \"id=(\\w+)\")\n token = scrapertools.find_single_match(item.url, \"token=(\\w+)\")\n post = {\"id\" : id, \"token\" : token}\n dd = httptools.downloadpage(\"https://cinestart.streams3.com/r.php\", post = post, allow_redirect=False).url\n v = scrapertools.find_single_match(dd, \"t=(\\w+)\")\n dd = httptools.downloadpage(\"https://cinestart.net/vr.php?v=%s\" %v).json\n item.url = dd[\"file\"]\n if \"apialfa.tomatomatela.com\" in item.url:\n data = httptools.downloadpage(item.url).data\n hostx = \"https://apialfa.tomatomatela.com/ir/\"\n item.url = hostx + scrapertools.find_single_match(data, 'id=\"link\" href=\"([^\"]+)')\n data = httptools.downloadpage(item.url).data\n xvalue = scrapertools.find_single_match(data, 'name=\"url\" value=\"([^\"]+)')\n post = {\"url\" : xvalue}\n item.url = httptools.downloadpage(hostx + \"rd.php\", follow_redirects=False, post=post).headers.get(\"location\", \"\")\n data = httptools.downloadpage(\"https:\" + item.url).data\n xvalue = scrapertools.find_single_match(data, 'name=\"url\" value=\"([^\"]+)')\n post = {\"url\" : xvalue}\n item.url = httptools.downloadpage(hostx + \"redirect_ddh.php\", follow_redirects=False, post=post).headers.get(\"location\", \"\")\n hash = scrapertools.find_single_match(item.url,\"#(\\w+)\")\n file = httptools.downloadpage(\"https://tomatomatela.com/details.php?v=%s\" %hash).json\n item.url = file[\"file\"]\n dd = httptools.downloadpage(item.url, only_headers=True).data\n return [item]\n\n\ndef search(item, texto):\n logger.info()\n texto = texto.replace(\" \", \"+\")\n item.url += texto\n\n try:\n if texto != '':\n return list_all(item)\n else:\n return []\n except:\n import sys\n for line in sys.exc_info():\n logger.error(\"%s\" % line)\n return []\n\n\ndef newest(categoria):\n logger.info()\n\n item = Item()\n try:\n if categoria in ['peliculas', 'latino']:\n item.url = host + 'peliculas/estrenos'\n elif categoria == 'infantiles':\n item.url = host + 'generos/animacion/'\n elif categoria == 'terror':\n item.url = host + 'generos/terror/'\n itemlist = list_all(item)\n if itemlist[-1].title == 'Siguiente >>':\n itemlist.pop()\n except:\n import sys\n for line in sys.exc_info():\n logger.error(\"{0}\".format(line))\n return []\n\n return itemlist\n","repo_name":"alfa-addon/addon","sub_path":"plugin.video.alfa/channels/pelisplus.py","file_name":"pelisplus.py","file_ext":"py","file_size_in_byte":13544,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"85"} +{"seq_id":"34988673508","text":"import requests\n\nURL = 'http://webhacking.kr/challenge/bonus/bonus-1/index.php?no={}'\nPHPSESSID = 'SESSION_HERE'\n\n\ndef ask(no):\n url = URL.format(no)\n r = requests.get(url, cookies={\n \"PHPSESSID\": PHPSESSID\n })\n return 'True' in r.text\n\n\ndef binsearch(query, minval, maxval):\n while minval < maxval:\n m = (minval + maxval) >> 1\n if ask(query.format(m)):\n minval = m+1\n else:\n maxval = m\n return minval - 1\n\nfor column in ('id', 'pw'):\n length = binsearch('2 and (select length({column})>={{}})'.format(column=column), 0, 100)\n\n print('{} length is {}'.format(column, length))\n\n acc = ''\n for idx in range(1, length+1):\n c = binsearch('2 and (select ascii(substr({column},{idx},1))>={{}})'.format(\n column=column,\n idx=idx\n ), 0, 128)\n acc += chr(c)\n\n print(acc)\n","repo_name":"Qwaz/solved-hacking-problem","sub_path":"webhacking.kr/21/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"85"} +{"seq_id":"3237890583","text":"\"\"\"Various validators\"\"\"\n\n\ndef validate_integer(\n arg_name, arg_value, min_value=None, max_value=None,\n custom_min_message=None, custom_max_message=None\n):\n \"\"\"Validates that `arg_value` is an integer, and optionally falls\n within specified bounds. A custom override error message can be\n provided when min/max bounds are exceeded.\n \"\"\"\n if not isinstance(arg_value, int):\n raise TypeError(f'{arg_name} must be an integer.')\n\n if min_value is not None and arg_value < min_value:\n if custom_min_message is not None:\n raise ValueError(custom_min_message)\n raise ValueError(f'{arg_name} must be greater than {min_value}.')\n if max_value is not None and arg_value > max_value:\n if custom_max_message is not None:\n raise ValueError(custom_max_message)\n raise ValueError(f'{arg_name} must be less than {max_value}.')\n","repo_name":"zkkamir/python_deep_dive","sub_path":"part4_projects/project3/course_solution/app/utils/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8363381783","text":"from flask_jwt_extended import (\n JWTManager, jwt_required, create_access_token,\n get_jwt_identity\n)\nfrom security.blacklist import blacklist\n\nclass UserObject:\n def __init__(self, username, roles):\n self.username = username\n self.roles = roles\n\njwt = JWTManager()\ndef initialize_Security(app):\n jwt.init_app(app)\n \n@jwt.user_claims_loader\ndef add_claims_to_access_token(user):\n return {'roles': user.roles}\n\n@jwt.user_loader_callback_loader\ndef user_loader_callback(identity):\n if identity not in users_to_roles:\n return None\n\n return UserObject(\n username=identity,\n roles=users_to_roles[identity]\n )\n \n@jwt.user_identity_loader\ndef user_identity_lookup(user):\n return user.username\n\n@jwt.user_loader_error_loader\ndef custom_user_loader_error(identity):\n ret = {\n \"msg\": \"User {} not found\".format(identity)\n }\n return ret \n\n\n# Logout \n@jwt.token_in_blacklist_loader\ndef check_if_token_in_blacklist(decrypted_token):\n jti = decrypted_token['jti']\n return jti in blacklist","repo_name":"scriptkid23/deploying-structure-flask-react","sub_path":"security/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21556650775","text":"import sys\n\nNOW_CHANNEL = 100\nCHANNEL_MAX = 1000000 # 500,000 가 최대지만, 그보다 높은 수가 나올 수 있기 떄문에 1,000,000을 최대로 한다.\n\ndef check_makable(N, broken_list):\n str_N = str(N)\n\n # N 을 구성하는 모든 수가 가능한 리스트에 있는지 확인.\n for n in str_N:\n if broken_list[int(n)]:\n return False\n \n return True\n\nif __name__ == \"__main__\":\n # For fast I / O. T mean test case number.\n N = int(sys.stdin.readline().rstrip())\n M = int(sys.stdin.readline().rstrip())\n broken_list = [False for _ in range(0, 10)]\n\n if M != 0:\n inp = sys.stdin.readline().rstrip().split(\" \")\n for i in inp:\n broken_list[int(i)] = True\n\n if N >= 10:\n low_bound = 10 ** (len(str(N)) - 2)\n upper_bound = 10 ** len(str(N))\n else:\n low_bound = 0\n upper_bound = 100\n \n # Low, Upper bound 를 쓰는 방식은 오류가 있다고 한다. 이유는 왤까?\n print(\" ==== \")\n print(low_bound)\n print(upper_bound)\n print(N)\n print(\" ==== \")\n\n min_answer = abs(100 - N)\n\n for n in range(0, CHANNEL_MAX):\n if check_makable(n, broken_list):\n # 만약 만들 수 있는 숫자라면 버튼 누르는 횟수 계산.\n answer = len(str(n)) + abs(n - N)\n if answer < min_answer:\n min_answer = answer\n\n print(min_answer)\n \n\n# 이하는 실패했던 코드들.\n\nimport sys\n\nNOW_CHANNEL = 100\nCHANNEL_MAX = 500000\n'''\n에러인 경우는 아래가 있다.\n1. digit 에서 차이가 나는 경우.\n ex ) 1555 [0, 1, 3, 4, 5, 6, 7, 9] => 888 과 2222를 통해 비교 하면 됨.\n ex ) 162 [0, 1, 3, 4, 5, 6, 7, 8, 9] => 22 랑 222를 통해 비교 하면 됨.\n2. + 와 - 만 누르는게 더 빠른 경우\n ex ) 101 같은 경우\n3. 0에서 시작 혹은 100에서 시작해서 내렸다가 올렸다 하는게 더 빠른 경우.\n ex ) 10 [1, 2, 3, 4, 5, 6, 7, 8, 9] => 0 에서 시작 혹은 100에서 시작.\n4. 버튼을 모두 쓰거나 모두 못쓰는 경우.\n'''\n\n\nif __name__ == \"__main__\":\n # For fast I / O. T mean test case number.\n N = int(sys.stdin.readline().rstrip())\n M = int(sys.stdin.readline().rstrip())\n avail_list = [i for i in range(0, 10)]\n if M != 0:\n inp = sys.stdin.readline().rstrip().split(\" \")\n else:\n inp = []\n\n for i in range(0, len(inp)):\n del avail_list[avail_list.index(int(inp[i]))]\n\n only_plus_minus = N - NOW_CHANNEL if N > NOW_CHANNEL else NOW_CHANNEL - N\n\n if M == 10:\n print(only_plus_minus)\n elif M == 0:\n print(len(str(N)))\n elif N == 100:\n print(0)\n else:\n # 사용 가능한 숫자로 만든 조합중에서 가장 차이가 적은걸 쓰면 될 것 같다.\n dec_all_list = []\n dec_list = [[[str(a)] for a in avail_list]]\n dec_all_list = [str(a) for a in avail_list]\n\n n = 1 # n 은 n + 1의 자릿수를 의미한다.\n while n < len(str(N)) + 1:\n # 사용 가능한 숫자로 조합을 만듬.\n dec_list.append([[] for _ in avail_list])\n\n for i in range(0, len(avail_list)):\n for j in range(0, len(avail_list)):\n dec_list[n][i] += [str(avail_list[i]) + contents for contents in dec_list[n-1][j]]\n dec_all_list += dec_list[n][i]\n n += 1\n \n # 가능성 있는 숫자를 찾아낸다. \n # Upper bound 를 쓰면 더 빠르게 찾을 수 있긴 하지만, 50만개는 적은 수라 그대로 둬도 상관 없을듯.\n pivot = 0\n for i in range(0, len(dec_all_list)):\n if int(dec_all_list[i]) > N:\n pivot = i\n break\n\n # 같은 자릿수와 한 자릿수 더 작은 수를 비교.\n digit_same_num = int(dec_all_list[pivot]) # Larger number then given N.\n digit_same = len(dec_all_list[pivot])\n if pivot != 0:\n digit_small_num = int(dec_all_list[pivot - 1]) # Smaller number then given N.\n digit_small = len(dec_all_list[pivot - 1])\n \n btn_touch1 = digit_same\n btn_touch1 += N - digit_same_num if N > digit_same_num else digit_same_num - N\n\n btn_touch2 = digit_small\n btn_touch2 += N - digit_small_num if N > digit_small_num else digit_small_num - N\n if btn_touch1 < btn_touch2:\n print(btn_touch1 if btn_touch1 < only_plus_minus else only_plus_minus)\n else:\n print(btn_touch2 if btn_touch2 < only_plus_minus else only_plus_minus)\n else:\n btn_touch = digit_sameㅉ\n btn_touch += N - digit_same_num if N > digit_same_num else digit_same_num - N\n print(btn_touch if btn_touch < only_plus_minus else only_plus_minus)","repo_name":"sshrik/algo-study","sub_path":"BaekJoon/success/1000 ~ 1500/bk1107.py","file_name":"bk1107.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19683864635","text":"##\n## Voting Classifier - applies very different\n## training algorithms to make predictions.\n## Each algorithm will have an output that tells\n## which class a test instance belongs to. The class\n## that gets the most votes is the ensemble's prediction.\n## This majority-vote classifier is called a\n## hard voting classifier\n##\n\n## Let's try voting classifier on moons data set\nfrom sklearn.datasets import make_moons\nX, y = make_moons(n_samples=600, noise=0.30, random_state=42)\n\n## Let's split the moons data set into training\n## data set and test data set, test_size defaults to 0.25\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n\n## We will use three diverse classifiers for our\n## voting classifier, they are\n## 1) Logistic Regression\n## 2) RandomForestClassifier\n## 3) Support Vector Machine\nfrom sklearn.ensemble import RandomForestClassifier, VotingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\n\nvoting_classifier = VotingClassifier(\n estimators=[\n (\"lr\", LogisticRegression(random_state=42)),\n (\"rfc\", RandomForestClassifier(random_state=42)),\n (\"svc\", SVC(random_state=42))\n ]\n)\n## Let's train our Voting Classifier object using our training\n## data set\nvoting_classifier.fit(X_train, y_train)\n\n## We can now test our trained Voting Classifier object using\n## our test data set. But before that, let's see the accuracy\n## of individual classifiers. Accuracy is given by score() function.\n## named_estimators_ outputs a dictionary of the cloned estimators\nprint(\"\")\nprint(\"individual classifier scores: \")\nfor classifier_name, classifier in voting_classifier.named_estimators_.items():\n print(classifier_name, \"=\", classifier.score(X_test,y_test))\n## Let's print the overall accuracy of the voting classifier object:\nprint(\"voting classifier score:\")\nstr = f\"{voting_classifier.score(X_test,y_test)}\"\nprint(str)\nprint(\"\")\n## Most of the time, voting classifier outperforms individual classifiers.\n## But for n_samples = 600 or higher, radom forest outperforms the rest\n\n\n## When predict() method is called, voting classifier object performs\n## hard voting and displays the class that was predicted by all or most\n## of the classifiers\nstr = voting_classifier.predict(X_test[:1])\nprint(\"voting classifer prediction = \", str)\n## display individual votes:\nstr = [clf.predict(X_test[:1]) for clf in voting_classifier.estimators_]\nprint(\"individual votes: \",str)\n## This means that 2 out of 3 classifiers predicted that X_test belongs to\n## class 1 of y_test whatever that is.\n\n","repo_name":"boyfriendnibluefairy/python_snippets_basics","sub_path":"ensemble_learning/01_voting_classifier_hard_voting.py","file_name":"01_voting_classifier_hard_voting.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5669201521","text":"# 동전 더하기\n## 서로 다른 동전 n 종류로 금액 k를 완성시키기 위해 필요한 동전 개수의 최솟값을 구하는 프로그램을 작성하세요.\n## 단, 2번째부터 주어지는 동전의 가치값은 항상 바로 전 동전의 가치의 배수로 주어집니다.\n### 테크닉 : 그리디 알고리즘\n\nn, k = input().split()\nkind, cost = int(n), int(k)\n\ncoin = []\nfor i in range(kind):\n get = int(input())\n coin.append(get)\n\nresult = 0\nnow = kind - 1\n\n# 큰 동전부터 처리하는 그리디 적용\nwhile cost != 0:\n num = cost // coin[now]\n cost = cost - num*coin[now]\n result += num\n now -= 1\n\nprint(result)","repo_name":"lungnahahd/Python_Prac","sub_path":"Code_Tree/IM/Greedy/CoinPlus.py","file_name":"CoinPlus.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"72509452757","text":"import os\nimport cv2\nimport numpy as np\nimport mediapipe as mp\nimport time\n\n# Initialize MediaPipe Hands\nmp_hands = mp.solutions.hands\nhands = mp_hands.Hands(static_image_mode=False, max_num_hands=1, min_detection_confidence=0.5)\n\n# Define directories and actions\ndirectory = \"Image/\"\nactions = [\"peace\", \"thumbs up\", \"stop\"]\n\n# Initialize empty lists for keypoints and labels\nkeypoints = []\nlabels = []\nwait_time = 5\n# Loop over actions and images\nfor action in actions:\n action_dir = os.path.join(directory, action)\n image_files = sorted(os.listdir(action_dir))\n\n for image_file in image_files:\n image_path = os.path.join(action_dir, image_file)\n\n # Read and preprocess the image\n image = cv2.imread(image_path)\n image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n \n # cv2.imshow(\"hands\", image)\n\n # Process the image with MediaPipe Hands\n results = hands.process(image_rgb)\n\n # Check if hand landmarks were detected\n if results.multi_hand_landmarks:\n # Extract the keypoints for the first detected hand\n annotated_image = image.copy()\n hand_landmarks = results.multi_hand_landmarks[0].landmark\n cv2.imshow(\"hands\", image)\n \n wait_time = 1\n\n # Store the keypoints in a list\n landmark_list = np.array([(lm.x, lm.y) for lm in hand_landmarks]).flatten()\n keypoints.append(landmark_list)\n labels.append(action)\n\n if cv2.waitKey(wait_time) == ord('q'):\n break\n\n# Convert the keypoints and labels to NumPy arrays\nkeypoints_array = np.array(keypoints)\nlabels_array = np.array(labels)\n\n# Print the shape of the keypoints and labels arrays\nprint(\"Keypoints array shape:\", type(keypoints_array))\nprint(\"Labels array shape:\", type(labels_array))\n\n#save keypoints in a file\ntry:\n os.makedirs(\"keypoints_data\")\nexcept:\n pass\nfilename = \"keypoints_data/\"\nnp.save(filename+\"keypoints_data.npy\", keypoints_array)\nnp.save(filename+\"labels.npy\", labels_array)\n\nkey = np.load(filename+\"keypoints_data.npy\")\nprint(key.shape)\nlabels = np.load(filename+\"labels.npy\")\nprint(labels.shape)\n\n# Release resources\nhands.close()\n","repo_name":"fawizzy/hand_gesture_recognition","sub_path":"collect_keypoints_data.py","file_name":"collect_keypoints_data.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39491878840","text":"import torch\nimport torch.optim as optim\nfrom arxiv_learning.nn.softnormalization import SoftNormalization\nfrom arxiv_learning.nn.scheduler import WarmupLinearSchedule\nfrom .head import Head\n\nclass BYOLHead(Head):\n def __init__(self, model, width=512, output_dim=64, tau=0.05):\n from copy import deepcopy\n super().__init__(model)\n self.width = width\n self.output_dim = output_dim\n self.tau = tau\n self.eta = 512\n self.output = torch.nn.Linear(self.width, self.output_dim, bias=False)\n self.mlp1 = torch.nn.Linear(self.output_dim, 1024, bias=False)\n self.mlp2 = torch.nn.Linear(1024, self.output_dim, bias=False)\n self.mlpbn = torch.nn.BatchNorm1d(1024)\n self.normalizer = torch.nn.BatchNorm1d(self.width)\n print(list(self.named_parameters()))\n self.optimizer = optim.Adam(self.parameters(), lr=0.01)\n # self.optimizer = arxiv_learning.nn.lars.LARS(self.parameters(), lr=3.2, eta=1e-3, )\n \n self.scheduler = None #WarmupLinearSchedule(self.optimizer, 500, 20 * 10000)\n self.target_model = deepcopy(model)\n self.target_output = torch.nn.Linear(self.width, self.output_dim, bias=False)\n self.target_normalizer = torch.nn.BatchNorm1d(self.width, track_running_stats=False)#.eval()\n for layer in self.target_model.modules():\n if hasattr(layer, 'reset_parameters'):\n print(\"reset\")\n layer.reset_parameters()\n\n for param in self.target_model.parameters():\n param.requires_grad = False\n for param in self.target_output.parameters():\n param.requires_grad = False\n for param in self.target_normalizer.parameters():\n param.requires_grad = False\n def reset_metrics(self):\n self.example_cnt = 0\n # self.running_accuracy = 0\n self.running_loss = 0\n \n\n def metrics(self):\n return {\n \"Number-Examples\": self.example_cnt,\n \"MSE-Loss\": round(self.running_loss / (1 if self.example_cnt < 1 else self.example_cnt), 4),\n \"Mean-Variance\": self.normalizer.running_var.mean(),\n # \"Accuracy\": round(self.running_accuracy / (1 if self.example_cnt < 1 else self.example_cnt), 4)\n }\n\n def train(self, par=True):\n print(\"set BYOL Head to Train=\", par)\n print(self.target_model.training, self.model.training, self.output.training, self.target_output.training)\n ret = super().train(par)\n # self.target_model = self.target_model.train(False)\n # self.target_normalizer = self.target_normalizer.train(True)\n # self.target_output = self.target_output.train(par)\n print(self.target_model.training, self.model.training, self.output.training, self.target_output.training)\n return ret\n\n def uniformize(self, x2, eta=512):\n # eta = 512\n tau = 1\n before = None\n for i in range(4):\n x2 = torch.autograd.Variable(x2, requires_grad=True)\n # print(x2.requires_grad)\n K = 2.0 - 2 * torch.matmul(x2, x2.transpose(0, 1))\n # print(K.requires_grad)\n # K = 2.0 - x2.dot(x2.transpose(0, 1))\n K = torch.exp(-tau * K)\n loss = 1.0 / (x2.shape[0]**2) * K.sum()\n # loss = -torch.log()\n # print(loss.requires_grad)\n if before is None:\n before = loss\n if not K.requires_grad:\n return x2\n loss.backward(retain_graph=True)\n # print(\"gradnorm:\", torch.norm(x2.grad))\n x2 = x2 - eta * x2.grad\n norm = torch.norm(x2, dim=1, keepdim=True) + 1e-8\n x2 = x2.div(norm.expand_as(x2))\n x2 = x2.detach()\n\n K = 2.0 - 2 * torch.matmul(x2, x2.transpose(0, 1))\n # print(K.requires_grad)\n # K = 2.0 - x2.dot(x2.transpose(0, 1))\n K = torch.exp(-tau * K)\n loss = 1.0 / (x2.shape[0]**2) * K.sum()\n print(\"\\nLoss{} -> {}\".format(before, loss))\n\n return x2.detach()\n def backward(self):\n with torch.autograd.detect_anomaly():\n self.target.backward()\n clip_grad_norm_(self.model.parameters(), 16.0)\n self.optimizer.step()\n self.optimizer.zero_grad()\n if self.scheduler:\n self.scheduler.step()\n\n def forward(self, data):\n # MOVING AVERAGE\n rho = 0.995\n if self.model.training:\n for (i,u), (j,v) in zip(self.target_model.named_parameters(), self.model.named_parameters()):\n if i!=j:\n print(i, j)\n u.data = rho * u.data + (1.0 - rho) * v.data.detach()\n for u, v in zip(self.target_output.parameters(), self.output.parameters()):\n u.data = rho * u.data + (1.0 - rho) * v.data.detach()\n for u, v in zip(self.target_normalizer.parameters(), self.normalizer.parameters()):\n u.data = rho * u.data + (1.0 - rho) * v.data.detach()\n\n # INFERENCE\n x = self.model(data)\n x2 = self.target_model(data)\n # print(x.shape[0]/4096.0)\n # x = self.normalizer(x)\n # x2 = self.target_normalizer(x2)\n\n if hasattr(data, \"batch\"):\n emb = scatter_mean(x, data.batch, dim=0)\n emb2 = scatter_mean(x2, data.batch, dim=0)\n else:\n emb = x.mean(dim=0, keepdim=True)\n emb2 = x2.mean(dim=0, keepdim=True)\n\n\n # PROJECTION \n emb = self.output(emb)\n emb2 = self.target_output(emb2)\n\n svs = np.linalg.svd(emb.detach().cpu().numpy(), compute_uv=False)\n # print(\"\\n\",np.sum(svs / svs[0]))\n\n # PREDICTION\n emb = self.mlp1(torch.nn.functional.selu(emb))\n emb = self.mlp2(torch.nn.functional.selu(self.mlpbn(emb)))\n\n\n # emb = self.normalizer(emb)\n # emb2 = self.target_normalizer(emb2)\n\n norm = torch.norm(emb, dim=1, keepdim=True) + 1e-8\n norm2 = torch.norm(emb2, dim=1, keepdim=True) + 1e-8\n \n emb = emb.div(norm.expand_as(emb))\n emb2 = emb2.div(norm2.expand_as(emb2))\n\n emb2 = emb2.detach()\n emb2 = self.uniformize(emb2, eta=self.eta)\n if self.training:\n self.eta *= 1.0 # 0.9995\n batch_size = data.num_graphs // 2\n\n emb = emb.view(batch_size, 2, -1)\n emb2 = emb2.view(batch_size, 2, -1)\n\n out11 = emb[:, 0, :]\n out21 = emb2[:, 1, :]\n out12 = emb[:, 1, :]\n out22 = emb2[:, 0, :]\n\n sim1 = torch.bmm(out11.view(-1, 1, self.output_dim),\n out21.view(-1, self.output_dim, 1)).view(-1)\n sim2 = torch.bmm(out12.view(-1, 1, self.output_dim),\n out22.view(-1, self.output_dim, 1)).view(-1)\n loss = (-2 * sim1 + -2 * sim2).mean()\n # loss = torch.mean((diff1 * diff1).sum(dim=1)) + torch.mean((diff2 * diff2).sum(dim=1))\n actual_batch_size = out11.shape[0] * 2\n self.running_loss += loss.item() * actual_batch_size\n self.example_cnt += actual_batch_size\n self.target = loss\n\n return emb","repo_name":"Whadup/arxiv_learning","sub_path":"arxiv_learning/nn/heads/byol.py","file_name":"byol.py","file_ext":"py","file_size_in_byte":7164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"28574123708","text":"import vtkmodules.vtkRenderingOpenGL2\nimport vtkmodules.vtkInteractionStyle\n\nfrom vtkmodules.vtkFiltersCore import vtkFeatureEdges\nfrom vtkmodules.vtkFiltersGeneral import vtkOBBTree\nfrom vtkmodules.vtkFiltersHybrid import vtkRenderLargeImage\nfrom vtkmodules.vtkCommonColor import vtkNamedColors\nfrom vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera\nfrom vtkmodules.vtkFiltersSources import vtkSphereSource\nfrom vtkmodules.vtkCommonCore import vtkPoints\nfrom vtkmodules.vtkCommonDataModel import (\n vtkCellArray,\n vtkPolyData,\n vtkPolyLine\n)\nfrom vtkmodules.vtkRenderingCore import (\n vtkRenderWindow,\n vtkRenderWindowInteractor,\n vtkRenderer,\n vtkPolyDataMapper,\n vtkActor,\n vtkTexture,\n vtkSkybox,\n vtkCoordinate,\n vtkWindowToImageFilter,\n vtkCamera\n)\nfrom vtkmodules.vtkIOGeometry import (\n vtkOBJReader\n)\nfrom vtkmodules.vtkIOImage import (\n vtkPNGReader,\n vtkPNGWriter,\n vtkHDRReader,\n vtkImageReader2Factory,\n vtkPNGWriter\n)\n\nfrom pathlib import Path\nfrom paths import (\n PBR,\n OUTPUT_IMAGES,\n OUTPUT_LABELS\n)\nimport camera_positioning\nimport visualization as vis\nimport numpy as np\nimport common_math\nimport math\nfrom typing import (\n Sequence\n)\nfrom typing import Tuple, List, Sequence\nfrom time import sleep\n\n\ncolors = vtkNamedColors()\n\n\ndef read_equirectangular_file(fn_path: Path) -> vtkTexture:\n \"\"\"\n Read an equirectangular environment file and convert to a texture.\n\n :param fn_path: The equirectangular file path.\n :return: The texture.\n \"\"\"\n texture = vtkTexture()\n\n suffix = fn_path.suffix.lower()\n if suffix in ['.jpeg', '.jpg', '.png']:\n reader_factory = vtkImageReader2Factory()\n img_reader = reader_factory.CreateImageReader2(str(fn_path))\n img_reader.SetFileName(str(fn_path))\n\n texture.SetInputConnection(img_reader.GetOutputPort(0))\n\n else:\n reader = vtkHDRReader()\n extensions = reader.GetFileExtensions()\n # Check the image can be read.\n if not reader.CanReadFile(str(fn_path)):\n print('CanReadFile failed for ', fn_path)\n return None\n if suffix not in extensions:\n print('Unable to read this file extension: ', suffix)\n return None\n reader.SetFileName(str(fn_path.resolve()))\n reader.Update()\n\n texture.SetColorModeToDirectScalars()\n texture.SetInputConnection(reader.GetOutputPort())\n\n texture.MipmapOn()\n texture.InterpolateOn()\n\n return texture\n\n\ndef getVTKMapper(objPath: str) -> vtkPolyDataMapper:\n objReader = vtkOBJReader()\n objReader.SetFileName(objPath)\n objReader.Update()\n\n mapper = vtkPolyDataMapper()\n mapper.SetInputConnection(objReader.GetOutputPort())\n return mapper\n\n\ndef getVTKTexture(imgPath: str) -> vtkTexture:\n imgReader = vtkPNGReader()\n imgReader.SetFileName(imgPath)\n imgReader.Update()\n\n texture = vtkTexture()\n texture.UseSRGBColorSpaceOn()\n texture.InterpolateOn()\n texture.SetInputConnection(imgReader.GetOutputPort())\n\n imgReader.CloseFile()\n\n return texture\n\n\ndef getVTKActorPBR(mapper: vtkPolyDataMapper, albedo: vtkTexture, ORM: vtkTexture, normal: vtkTexture) -> vtkActor:\n actor = vtkActor()\n actor.SetMapper(mapper)\n actor.GetProperty().SetInterpolationToPBR()\n \n setPBR(actor, 1.0, 1.0, 1.0)\n actor.GetProperty().SetColor(colors.GetColor3d('White'))\n\n actor.GetProperty().SetBaseColorTexture(albedo)\n # actor.GetProperty().SetORMTexture(material)\n actor.GetProperty().SetNormalTexture(normal)\n\n return actor\n\n\ndef setPBR(actor: vtkActor, baseIOR: float, metallic: float, roughness: float) -> None:\n actor.GetProperty().SetBaseIOR(baseIOR)\n actor.GetProperty().SetMetallic(metallic)\n actor.GetProperty().SetRoughness(roughness)\n\n\ndef getVTKSkybox(envTexture: vtkTexture) -> vtkSkybox:\n skybox = vtkSkybox()\n skybox.SetFloorRight(0, 0, 1)\n skybox.SetProjection(vtkSkybox.Sphere)\n skybox.SetTexture(envTexture)\n skybox.GammaCorrectOn()\n return skybox\n\n\ndef getVTKRenderer(envTexture: vtkTexture) -> vtkRenderer:\n ren = vtkRenderer()\n ren.UseImageBasedLightingOn()\n ren.UseSphericalHarmonicsOn()\n ren.SetEnvironmentTexture(envTexture, False)\n return ren\n\n\ndef screenshot(window: vtkRenderWindow, filename: str = 'screenshot.png') -> None:\n w2if = vtkWindowToImageFilter()\n w2if.SetInput(window)\n w2if.Update()\n \n writer = vtkPNGWriter()\n writer.SetFileName(filename)\n writer.SetInputData(w2if.GetOutput())\n writer.Write()\n\n\ndef screenshot_large(renderer: vtkRenderer, magnification: int, filename: str = 'screenshot.png') -> None:\n renderLarge = vtkRenderLargeImage()\n renderLarge.SetInput(renderer)\n renderLarge.SetMagnification(magnification)\n \n writer = vtkPNGWriter()\n writer.SetFileName(str(OUTPUT_IMAGES.joinpath(filename).resolve()))\n writer.SetInputConnection(renderLarge.GetOutputPort())\n writer.Write()\n\n\n# Type for display points description\nDPoints = List[List[int]]\n# Type for world points description\nWPoints = List[List[float]]\n\n\nclass YOLOv8Tools:\n \"\"\"Class for labeling dataset images in YOLOv8 format\"\"\"\n @staticmethod\n def correctionOffDisplay(displayPoints: DPoints, img_size: Tuple[int, int]) -> DPoints:\n \"\"\"Pixels which are located off screen are then transfered to screen borders\"\"\"\n correctedDPoints = []\n\n for point in displayPoints:\n corrected = False\n beforeCorrection = point\n\n # Checking x coordinate\n if point[0] >= img_size[0]:\n point[0] = img_size[0] - 1\n corrected = True\n elif point[0] < 0:\n point[0] = 0\n corrected = True\n\n # Checking y coordinate\n if point[1] >= img_size[1]:\n point[1] = img_size[1] - 1\n corrected = True\n elif point[1] < 0:\n point[1] = 0\n corrected = True\n\n if corrected:\n print('Corrected')\n print(beforeCorrection)\n print(point)\n\n # Checking for duplicates\n if len(correctedDPoints) > 0 and point == correctedDPoints[-1]:\n continue\n correctedDPoints.append(point)\n\n return correctedDPoints\n \n @staticmethod\n def polygonFromPoints(points: list, centroid):\n angles = [math.atan2(point[1] - centroid[1], point[0] - centroid[0]) for point in points]\n\n for i, angle in enumerate(angles):\n angles[i] = angle * 180 / math.pi\n if angle < 0:\n angles[i] += 360\n\n sorted_points = [p for _, p in sorted(zip(angles, points))]\n sorted_points.append(sorted_points[0])\n return sorted_points\n \n @staticmethod\n def correctionCovering(worldQRPoints: WPoints, worldDocPoints: WPoints,\n mesh, ren: vtkRenderer, img_size: Tuple[int, int], fp) -> DPoints:\n \"\"\"Pixels which are located under the covering object are \n then transfered to a place where it belongs to both covering and labeling zones\"\"\"\n camPoint = ren.GetActiveCamera().GetPosition()\n npCamPoint = np.array(camPoint)\n labelPoints = []\n\n allCasted = True\n for wpQR in worldQRPoints:\n vectorTarget = 3 * (np.array(wpQR) - npCamPoint)\n intersections = ray_cast_vector_intersection(camPoint, vectorTarget, mesh)\n if math.isclose(intersections[0][0], wpQR[0], rel_tol=1e-5) and \\\n math.isclose(intersections[0][1], wpQR[1], rel_tol=1e-5) and \\\n math.isclose(intersections[0][2], wpQR[2], rel_tol=1e-5):\n labelPoints.append(wpQR)\n elif allCasted:\n allCasted = False\n\n labelPolygon = [labelPoints]\n labelDPoints = displayCompute(labelPolygon, ren, img_size)[0]\n if allCasted:\n # print('labelDPoints', labelDPoints)\n return labelDPoints\n \n coverPoints = []\n for wpDoc in worldDocPoints:\n vectorTarget = 3 * (np.array(wpDoc) - npCamPoint)\n intersections = ray_cast_vector_intersection(camPoint, vectorTarget, mesh)\n if len(intersections) > 1 and \\\n np.linalg.norm(np.array(intersections[0]) - npCamPoint) < np.linalg.norm(np.array(intersections[1]) - npCamPoint):\n # math.isclose(intersections[0][0], wpDoc[0], rel_tol=1e-5) and \\\n # math.isclose(intersections[0][1], wpDoc[1], rel_tol=1e-5) and \\\n # math.isclose(intersections[0][2], wpDoc[2], rel_tol=1e-5):\n coverPoints.append(intersections[0])\n\n coverPolygon = [coverPoints]\n QRPolygon = [worldQRPoints]\n\n coverDPoints = displayCompute(coverPolygon, ren, img_size)[0]\n QRDPoints = displayCompute(QRPolygon, ren, img_size)[0]\n\n centroid = common_math.centroid_display(QRDPoints)\n if not centroid:\n return []\n\n def isAnglePositive(p1: Sequence[int], p2: Sequence[int], p3: Sequence[int]):\n matrix = np.array([[p1[0], p1[1], 1],\n [p2[0], p2[1], 1],\n [p3[0], p3[1], 1]], dtype=np.int32)\n \n if np.linalg.det(matrix) > 0:\n return True\n else:\n return False\n\n p_list = []\n for z in coverDPoints:\n for i in range(len(QRDPoints) - 1):\n if not isAnglePositive(z, centroid, QRDPoints[i]) and \\\n isAnglePositive(z, centroid, QRDPoints[i+1]):\n p1 = QRDPoints[i]\n p2 = QRDPoints[i+1]\n p_list.append([p1, p2])\n break\n\n for i, z in enumerate(coverDPoints):\n if not isAnglePositive(p_list[i][0], p_list[i][1], z):\n labelDPoints.append(z)\n \n centroid = common_math.centroid_display(labelDPoints)\n if not centroid:\n return []\n return YOLOv8Tools.polygonFromPoints(labelDPoints, centroid)\n\n\ndef labelImageYOLO(displayPoints: list, img_size: tuple[int, int], file_name: str):\n label = '1' # qr code class\n\n displayPointsLists = []\n for point in displayPoints:\n displayPointsLists.append([point[0], point[1]])\n\n # Getting DPoints\n displayPointsLists = YOLOv8Tools.correctionOffDisplay(displayPointsLists, img_size)\n \n width, height = img_size\n # Labeling\n for point in displayPointsLists:\n label += ' '\n label += f'{point[0]/width} {point[1]/height}'\n\n #TODO: remove explicit path\n with open(str(OUTPUT_LABELS.joinpath(f'{file_name}.txt').resolve()), 'w') as file_label:\n file_label.write(label)\n\n\ndef outOfView(pixels, resolution: tuple[int, int]) -> bool:\n for pixel in pixels:\n if pixel[0] < 0 or pixel[0] >= resolution[0]:\n return True\n if pixel[1] > 0 or pixel[1] <= -resolution[1]:\n return True\n \n return False\n\n\nclass vtkCameraCallback(object):\n \"\"\"\n Callback for the camera visualization in the second renderer.\n \"\"\"\n\n def __init__(self,\n ren: vtkRenderer,\n renSim: vtkRenderer,\n camSim: vtkActor,\n polyCam: vtkActor,\n polyQR: vtkActor,\n polyRay: vtkActor,\n geometry: vis.NPGeometryGetter\n ):\n self.ren = ren\n self.renSim = renSim\n self.camSim = camSim\n self.polyCam = polyCam\n self.polyQR = polyQR\n self.polyRay = polyRay\n self.geometry = geometry\n\n\n def __call__(self, caller, ev):\n position = self.ren.GetActiveCamera().GetPosition()\n self.camSim.SetPosition(position)\n self._drawCam()\n self._drawRay()\n # self._drawQR()\n self.renSim.ResetCamera()\n\n\n @staticmethod\n def lines(line_paths: list[list[int]]) -> vtkCellArray:\n lines = vtkCellArray()\n\n for path in line_paths:\n polyLine = vtkPolyLine()\n polyLine.GetPointIds().SetNumberOfIds(len(path))\n for i in range(0, len(path)):\n polyLine.GetPointIds().SetId(i, path[i])\n\n lines.InsertNextCell(polyLine)\n\n return lines\n\n\n def _drawRay(self):\n document3D = self.geometry.documentScaled3D(2)\n points = vtkPoints()\n vertices = vtkCellArray()\n lenPoints = len(document3D) + 1\n pid = [0] * lenPoints\n pid[0] = points.InsertNextPoint(self.ren.GetActiveCamera().GetPosition())\n for i in range(1, lenPoints):\n pid[i] = points.InsertNextPoint(document3D[i-1])\n vertices.InsertNextCell(lenPoints, pid)\n\n paths = [[0, x] for x in range(1, lenPoints)]\n lines = vtkCameraCallback.lines(paths)\n\n poly = vtkPolyData()\n poly.SetPoints(points)\n poly.SetVerts(vertices)\n poly.SetLines(lines)\n\n self.polyRay.GetMapper().SetInputData(poly)\n\n\n def _drawCam(self):\n imageFocalPoint = self.geometry.getImageFocalPoint()\n imageCorners = self.geometry.getImageCorners()\n points = vtkPoints()\n\n polyLine = vtkPolyLine()\n linePath = [1, 2, 3, 1, 3, 4, 1, 4, 5, 1, 5, 2]\n polyLine.GetPointIds().SetNumberOfIds(len(linePath))\n for i in range(0, len(linePath)):\n polyLine.GetPointIds().SetId(i, linePath[i])\n\n lines = vtkCellArray()\n lines.InsertNextCell(polyLine)\n\n vertices = vtkCellArray()\n pid = [0] * 6\n pid[0] = points.InsertNextPoint(imageFocalPoint)\n pid[1] = points.InsertNextPoint(self.ren.GetActiveCamera().GetPosition())\n pid[2] = points.InsertNextPoint(imageCorners[0])\n pid[3] = points.InsertNextPoint(imageCorners[1])\n pid[4] = points.InsertNextPoint(imageCorners[2])\n pid[5] = points.InsertNextPoint(imageCorners[3])\n vertices.InsertNextCell(6, pid)\n\n poly = vtkPolyData()\n\n poly.SetPoints(points)\n poly.SetVerts(vertices)\n poly.SetLines(lines)\n\n self.polyCam.GetMapper().SetInputData(poly)\n\n\n def _drawQR(self):\n cornersProjected = self.geometry.getCornersProjected()\n\n points = vtkPoints()\n\n polyLine = vtkPolyLine()\n linePath = [0, 1, 2, 3, 0]\n polyLine.GetPointIds().SetNumberOfIds(len(linePath))\n for i in range(0, len(linePath)):\n polyLine.GetPointIds().SetId(i, linePath[i])\n\n lines = vtkCellArray()\n lines.InsertNextCell(polyLine)\n\n vertices = vtkCellArray()\n pid = [0] * 4\n pid[0] = points.InsertNextPoint(cornersProjected[0])\n pid[1] = points.InsertNextPoint(cornersProjected[1])\n pid[2] = points.InsertNextPoint(cornersProjected[2])\n pid[3] = points.InsertNextPoint(cornersProjected[3])\n vertices.InsertNextCell(4, pid)\n\n poly = vtkPolyData()\n\n poly.SetPoints(points)\n poly.SetVerts(vertices)\n poly.SetLines(lines)\n\n self.polyQR.GetMapper().SetInputData(poly)\n\n\ndef demoCameraFly(ren, renWin):\n for i in range(360):\n ren.GetActiveCamera().OrthogonalizeViewUp()\n renWin.Render()\n ren.GetActiveCamera().Elevation(-1)\n ren.ResetCameraClippingRange()\n\n for i in range(360):\n ren.GetActiveCamera().OrthogonalizeViewUp()\n renWin.Render()\n ren.GetActiveCamera().Azimuth(-1)\n ren.ResetCameraClippingRange()\n\n for i in range(360):\n ren.GetActiveCamera().OrthogonalizeViewUp()\n renWin.Render()\n ren.GetActiveCamera().Roll(-1)\n ren.ResetCameraClippingRange()\n\n\ndef displayCompute(squares3D, ren, img_size=None):\n squaresDisplay = [[] for _ in squares3D]\n\n coord = vtkCoordinate()\n coord.SetCoordinateSystemToWorld()\n for i in range(len(squares3D)):\n for j in range(len(squares3D[i])):\n coord.SetValue(squares3D[i][j])\n displayCoordinates = coord.GetComputedDisplayValue(ren)\n if not img_size:\n displayCoordinates = (displayCoordinates[0], -displayCoordinates[1])\n else:\n displayCoordinates = (displayCoordinates[0], img_size[1]-displayCoordinates[1])\n squaresDisplay[i].append(displayCoordinates)\n\n return squaresDisplay\n\n\ndef createPointsVertices(points3D) -> tuple[vtkPoints, vtkCellArray]:\n points = vtkPoints()\n vertices = vtkCellArray()\n \n lenPoints = len(points3D[0])\n pid = [0] * lenPoints\n\n for i in range(0, lenPoints):\n pid[i] = points.InsertNextPoint(points3D[0][i])\n vertices.InsertNextCell(lenPoints, pid)\n\n return points, vertices\n\n\ndef createActorPoly(points, vertices, lines, color, point_size=3):\n poly = vtkPolyData()\n poly.SetPoints(points)\n poly.SetVerts(vertices)\n \n mapperPoly = vtkPolyDataMapper()\n mapperPoly.SetInputData(poly)\n \n actorPoly = vtkActor()\n actorPoly.SetMapper(mapperPoly)\n actorPoly.GetProperty().SetColor(color)\n actorPoly.GetProperty().SetPointSize(point_size)\n\n return actorPoly\n\n\ndef createActorRay(document3D, cam):\n points = vtkPoints()\n vertices = vtkCellArray()\n lenPoints = len(document3D[0]) + 1\n pid = [0] * lenPoints\n pid[0] = points.InsertNextPoint(cam.GetPosition())\n for i in range(1, lenPoints):\n pid[i] = points.InsertNextPoint(document3D[0][i-1])\n vertices.InsertNextCell(lenPoints, pid)\n\n paths = [[0, x] for x in range(1, lenPoints)]\n lines = vtkCameraCallback.lines(paths)\n\n poly = vtkPolyData()\n poly.SetPoints(points)\n poly.SetVerts(vertices)\n poly.SetLines(lines)\n\n mapperPoly = vtkPolyDataMapper()\n mapperPoly.SetInputData(poly)\n\n actorPolyRay = vtkActor()\n actorPolyRay.SetMapper(mapperPoly)\n actorPolyRay.GetProperty().SetColor(colors.GetColor3d('Orange'))\n actorPolyRay.GetProperty().SetPointSize(3)\n\n return actorPolyRay\n\n\ndef main(\n *argv, \n iren: bool = True, \n screen_shot: str = \"\", \n vizualize: bool = False, \n camera: vtkCamera = None, \n folder\n ) -> None:\n objPath = str(Path(argv[1]).resolve())\n imgPath = str(Path(argv[2]).resolve())\n jsonProfilePath = str(Path(argv[3]).resolve())\n hdrPath = Path(argv[4])\n\n distortionPixels = argv[5]\n minArea = argv[6]\n maxArea = argv[7]\n\n envTexture = read_equirectangular_file(hdrPath)\n\n ren = getVTKRenderer(envTexture)\n if vizualize:\n ren.SetViewport(0.0, 0.0, 0.5, 1.0)\n\n if vizualize:\n ren_sim = getVTKRenderer(envTexture)\n ren_sim.SetViewport(0.5, 0.0, 1.0, 1.0)\n\n mapper = getVTKMapper(objPath)\n texture = getVTKTexture(imgPath)\n\n normal_reader = vtkPNGReader()\n normal_reader.SetFileName(str(PBR.joinpath('Paper001_2K-PNG/Paper001_2K_NormalGL').with_suffix('.png').resolve()))\n\n normal = vtkTexture()\n normal.InterpolateOn()\n normal.SetInputConnection(normal_reader.GetOutputPort())\n\n material_reader = vtkPNGReader()\n material_reader.SetFileName(str(PBR.joinpath('Paper001_2K-PNG/Paper001_2K_ORM').with_suffix('.png').resolve()))\n\n material = vtkTexture()\n material.InterpolateOn()\n material.SetInputConnection(material_reader.GetOutputPort())\n\n actor = getVTKActorPBR(mapper, texture, material, normal)\n\n skybox = getVTKSkybox(envTexture)\n\n ren.AddActor(actor)\n ren.AddActor(skybox)\n\n centerQR3D = camera_positioning.QR_3D_center(objPath, jsonProfilePath)\n\n edge3D = camera_positioning.QR_edge_3D(objPath, jsonProfilePath)\n\n renWin = vtkRenderWindow()\n renWin.SetSize(1200, 600)\n renWin.AddRenderer(ren)\n \n if iren:\n iren = vtkRenderWindowInteractor()\n iren.SetRenderWindow(renWin)\n style = vtkInteractorStyleTrackballCamera()\n iren.SetInteractorStyle(style)\n iren.Initialize()\n\n if camera:\n viewAngle = camera.GetViewAngle()\n ren.SetActiveCamera(camera)\n ren.ResetCamera()\n ren.GetActiveCamera().SetViewAngle(viewAngle)\n else:\n cam = ren.GetActiveCamera()\n cam.SetClippingRange(0.0001, 100000)\n cam.Azimuth(0)\n cam.Elevation(0)\n ren.ResetCamera()\n cam.SetFocalPoint(*centerQR3D)\n cam.OrthogonalizeViewUp()\n cam.SetViewAngle(30)\n cam.Zoom(1)\n\n if vizualize:\n sphere = vtkSphereSource()\n sphere.SetRadius(0.01)\n\n sphereMapper = vtkPolyDataMapper()\n sphereMapper.SetInputConnection(sphere.GetOutputPort())\n\n sphereActor = vtkActor()\n sphereActor.SetMapper(sphereMapper)\n sphereActor.SetPosition(ren.GetActiveCamera().GetPosition())\n sphereActor.GetProperty().SetColor(colors.GetColor3d('MistyRose'))\n\n textureSim = getVTKTexture(imgPath)\n actorSim = getVTKActorPBR(mapper, textureSim, material, normal)\n\n ren_sim.AddActor(sphereActor)\n ren_sim.AddActor(actorSim)\n ren_sim.AddActor(skybox)\n ren_sim.ResetCamera()\n\n renWin.AddRenderer(ren_sim)\n renWin.Render()\n\n squares3D = camera_positioning.QR_3D(objPath, jsonProfilePath)\n barcells = camera_positioning.QR_3D_barcells(objPath, jsonProfilePath)\n document3D = camera_positioning.document_3D(objPath, jsonProfilePath, 2)\n squaresDisplay = [[] for _ in squares3D]\n\n coord = vtkCoordinate()\n coord.SetCoordinateSystemToWorld()\n for i in range(len(squares3D)):\n for j in range(len(squares3D[i])):\n coord.SetValue(squares3D[i][j])\n displayCoordinates = coord.GetComputedDisplayValue(ren)\n displayCoordinates = (displayCoordinates[0], -displayCoordinates[1])\n squaresDisplay[i].append(displayCoordinates)\n \n if vizualize:\n geometry = vis.NPGeometryGetter(cam, ren, np.array(squares3D[0]), np.array(document3D[0]))\n geometry.updateDTM()\n\n imageFocalPoint = geometry.getImageFocalPoint()\n imageCorners = geometry.getImageCorners()\n points = vtkPoints()\n\n polyLine = vtkPolyLine()\n linePath = [1, 2, 3, 1, 3, 4, 1, 4, 5, 1, 5, 2]\n polyLine.GetPointIds().SetNumberOfIds(len(linePath))\n for i in range(0, len(linePath)):\n polyLine.GetPointIds().SetId(i, linePath[i])\n\n lines = vtkCellArray()\n lines.InsertNextCell(polyLine)\n\n # Create the topology of the point (a vertex)\n vertices = vtkCellArray()\n # We need an an array of point id's for InsertNextCell.\n pid = [0] * 6\n pid[0] = points.InsertNextPoint(imageFocalPoint)\n pid[1] = points.InsertNextPoint(cam.GetPosition())\n pid[2] = points.InsertNextPoint(imageCorners[0])\n pid[3] = points.InsertNextPoint(imageCorners[1])\n pid[4] = points.InsertNextPoint(imageCorners[2])\n pid[5] = points.InsertNextPoint(imageCorners[3])\n vertices.InsertNextCell(6, pid)\n\n # Create a polydata object\n poly = vtkPolyData()\n\n # Set the points and vertices we created as the geometry and topology of the polydata\n poly.SetPoints(points)\n poly.SetVerts(vertices)\n poly.SetLines(lines)\n\n # Visualize\n mapperPoly = vtkPolyDataMapper()\n mapperPoly.SetInputData(poly)\n\n actorPolyCam = vtkActor()\n actorPolyCam.SetMapper(mapperPoly)\n actorPolyCam.GetProperty().SetColor(colors.GetColor3d('Tomato'))\n pointSize = sphereActor.GetProperty().GetPointSize() * 4\n actorPolyCam.GetProperty().SetPointSize(pointSize)\n\n ren_sim.AddActor(actorPolyCam)\n\n cornersProjected = geometry.getCornersProjected()\n\n points = vtkPoints()\n\n polyLine = vtkPolyLine()\n linePath = [0, 1, 2, 3, 0]\n polyLine.GetPointIds().SetNumberOfIds(len(linePath))\n for i in range(0, len(linePath)):\n polyLine.GetPointIds().SetId(i, linePath[i])\n\n lines = vtkCellArray()\n lines.InsertNextCell(polyLine)\n\n # Create the topology of the point (a vertex)\n vertices = vtkCellArray()\n # We need an an array of point id's for InsertNextCell.\n pid = [0] * 4\n pid[0] = points.InsertNextPoint(cornersProjected[0])\n pid[1] = points.InsertNextPoint(cornersProjected[1])\n pid[2] = points.InsertNextPoint(cornersProjected[2])\n pid[3] = points.InsertNextPoint(cornersProjected[3])\n vertices.InsertNextCell(4, pid)\n\n # Create a polydata object\n poly = vtkPolyData()\n\n # Set the points and vertices we created as the geometry and topology of the polydata\n poly.SetPoints(points)\n poly.SetVerts(vertices)\n poly.SetLines(lines)\n\n # Visualize\n mapperPoly = vtkPolyDataMapper()\n mapperPoly.SetInputData(poly)\n\n actorPolyQR = vtkActor()\n actorPolyQR.SetMapper(mapperPoly)\n actorPolyQR.GetProperty().SetColor(colors.GetColor3d('Orange'))\n pointSize = sphereActor.GetProperty().GetPointSize()\n actorPolyQR.GetProperty().SetPointSize(pointSize)\n\n actorPolyRay = createActorRay(document3D, cam)\n\n ren_sim.AddActor(actorPolyQR)\n ren_sim.AddActor(actorPolyRay)\n ren_sim.RemoveActor(actorPolyQR)\n\n ren_sim.ResetCamera()\n\n mo = vtkCameraCallback(ren, ren_sim, sphereActor, actorPolyCam, actorPolyQR, actorPolyRay, geometry)\n ren.AddObserver('StartEvent', mo)\n renWin.Render()\n\n if iren:\n iren.Start()\n\n if screen_shot:\n renWin.Render()\n screenshot_large(ren, 4, screen_shot)\n\n ### 3D -> Display coordinates ###\n if vizualize:\n # from PIL import Image\n renSize = (renWin.GetSize()[0] // 2, renWin.GetSize()[1])\n limit_movement(ren, mapper.GetInput(), renSize, distortionPixels, minArea, maxArea, squares3D, barcells, document3D, func_render=renWin.Render)\n\n if not vizualize:\n renWin.SetSize(600, 600)\n renSize = renWin.GetSize()\n limits = limit_movement(ren, mapper.GetInput(), renSize, distortionPixels, minArea, maxArea, squares3D, barcells, document3D, func_render=renWin.Render)\n \n def divide2(elem):\n return int(elem / 2)\n \n npDiv2 = np.vectorize(divide2)\n limits2 = [[npDiv2(x[0]), x[1]] for x in limits]\n limits.extend(limits2)\n\n # camerapos = limits_to_camerapos(ren, limits)\n document3D = camera_positioning.document_3D(objPath, jsonProfilePath, 64)\n save_limits(ren, limits, edge3D, document3D, mapper.GetInput(), f'{folder}', renWin)\n\n\ndef save_limits(renderer: vtkRenderer, limits: np.ndarray, edge3D, document3D, mesh, file_path: str, renWin: vtkRenderWindow):\n cam = renderer.GetActiveCamera()\n pos = cam.GetPosition()\n viewUp = cam.GetViewUp()\n\n for i, limit in enumerate(limits):\n cam.Azimuth(limit[0][0])\n cam.Elevation(limit[0][1])\n \n # azimuth = random.uniform(-5, 5)\n # elevation = random.uniform(-5, 5)\n # cam.Azimuth(azimuth)\n # cam.Elevation(elevation)\n\n randZoom = random.uniform(0.5, 1.0)\n cam.Zoom(limit[1] * randZoom)\n \n focalPoint = np.array(cam.GetFocalPoint())\n edgePoint = edge3D[0][random.randrange(0, len(edge3D[0]))]\n edgePoint = np.array(edgePoint)\n toVector = edgePoint - focalPoint\n randFocalPoint = focalPoint + random.uniform(0, 1) * toVector\n cam.SetFocalPoint(*randFocalPoint.tolist())\n\n roll = random.uniform(-90, 90)\n cam.Roll(roll)\n cam.OrthogonalizeViewUp()\n\n renWin.Render()\n \n # adding image to dataset\n screenshot_large(renderer, 4, f'{file_path}_{i}.png')\n \n # adding label to dataset\n edgeDisplay = YOLOv8Tools.correctionCovering(edge3D[0], document3D[0], mesh, renderer, renWin.GetSize(), f'{file_path}_{i}.png')\n if not edgeDisplay:\n continue\n labelImageYOLO(edgeDisplay, renWin.GetSize(), f'{file_path}_{i}')\n\n cam.SetPosition(pos)\n cam.SetFocalPoint(*focalPoint.tolist())\n cam.Roll(-roll)\n cam.Zoom(1 / limit[1] / randZoom)\n cam.SetViewUp(viewUp)\n\n\ndef limits_to_camerapos(renderer: vtkRenderer, limits: list):\n camerapos = []\n\n cam = renderer.GetActiveCamera()\n pos = cam.GetPosition()\n viewUp = cam.GetViewUp()\n\n for i, limit in enumerate(limits):\n cam.Azimuth(limit[0][0])\n cam.Elevation(limit[0][1])\n cam.Zoom(limit[1])\n cam.OrthogonalizeViewUp()\n\n camerapos.append(cam.GetPosition())\n\n cam.SetPosition(pos)\n cam.Zoom(1 / limit[1])\n cam.SetViewUp(viewUp)\n\n return camerapos\n\n\ndef ray_cast_distorted(cam, document3D, mesh) -> bool:\n distorted = False\n\n for square in document3D:\n for point in square:\n vector_target = np.array(point) - np.array(cam.GetPosition())\n vector_target *= 3\n code = ray_cast_vector(cam.GetPosition(), vector_target, mesh)\n\n if code == -1:\n distorted = True\n break\n \n if distorted:\n break\n\n return distorted\n\n\ndef limit_movement(\n ren: vtkRenderer, \n mesh: vtkPolyData,\n ren_size: tuple[int, int],\n distortionPixels: float,\n minArea: int,\n maxArea: int,\n squares3D, \n barcells3D, \n document3D, \n func_render\n ) -> None:\n cam = ren.GetActiveCamera()\n cam.SetClippingRange(0.0001, 1000)\n # directions = np.array([[90, 0], [0, 90], [-90, 0], [0, -90]], dtype=np.int32)\n directions = np.array([[90, 0], [90, 90], [0, 90], [-90, 90], [-90, 0], [-90, -90], [0, -90], [90, -90]], dtype=np.int32)\n zero = np.array([0, 0], dtype=np.int32)\n\n limits = []\n direction1 = directions[0] - zero\n\n mov: np.ndarray = direction1 // 6\n path = np.array([0, 0], dtype=np.int32)\n pos = cam.GetPosition()\n viewUp = cam.GetViewUp()\n zoomFactor = 1\n\n zoomOut = 0.8\n zoomIn = 1.2\n\n def divide2(elem):\n return int(elem / 2)\n \n npDivide2 = np.vectorize(divide2)\n\n def zoomDocument(zone3D, ren, cam, zoomFactor, func_render):\n outZone = False\n while not outZone:\n zoneDisplay = displayCompute(zone3D, ren)\n for square in zoneDisplay:\n outZone = outOfView(square, ren_size)\n\n if outZone:\n cam.Zoom(zoomOut)\n zoomFactor *= zoomOut\n else:\n cam.Zoom(zoomIn)\n zoomFactor *= zoomIn\n\n func_render()\n\n return zoomFactor\n\n for i, direction in enumerate(directions):\n cam.SetPosition(pos)\n cam.SetViewUp(0, 1, 0)\n cam.OrthogonalizeViewUp()\n\n mov: np.ndarray = direction // 6\n path = np.array([0, 0], dtype=np.int32)\n cam.Zoom(1 / zoomFactor)\n zoomFactor = 1\n\n limits.append([])\n\n while mov[0] != 0 or mov[1] != 0:\n zoomFactor = zoomDocument(squares3D, ren, cam, zoomFactor, func_render=func_render)\n\n squaresDisplay = displayCompute(squares3D, ren)\n out = False\n\n for square in squaresDisplay:\n if outOfView(square, ren_size):\n out = True\n break\n\n if out:\n print('Out')\n cam.Zoom(zoomOut)\n zoomFactor *= zoomOut\n continue\n\n distorted = False\n barcellsDisplay = displayCompute(barcells3D, ren)\n\n for square in barcellsDisplay:\n try:\n distorted = camera_positioning.isDistorted(square, distortionPixels)\n except ValueError:\n distorted = True\n\n if distorted:\n break\n\n # sized = False\n # for square in squaresDisplay:\n # sized = camera_positioning.isSized(square, minArea, maxArea)\n # if not sized:\n # break\n\n distorted = distorted or ray_cast_distorted(cam, document3D, mesh)\n\n if distorted:\n maxCloseFactor = random.uniform(-0.2, 0.7)\n while camera_positioning.closeToMax(squaresDisplay[0], minArea, maxArea) < maxCloseFactor:\n cam.Zoom(0.95)\n zoomFactor *= 0.95\n squaresDisplay = displayCompute(squares3D, ren)\n func_render()\n\n limits[i] = [path, zoomFactor]\n \n if path[0] == zero[0] and path[1] == zero[1]:\n break\n\n cam.Elevation(-mov[1])\n cam.Azimuth(-mov[0])\n func_render()\n path -= mov\n mov = npDivide2(mov)\n else:\n cam.Azimuth(mov[0])\n cam.Elevation(mov[1])\n path += mov\n cam.OrthogonalizeViewUp()\n func_render()\n\n\n cam.SetPosition(pos)\n cam.Zoom(1 / zoomFactor)\n cam.SetViewUp(0, 1, 0)\n cam.OrthogonalizeViewUp()\n\n return limits\n\n\ndef ray_cast_point(point_source: Sequence[float], point_target: Sequence[float],\n mesh: vtkPolyData):\n\n OBBTree = vtkOBBTree()\n OBBTree.SetDataSet(mesh)\n OBBTree.BuildLocator()\n\n pointsVTKintersection = vtkPoints()\n code = OBBTree.IntersectWithLine(point_source, point_target, pointsVTKintersection, None)\n\n return code\n\n\ndef ray_cast_vector(point_source: Sequence[float], vector_target: Sequence[float],\n mesh: vtkPolyData):\n\n OBBTree = vtkOBBTree()\n OBBTree.SetDataSet(mesh)\n OBBTree.BuildLocator()\n\n pointsVTKintersection = vtkPoints()\n point_target = tuple(s + v for s, v in zip(point_source, vector_target))\n code = OBBTree.IntersectWithLine(point_source, point_target, pointsVTKintersection, None)\n\n return code\n\n\ndef ray_cast_vector_intersection(point_source: Sequence[float], vector_target: Sequence[float],\n mesh: vtkPolyData):\n\n OBBTree = vtkOBBTree()\n OBBTree.SetDataSet(mesh)\n OBBTree.BuildLocator()\n\n pointsVTKintersection = vtkPoints()\n point_target = tuple(s + v for s, v in zip(point_source, vector_target))\n code = OBBTree.IntersectWithLine(point_source, point_target, pointsVTKintersection, None)\n\n pointsVTKIntersectionData = pointsVTKintersection.GetData()\n noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()\n pointsIntersection = []\n for idx in range(noPointsVTKIntersection):\n _tup = pointsVTKIntersectionData.GetTuple3(idx)\n pointsIntersection.append(_tup)\n\n return pointsIntersection\n\n\ndef complete_barcell_visibility_test(folder_id: int):\n azimuths = [float(x) for x in range(-15, 30, 15)]\n elevations = [float(x) for x in range(-15, 30, 15)]\n viewAngles = [float(x) for x in range(30, 60, 15)]\n\n for azimuth in azimuths:\n for elevation in elevations:\n for viewAngle in viewAngles:\n camera = vtkCamera()\n camera.Azimuth(azimuth)\n camera.Elevation(elevation)\n camera.SetViewAngle(viewAngle)\n\n main(*sys.argv, iren=False, vizualize=True, screen_shot='camera_tmp/{}/{}_{}_{}.png'.format(folder_id, azimuth, elevation, viewAngle), camera=camera)\n\n\nif __name__ == '__main__':\n import sys\n import json\n import random\n\n if len(sys.argv) != 5:\n distortionPixels = 2\n minArea = 50000\n maxArea = 150000\n else:\n template_name = sys.argv[1]\n distortionPixels = float(sys.argv[2])\n minArea = int(sys.argv[3])\n maxArea = int(sys.argv[4])\n\n hdrs = ['fireplace_4k.hdr', 'venetian_crossroads_4k.hdr', 'street_lamp_4k.hdr', 'pretville_street_4k.hdr',\n 'christmas_photo_studio_04_4k.hdr', 'blocky_photo_studio_4k.hdr', 'colorful_studio_4k.hdr',\n 'gear_store_4k.hdr', 'peppermint_powerplant_2_4k.hdr', 'royal_esplanade_4k.hdr',\n 'sepulchral_chapel_basement_4k.hdr']\n \n count = 0\n with open(f'json/{template_name}.json') as config_fp:\n count = len(json.load(config_fp))\n\n for i in range(0, count):\n objPath = f'obj/{template_name}_{i}.obj'\n jsonProfilePath = f'json/profile/{template_name}_{i}.json'\n imgPath = f'texture/{template_name}_{i}.png'\n \n j = random.randrange(0, len(hdrs))\n hdrPath = f'hdr/{hdrs[j]}'\n\n argv = ['', objPath, imgPath, jsonProfilePath, hdrPath, distortionPixels, minArea, maxArea]\n main(\n *argv,\n iren=False,\n vizualize=False,\n screen_shot='',\n folder=i\n )\n","repo_name":"Vill21/science","sub_path":"project/vtk_render.py","file_name":"vtk_render.py","file_ext":"py","file_size_in_byte":36779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"73771416915","text":"import re\nimport os\nimport numpy as np\nfrom pathlib import Path\nimport io\nimport base64\nimport gradio as gr\nfrom PIL import Image\nfrom comm import Client\nimport cv2\n\ndef img_to_txt(filename,s):\n msg = b\"\"\n with open(filename, \"rb\") as imageFile:\n msg = msg + base64.b64encode(imageFile.read())\n msg = msg + b\"\"\n q = b\"\"\n q = q + base64.b64encode(s.encode('ascii'))\n q = q + b\"\"\n msg = msg+q\n return msg\n\ndef decode_img(msg):\n msg1 = msg[msg.find(b\"\")+len(b\"\"):\n msg.find(b\"\")]\n msg1 = base64.b64decode(msg1)\n\n jpg_as_np = np.frombuffer(msg1, dtype=np.uint8)\n img = cv2.imdecode(jpg_as_np, flags=1)\n\n return img\n\n\ndef main(client, server_host, server_port, Picture,Question):\n # Send request\n data = img_to_txt(Picture,Question)\n client.connectService(server_host, server_port)\n client.sendImageRequest(data)\n # Display result\n reply = client.receiveData()\n out = []\n for command, data_type, data in reply:\n\n out.append(decode_img(data))\n if len(out) == 1:\n out = out[0]\n return out\n\nif __name__ == \"__main__\":\n example = [['pokemons.jpg','a lizard with fire on its tail'],\\\n ['one_piece.jpg','a man in a straw hat and a red dress'],\\\n ['flowers.jpg','a white vase and pink flowers']] \n server_host = os.environ['SERVER_HOST']\n server_port = int(os.environ['SERVER_PORT'])\n\n client = Client()\n try:\n client.connectService(server_host, server_port)\n client.initService()\n reply = client.receiveData()\n for command, data_type, data in reply:\n print(command)\n\n gr.Interface(fn=lambda Picture,Question: main(client, server_host, server_port, Picture,Question), \n inputs=[gr.Image(type=\"filepath\"),'text'],\n outputs='image',\n examples= example,\n ).launch(server_name=\"0.0.0.0\")\n\n except InterruptedError:# Stop Service\n client.connectService(server_host, 10010)\n client.stopService()\n client.disconnectService()\n","repo_name":"Rubayethkabir/Automatic-ML-model-deployment-as-web-service","sub_path":"TorchClients/visual-grounding/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"32973320041","text":"import numpy as np\nimport pdb\nimport matplotlib.pyplot as plt\n\ndef galmodel(dist,feh,glong,glat,nomet=True,plot=False) :\n\n ''' Return probabilities in each galactic component for a range of distances at given l, b'''\n\n #solar distance from galactic center (pc)\n soldistgc = np.double(8000.)\n\n gallat = np.double(glat)*np.pi/180.\n gallong = np.double(glong)*np.pi/180.\n\n # GALAXY PARAMETERS FOR PRIOR ASSUMPTIONS \n\n rthin = 2900. #thin disk scale length, pc\n zthin = 300. #thin disk scale height,pc\n zhthin = 94.69*2**1.666\n rthick = 2400. #thick disk scale length, pc\n zthick = 800. #thick disk scale height, pc\n zhthick= 800.\n bulgescale = 2500. # bulge scale length,pc\n bulgetrunc = 95. # bulge inner truncation radius, pc\n bulgeangle = -15.*np.pi/180. #15 degree major axis angle relative to the sun-gc LoS, converted to radians\n bulgezeta = 0.31 # z axis ratio for bulge\n bulgeeta = 0.68 #y axis ratio for bulge\n\n #metallicity distribution for our priors. the metallicity\n #distribution will probably need to be revisisted, most studies of\n #these (other than the bulge) take place at the solar neighborhood.\n #might need tweaking (larger standard deviations, or perhaps as a function of R_gc).\n\n bulgemetal = -0.1 # [Fe/H]\n bulgesig = 0.5 # standard deviation of metallicity for bulge\n bulgenorm = 406. # msol/pc**3. at GC\n halometal = -1.6 # [Fe/H]\n halosig = 0.5 # standard devation of metallicity for halo\n halonorm = 0.03 # msol/pc**3 for GC (the normalization was truncated at 1 kpc, as it blows up as you approach GC)\n thinmetal = 0. # [Fe/H]\n thinsig = 0.20 # Standard Deviation of metallicity for thin disk\n thinnorm = 0.12 # Msol/pc**3 at GC\n thinhnorm = 55.4082/1202.43 # Msol/pc**3 at solar circle\n thickmetal = -0.6 # [Fe/H]\n thicksig = 0.5 # standard deviation in metallicity for the thick disk\n thicknorm = 0.03 # msol/pc**3 at GC\n thickhnorm = 0.028 # msol/pc**3 at GC\n\n # distance above plane\n tempz = np.sin(gallat)*dist \n # distance to target in plane\n tempprojection = np.cos(gallat)*dist \n # radial distance from the galactic center\n tempr = np.sqrt(soldistgc**2.+tempprojection**2.-2.*soldistgc*tempprojection*np.cos(gallong))\n\n # distance from galactic center for halo stars (i.e. those out of the plane of the galaxy)\n temphalodist = np.sqrt(tempr**2.+tempz**2.)\n \n # the following loop calculates X & Y\n # coordinates for each star. (0,0) is at\n # GC, (0,-8 kpc) for the sun\n x=temphalodist*0.\n y=temphalodist*0.\n tmp = (tempprojection**2.-tempr**2.-8000.**2)/(-2.*8000.*tempr)\n bd = np.where(tmp > 1.)\n tmp[bd] = 1.\n bd = np.where(tmp < -1.)\n tmp[bd] = -1.\n theta = np.arccos(tmp)\n if gallong >= np.pi :\n j=np.where(theta < np.pi/2.)\n if len(j) > 0 :\n x[j] = tempr[j]*np.sin(theta[j])\n beta = np.pi/2.-theta[j]\n y[j] = -tempr[j]*np.sin(beta)\n j2=np.where(theta >= np.pi/2.)\n if len(j2) > 0 :\n thetaprime = np.pi-theta[j2]\n x[j2] = tempr[j2]*np.sin(thetaprime)\n beta = np.pi/2. - thetaprime\n y[j2] = tempr[j2]*np.sin(beta)\n\n if gallong < np.pi :\n j=np.where(theta > np.pi/2.)\n if len(j) > 0 :\n thetaprime = np.pi-theta[j]\n x[j] = -tempr[j]*np.sin(theta[j])\n beta = np.pi/2.-thetaprime\n y[j] = tempr[j]*np.sin(beta)\n j2=np.where(theta <= np.pi/2.)\n if len(j2) > 0 :\n x[j2] = -tempr[j2]*np.sin(theta[j2])\n beta = np.pi/2.-theta[j2]\n y[j2] = -tempr[j2]*np.sin(beta) \n\n #convert X & Y to bulge X & Y, assuming a 15 degree shift for the bar. \n bulgecoordx = x*np.cos(bulgeangle)+y*np.sin(bulgeangle)\n bulgecoordy = -x*np.sin(bulgeangle)+y*np.cos(bulgeangle)\n\n # no bulge past 30 kpc\n bd=np.where(tempr > 30000.)\n if len(bd) > 0 :\n bulgecoordx[bd] = 100000.\n bulgecoordy[bd] = 100000.\n\n # triaxial bulge from Binney et al\n coords = (bulgecoordx**2.+(bulgecoordy**2.)/(bulgeeta**2.)+(tempz**2.)/(bulgezeta**2.))**(1./2.)\n\n #prior probabilities for the spatial and metallicity distribution functions. Separated the SFH into\n #its own probability as it is most likely to change. \n #triaxial bulge\n pbulge = bulgenorm*((np.exp(-(coords**2.)/(bulgescale**2.)))/((1.+coords/bulgetrunc)**1.8))\n # Burnett & Binney halo\n phalo= halonorm*(temphalodist/1000.)**(-3.39)\n # TRILEGAL halo\n halonorm = 1.e-4/(np.exp(-7.67*((8000./2698.)**0.25-1.)))\n phalo= halonorm*(np.exp(-7.67*((temphalodist/2698.)**0.25-1.)))\n\n # exponential relations for vertical disk distribituion\n # pthick = thicknorm*np.exp(-tempr/rthick-abs(tempz)/zthick)\n # pthin = thinnorm*np.exp(-tempr/rthin-abs(tempz)/zthin)\n # hyperbolic secant relations\n pthin = thinhnorm*(np.exp(-tempr/rthin)*1./np.cosh(0.5*tempz/zhthin)**2)\n pthick = thickhnorm*(np.exp(-tempr/rthick)*1./np.cosh(0.5*tempz/zhthick)**2)\n # metallicity priors\n if not nomet :\n pbulge*=np.exp(-(feh-bulgemetal)**2./(2.*bulgesig**2.))*1./(bulgesig*np.sqrt(2.*np.pi))\n phalo *= 1./(halosig*np.sqrt(2.*np.pi))*np.exp(-(feh-halometal)**2./(2.*halosig**2.))\n pthick *= 1./(thicksig*np.sqrt(2.*np.pi))*np.exp(-(feh-thickmetal)**2./(2.*thicksig**2.))\n pthin *= 1./(thinsig*np.sqrt(2.*np.pi))*np.exp(-(feh-thinmetal)**2./(2.*thinsig**2.))\n\n if plot :\n plt.plot(dist,np.log10(pthin))\n plt.plot(dist,np.log10(pthick))\n plt.plot(dist,np.log10(pbulge))\n plt.plot(dist,np.log10(phalo))\n return pthin,pthick,pbulge,phalo\n\n\ndef test() :\n dist=np.arange(0.,20.,0.1)\n out=galmodel(dist,0.,0.,0.)\n return out\n\ndef lbd2xyz(l,b,d,R0=8.5) :\n ''' Angular coordinates + distance -> galactocentry x,y,z '''\n\n brad = b*np.pi/180.\n lrad = l*np.pi/180.\n\n x = d*np.sin(0.5*np.pi-brad)*np.cos(lrad)-R0\n y = d*np.sin(0.5*np.pi-brad)*np.sin(lrad)\n z = d*np.cos(0.5*np.pi-brad)\n r = np.sqrt(x**2+y**2) \n return x, y, z, r\n\n","repo_name":"holtzmanjon/gal","sub_path":"galmodel.py","file_name":"galmodel.py","file_ext":"py","file_size_in_byte":6112,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"84"} +{"seq_id":"71577794194","text":"from wsgiref import headers\n\nimport boto3\nimport os\nimport json\nimport uuid\nfrom datetime import datetime\n\nclient = boto3.client('cognito-idp')\n\nCognitoUserPool = os.getenv('CongnitoPoolId')\n\n\ndef lambda_handler(message, context):\n print(\"COGNITO POOL ID:::::::: \", os.getenv('CongnitoPoolId'))\n if ('body' not in message or\n message['httpMethod'] != 'POST'):\n return {\n 'statusCode': 400,\n 'headers': {},\n 'body': json.dumps({'msg': 'Bad Request'})\n }\n table_name = os.environ.get('TABLE', 'water-billing-new')\n region = os.environ.get('REGION', 'ap-northeast-1')\n item_table = boto3.resource(\n 'dynamodb',\n region_name=region\n )\n\n table = item_table.Table(table_name)\n user = json.loads(message['body'])\n randomString = str(uuid.uuid4())\n params = {\n 'PK': \"USER#\",\n 'SK': \"USER#\" + randomString,\n 'firstName': user['firstName'],\n 'lastName': user['lastName'],\n 'isActive': user['isActive'],\n 'email': user['email'],\n 'phoneNumber': user['phoneNumber'],\n 'createdAt': str(datetime.timestamp(datetime.now())),\n \"GSI1PK\": \"USER#\" + randomString,\n \"GSI1SK\": \"USER#\"\n }\n\n dbResponse = table.put_item(\n TableName=table_name,\n Item=params\n )\n # response = client.sign_up(\n # ClientId=CognitoUserPool,\n # Username=user['email'],\n # Password=user['password'],\n # )\n\n response1 = client.admin_create_user(\n UserPoolId=CognitoUserPool,\n Username=user['email'],\n MessageAction='SUPPRESS',\n )\n\n print(\"RESPONSE 1:::: \", response1)\n response2 = client.admin_set_user_password(\n UserPoolId=CognitoUserPool,\n Username=user['email'],\n Password=user['password'],\n Permanent=True\n )\n\n reply1 = client.create_group(UserPoolId=CognitoUserPool, GroupName=user['role'])\n print(\"REPLY 1:::: \", reply1)\n reply2 = client.admin_add_user_to_group(UserPoolId=CognitoUserPool, Username=user['email'], GroupName=user['role'])\n print(\"Reply 2::::: \", reply2)\n print(\"RESPONSE 2:::: \", response2)\n return {\n \"statusCode\": 200,\n \"headers\": {},\n 'body': json.dumps(response1, indent=4, sort_keys=True, default=str), # default=decimal_default),\n }\n","repo_name":"mahadihasanjoy95/Cognito-Custom-Authorization-Lambda-AWS","sub_path":"user-stack/lamdas/createUser.py","file_name":"createUser.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"4727564230","text":"import random\n\nclass Hangman():\n def __init__(self,word_list,num_lives=5):\n self.word = random.choice(word_list)\n self.word_guessed = ['_'] * len(self.word)\n not_guessed = set(self.word)\n self.num_letters = len(not_guessed)\n self.num_lives = num_lives\n self.word_list = word_list\n self.list_of_guesses = []\n # self.letterList = list(self.word)\n\n # self.guess = ''\n\n def check_guess(self,guess):\n guess1 = guess.lower() \n if (guess1 in self.word):\n print(\"Good guess! \",guess1 ,\"is in the word.\")\n for letterIdx,letter in enumerate(self.word):\n if (letter == guess):\n self.word_guessed[letterIdx]=letter\n # print(letterIdx)\n self.num_letters -= 1\n print(self.word_guessed, \" / \", self.num_letters)\n else:\n self.num_lives -= 1\n print(\"Sorry, \",guess1, \" is not in the word. \")\n print(\"You have\", self.num_lives, \"lives left.\")\n\n self.list_of_guesses.append(guess)\n # self.list_of_guesses.append(guess)\n\n def ask_for_input(self): \n # while True:\n guess = input(\"Enter a letter\")\n if not(len(guess) == 1 and guess.isalpha() ):\n # break\n # else:\n print(\"Invalid letter. Please, enter a single alphabetical character.\")\n elif guess in self.list_of_guesses:\n print(\"You already tried that letter!\")\n print(self.list_of_guesses)\n else: \n self.check_guess(guess) \n # return guess\ndef play_game(game_word_list):\n # function \n game = Hangman(game_word_list,3)\n while True:\n if game.num_lives == 0:\n print(\"You lost\")\n break\n elif game.num_letters > 0:\n game.ask_for_input()\n else: \n print(\"Congratulations. You won the game!\")\n break\n\nplay_game([\"apple\",\"football\",\"mischief\",\"practise\",\"maintain\",\"maintenance\",\"winter\",\"butterfly\"])\n\n\n\n# print(game.word, game.num_letters)\n# print(type(game))\n# game.ask_for_input() i\n","repo_name":"pradxj07/pajaicore-Hangman","sub_path":"hangman/milestone_5.py","file_name":"milestone_5.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"20289354108","text":"'''\nA teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book.\n They always turn pages one at a time. When they open the book, page 1 is always on the right side:\n Example:\n n = 5, p = 3\n Given n and p, find and print the minimum number of pages that must be turned in order to arrive at page p.\n\n pageCount has the following parameter(s):\n\nint n: the number of pages in the book\nint p: the page number to turn to\nReturns\nint: the minimum number of pages to turn\n'''\nimport os\n\ndef pageCount(n, p):\n \n return min((n//2 - p//2),p//2)\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input().strip())\n\n p = int(input().strip())\n\n result = pageCount(n, p)\n print(result)\n fptr.write(str(result) + '\\n')\n\n fptr.close()","repo_name":"neetu-sh/HackerRank","sub_path":"DrawingBook.py","file_name":"DrawingBook.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"71869472913","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nanat_and_zmap_lut\n\nOverlay a QC image (e.g. CAT12 p0 images) onto another image (e.g. an anatomical T1w), while highlighting the segmentation using transparency.\n\nChristian Rubbert (christian.rubbert@med.uni-duesseldorf.de)\n\"\"\"\n\nimport argparse\nimport os\nimport sys\n\nfrom PIL import Image\nfrom PIL import ImageFont, ImageDraw, ImageOps, ImageFilter\n\nimport nibabel as nib\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as pla\nimport matplotlib.cm as cm\n\nimport colorcet as cc\n\ndef arg_parser():\n parser = argparse.ArgumentParser(description='Overlay a quality control (QC) image (e.g. CAT12 p0 images) onto another image (e.g. an anatomical T1w), while highlighting the segmentation using transparency.')\n parser.add_argument('anat_file', type=str, \n help='Path to the anatomical NIfTI image')\n parser.add_argument('qc_file', type=str, \n help='Path to the quality control (QC) NIfTI image')\n parser.add_argument('--transparency', type=int, default=25, choices=range(0,101), metavar=\"[0-100]\",\n help='Transparency of colour map in percent (default: 25)')\n parser.add_argument('out_dir', type=str, \n help='path to output the corresponding JPEG image slices')\n return parser\n\ndef main():\n try:\n # Parse arguments\n args = arg_parser().parse_args()\n\n # Load the anatomical and zmap NIfTI\n anat = nib.load(args.anat_file).get_fdata()\n qc = nib.load(args.qc_file).get_fdata()\n\n # Normalize anat\n anat = (anat / np.max(anat)) * np.max(qc)\n\n # In order to plot the anatomical slices with windowing, we need to apply the reverse Greys \"colour\" map\n grey = plt.get_cmap(\"Greys_r\")\n\n # Create an alpha channel for the quality control to highlight segmented areas\n # 0 = 100% transparency, 255 = 0% transparency/solid\n alpha_qc = np.copy(qc)\n alpha_qc[alpha_qc > 0] = 50\n alpha_qc[alpha_qc == 0] = 255 * (1 - (args.transparency / 100))\n\n # Create a binary mask of the QC volume for contour detection later on\n qc_binary = np.copy(qc)\n qc_binary[qc_binary > 0] = np.max(qc)\n\n # Default font and font colour\n fnt = ImageFont.truetype(os.path.dirname(os.path.realpath(__file__)) + \"/fonts/Beef'd.ttf\", 5)\n fnt_colour=\"#A9A9A9\"\n\n # For each slice of the anatomical image:\n # - Overlay an image for quality checking\n # - Resize by a factor of 2 to make text more visually pleasing\n # - Add legend and text and save as JPEG\n #\n for i in range(1, anat.shape[2]+1):\n sm = cm.ScalarMappable(cmap = grey)\n\n # Read the anatomical slice, creating a min/max scaled grey RGBA image\n A = Image.fromarray(sm.to_rgba(anat[:,:,i-1], bytes=True))\n\n # Read the QC image slice, creating a min/max scalred grey RGBA image\n C = Image.fromarray(sm.to_rgba(qc[:,:,i-1], bytes=True))\n\n # Use the previously defined alpha map, turn it into an image and use it as the alpha channel on C\n T = Image.fromarray(alpha_qc[:,:,i-1].astype(np.uint8))\n C.putalpha(T)\n\n # Read the previously defined binary mask, then ...\n B = Image.fromarray(sm.to_rgba(qc_binary[:,:,i-1], bytes=True))\n # ... find the outer contours and invert black/white\n E = B.filter(ImageFilter.CONTOUR).convert('L')\n E = ImageOps.invert(E)\n # Crop the outer 1 px border (which would otherwise be white)\n E = ImageOps.crop(E, (1, 1))\n\n # Overlay the QC image onto the anatomical images\n A.paste(C, (0, 0), C)\n # Overlay the outer contour of the binary mask onto both images (note that we nudge by 1 px after cropping above)\n A.paste(E, (1, 1), E)\n # Rotate and mirror for radiological orientation\n A = ImageOps.mirror(A.transpose(Image.ROTATE_90))\n # Resize by a factor of two to make the legend text drawn on the image more visually pleasing\n A = A.resize((A.width * 2, A.height * 2))\n\n # Add obligatory message \"NOT FOR DIAGNOSTIC USE\" to bottom center of the slice\n d = ImageDraw.Draw(A)\n msg = \"Not for diagnostic use\"\n w, h = d.textsize(msg, font = fnt)\n d.text(((A.width - w)/2, (A.height - 10)), msg, font = fnt, fill = fnt_colour)\n\n # Convert to RGB (from RGBA) and write the resulting image as JPEG\n A = A.convert(\"RGB\")\n A.save(os.path.join(args.out_dir, f'bia-slice{i:03}.jpg'), format = 'JPEG', subsampling = 0, quality = 100)\n return 0\n except Exception as e:\n print(e)\n return 1\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"BrainImAccs/veganbagel","sub_path":"tools/python/anat_qc.py","file_name":"anat_qc.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"84"} +{"seq_id":"17647650455","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom Utils.Paths import RESULTS_LOGS_DIR, FRAME_CONFIG_FILE_PATH\r\nfrom logging.handlers import TimedRotatingFileHandler\r\nfrom configparser import ConfigParser\r\nimport logging\r\nimport time\r\nimport os\r\n\r\ntry:\r\n config = ConfigParser()\r\n config.read(FRAME_CONFIG_FILE_PATH)\r\n _console_switch = config.get('LogConfig', 'ConsoleSwitch')\r\n ConsoleSwitch = True if _console_switch != 'False' else False\r\n _file_switch = config.get('LogConfig', 'FileSwitch')\r\n FileSwitch = True if _file_switch != 'False' else False\r\n ConsoleLevel = config.get('LogConfig', 'ConsoleLevel')\r\n FileLevel = config.get('LogConfig', 'FileLevel')\r\nexcept Exception as e:\r\n print('[FrameConfig.ini] read error: {0}'.format(e))\r\n ConsoleSwitch = True\r\n FileSwitch = True\r\n ConsoleLevel = 'INFO'\r\n FileLevel = 'DEBUG'\r\n\r\n\r\nclass Logger:\r\n def __init__(self, logger_name=__name__):\r\n self.logger = logging.getLogger(logger_name)\r\n logging.root.setLevel(logging.NOTSET)\r\n now_time = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\r\n self.log_file_name = '{0}.log'.format(now_time)\r\n if not os.path.exists(RESULTS_LOGS_DIR):\r\n os.makedirs(RESULTS_LOGS_DIR)\r\n self.log_file_path = os.path.join(RESULTS_LOGS_DIR, self.log_file_name)\r\n self.formatter = logging.Formatter('[%(asctime)s][%(levelname)s]: %(message)s')\r\n self.console_output_level = ConsoleLevel\r\n self.file_output_level = FileLevel\r\n self.backup_count = 20\r\n\r\n def get_logger(self, console_switch=ConsoleSwitch, file_switch=FileSwitch):\r\n \"\"\"在logger中添加日志句柄并返回,如果logger已有句柄,则直接返回\"\"\"\r\n if not self.logger.handlers:\r\n if console_switch:\r\n console_handler = logging.StreamHandler()\r\n console_handler.setLevel(self.console_output_level)\r\n console_handler.setFormatter(self.formatter)\r\n self.logger.addHandler(console_handler)\r\n if file_switch:\r\n file_handler = TimedRotatingFileHandler(filename=self.log_file_path, when='D', interval=1,\r\n backupCount=self.backup_count, delay=True, encoding='utf-8')\r\n file_handler.setLevel(self.file_output_level)\r\n file_handler.setFormatter(self.formatter)\r\n self.logger.addHandler(file_handler)\r\n return self.logger\r\n\r\n\r\nlogger = Logger().get_logger()\r\n\r\n\r\nif __name__ == '__main__':\r\n logger.info('hello world')\r\n","repo_name":"QAAutomationLearn/PythonAutomationFramework","sub_path":"Utils/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"84"} +{"seq_id":"4581467640","text":"''' Downloading meteorological data from site monitor.pogodynka.pl for three stations and save it to Excel files.\r\nIf Excel file exists, script does not delete already existed data, but append new sheet to existed file. So do not\r\nworry about overwriting.\r\nPython 3. Necessary packages:\r\n * Selenium\r\n * NumPy\r\n * Pandas\r\n * OpenPyXL\r\nVersion 2.0, 2017-08-30\r\nMaciej Barnaś, e-mail: maciej.michal.barnas(at)gmail.com '''\r\n\r\nimport selenium.webdriver as webdriver\r\nimport pandas as pd\r\nimport time\r\nimport re\r\nfrom openpyxl import load_workbook\r\nfrom pathlib import Path\r\n\r\n################################################################################\r\n\r\n# Input - fill urls of websites and output Excel filenames\r\nSiercza_url = 'http://monitor.pogodynka.pl/#station/meteo/249201010'\r\nSiercza_output = 'Siercza1.xlsx'\r\nWronowice_url = 'http://monitor.pogodynka.pl/#station/meteo/249200990'\r\nWronowice_output = 'Wronowice1.xlsx'\r\nLimanowa_url = 'http://monitor.pogodynka.pl/#station/meteo/249200180'\r\nLimanowa_output = 'Limanowa1.xlsx'\r\n\r\n################################################################################\r\n\r\ndriver = webdriver.Chrome() # Driver must be in the same folder as a script\r\n\r\n# Three rows for Opera browser\r\n#webdriver_service = service.Service('operadriver.exe')\r\n#webdriver_service.start()\r\n#driver = webdriver.Remote(webdriver_service.service_url, webdriver.DesiredCapabilities.OPERA)\r\n\r\nnowdate = time.strftime('%Y-%m-%d %H%M%S') # Now date - for name of sheet in Excel files\r\n\r\ndef download_and_save(url, output_filename):\r\n driver.get(url) # Open website\r\n time.sleep(10) # Website is loading, script waits\r\n\r\n raw_table = driver.find_element_by_xpath(\"//table[@class='table table-striped table-responsive table-bordered']\").\\\r\n get_attribute('outerHTML') # Find table with results\r\n\r\n # Prepare scrapped html code for making Pandas DataFrame from it\r\n table_temp = raw_table.split('(.*?) pd.DataFrame:\n \"\"\"\n Fetches weather data based on the latitude and longitude of user addresses.\n Args:\n merged_data (pd.DataFrame): The merged data containing sales and user information.\n Returns:\n pd.DataFrame: The merged data with added weather information.\n \"\"\"\n api_key = \"8a07d17a778413731d4440c41812b402\"\n for index, row in merged_data.iterrows():\n lat = row['address']['geo']['lat']\n lon = row['address']['geo']['lng']\n url = f\"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}\"\n try:\n response = requests.get(url, timeout=10)\n response.raise_for_status()\n weather_data = response.json()\n temperature = weather_data['main']['temp']\n description = weather_data['weather'][0]\n merged_data.at[index, 'temperature'] = temperature\n logger.debug(\"Added weather info to index %s: %s %s\", index, temperature, description)\n except requests.exceptions.RequestException as req_exc:\n logger.warning(\"An error occurred while fetching weather data: %s\", req_exc)\n merged_data.at[index, 'temperature'] = None\n merged_data.at[index, 'weather_description'] = 'Weather data unavailable'\n return merged_data\n","repo_name":"zaheer847/data_pipeline","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"30440152578","text":"from flask import render_template, request, redirect, url_for\nfrom flask_login import current_user, login_manager, login_required\nfrom sqlalchemy.sql import text\n\nfrom application import app, db\nfrom application.tracks.models import Track\n\n\n@app.route(\"/tracks\", methods=[\"GET\"])\n@login_required\ndef tracks_index():\n return render_template(\"tracks/listtracks.html\", tracks=Track.query.all(), \n basic_stats=Track.tracks_basic_stats(id=current_user.id))\n\n\n@app.route(\"/delete_track/\", methods=[\"POST\"])\n@login_required\ndef tracks_deleteone(id):\n stmt = text(\"DELETE FROM favoriteTracks WHERE track_id = :id\").params(id=id)\n db.engine.execute(stmt)\n Track.query.filter_by(id=id).delete()\n db.session.commit()\n\n return redirect(url_for(\"tracks_index\"))\n","repo_name":"saarasat/mariokart-stats","sub_path":"application/tracks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"84"} +{"seq_id":"24210013055","text":"from torchvision.models import detection\r\nimport numpy as np\r\nimport torch\r\nimport cv2\r\nimport pickle\r\n\r\n\r\n\r\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n#print(DEVICE)\r\n\r\nimage_path = \"pets.jpg\"\r\nconfidenece_1 = 0.5\r\nph = \"coco.pickle\"\r\n\r\nCLASSES = pickle.loads(open(ph,\"rb\").read())\r\nCOLORS = np .random.uniform(0, 255, size=(len(CLASSES), 3))\r\n\r\n#print(CLASSES)\r\n\r\nmodel = detection.fasterrcnn_resnet50_fpn(pretrained=True, progress=True,\r\n\tnum_classes=len(CLASSES), pretrained_backbone=True).to(DEVICE)\r\nmodel.eval()\r\n\r\nimage = cv2.imread(image_path)\r\norig = image.copy()\r\n\r\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\nimage = image.transpose((2, 0, 1))\r\n\r\nimage = np.expand_dims(image, axis=0)\r\nimage = image / 255.0\r\nimage = torch.FloatTensor(image)\r\n\r\nimage = image.to(DEVICE)\r\ndetections = model(image)[0]\r\n\r\nfor i in range(0, len(detections[\"boxes\"])):\r\n\t# extract the confidence (i.e., probability) associated with the\r\n\t# prediction\r\n\tconfidence = detections[\"scores\"][i]\r\n\r\n\t# filter out weak detections by ensuring the confidence is\r\n\t# greater than the minimum confidence\r\n\tif confidence > confidenece_1:\r\n\t\t# extract the index of the class label from the detections,\r\n\t\t# then compute the (x, y)-coordinates of the bounding box\r\n\t\t# for the object\r\n\t\tidx = int(detections[\"labels\"][i])\r\n\t\tbox = detections[\"boxes\"][i].detach().cpu().numpy()\r\n\t\t(startX, startY, endX, endY) = box.astype(\"int\")\r\n\r\n\t\t# display the prediction to our terminal\r\n\r\n\t\tlabel = \"{}: {:.2f}%\".format(CLASSES[idx-1], confidence * 100)\r\n\t\tprint(\"[INFO] {}\".format(label))\r\n\t\t# draw the bounding box and label on the image\r\n\t\tcv2.rectangle(orig, (startX, startY), (endX, endY),\r\n\t\t\tCOLORS[idx], 2)\r\n\t\ty = startY - 15 if startY - 15 > 15 else startY + 15\r\n\r\n\t\tcv2.putText(orig, label, (startX, y),\r\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)\r\n\r\n\r\n\r\ncv2.imshow(\"Output\", orig)\r\ncv2.waitKey(0)\r\n\r\n\r\n","repo_name":"AkashKhamkar/Object-Detectiong-using-pretrained-Fast-RCNN-with-Pytorch","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"84"} +{"seq_id":"8863016980","text":"from typing import List\n\nfrom sqlalchemy import select, delete\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom src.admin.blog_admin.blog import BlogPanel\nfrom fastapi import APIRouter, Query, Depends, HTTPException\n\nfrom src.admin.schemas.blog import NewsPatch, NewsCreate\nfrom src.api.handlers.login import get_current_user_from_token\nfrom src.database.models import News\nfrom src.database.session import get_db\nfrom uuid import UUID\n\nadmin_blog = APIRouter()\n\n\n@admin_blog.get(\"/blog_list\")\nasync def get_news(\n page_size: int = Query(5, ge=1),\n page: int = Query(1, ge=1),\n db: AsyncSession = Depends(get_db),\n user=Depends(get_current_user_from_token),\n):\n if user.roles != \"Admin\":\n raise HTTPException(detail=\"Permission denied\", status_code=403)\n blog_panel = BlogPanel(db=db)\n\n res = await blog_panel.get_bulk_blog(page=page, per_page=page_size)\n\n return res\n\n\n@admin_blog.get(\"/post\")\nasync def get_one(\n uuid: UUID,\n db: AsyncSession = Depends(get_db),\n user=Depends(get_current_user_from_token),\n):\n if user.roles != \"Admin\":\n raise HTTPException(detail=\"Permission denied\", status_code=403)\n blog_panel = BlogPanel(db=db)\n\n res = await blog_panel.get_one(uuid=uuid)\n\n return res\n\n\n@admin_blog.patch(\"/post\")\nasync def update_news(\n news_id: UUID,\n data: NewsPatch,\n db=Depends(get_db),\n user=Depends(get_current_user_from_token),\n):\n if user.roles != \"Admin\":\n raise HTTPException(detail=\"Permission denied\", status_code=403)\n async with db.begin():\n stmt = select(News).where(News.id_news == news_id)\n result = await db.execute(stmt)\n news = result.scalar()\n\n if news is None:\n raise HTTPException(status_code=404, detail=\"News not found\")\n\n # Update only the fields that are present in the request data\n for field, value in data.model_dump().items():\n if hasattr(News, field):\n setattr(news, field, value)\n\n await db.commit()\n await db.refresh(news)\n return news\n\n\n@admin_blog.post(\"/create\")\nasync def create_news(\n news_data: NewsCreate, db=Depends(get_db), user=Depends(get_current_user_from_token)\n):\n if user.roles != \"Admin\":\n raise HTTPException(detail=\"Permission denied\", status_code=403)\n async with db.begin():\n news = News(**news_data.model_dump())\n await db.add(news)\n await db.flush() # Use flush() instead of commit()\n await db.refresh(news)\n return news\n\n\n@admin_blog.delete(\"/blog\")\nasync def delete_news(\n news_id: List[UUID],\n db: AsyncSession = Depends(get_db),\n user=Depends(get_current_user_from_token),\n):\n if user.roles != \"Admin\":\n raise HTTPException(detail=\"Permission denied\", status_code=403)\n\n news_for_delete = []\n for uuid in news_id:\n stmt = select(News).where(News.id_news == uuid)\n news = await db.scalar(stmt)\n await db.delete(news)\n if news_for_delete is None:\n raise HTTPException(status_code=404, detail=\"News not found\")\n\n await db.flush()\n return \"News was deleted\"\n","repo_name":"justiksss/Backend","sub_path":"src/admin/routers/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"30618819531","text":"import django.conf.global_settings as DEFAULT_SETTINGS\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '45@qqvbavfu*3)@e6vs#z8tp0_l^q^)aota0)2_lw^fh(96rim'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = ['www.ain7.com', 'ain7.com', 'www.ain7.org', 'ain7.org']\n\n# Application definition\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.sitemaps',\n)\n\nMIDDLEWARE_CLASSES = (\n 'ain7.middleware.forcelocale.ForceDefaultLanguageMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'ain7.urls'\n\nWSGI_APPLICATION = 'ain7.wsgi.application'\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'fr'\nTIME_ZONE = 'Europe/Paris'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\nSTATIC_URL = '/static/'\nMEDIA_URL = '/site_media/'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [ BASE_DIR + '/ain7/templates', ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'ain7.context_processors.piwik',\n 'ain7.context_processors.user_groups',\n ],\n }\n }\n]\n\nDEFAULT_FROM_EMAIL = 'AIn7 '\n\n# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n# EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'\n# EMAIL_FILE_PATH = '/tmp/app-messages'\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\nEMAIL_HOST = 'localhost'\nEMAIL_PORT = 1025\nEMAIL_HOST_USER = ''\nEMAIL_HOST_PASSWORD = ''\n\nSITE_ID = 1\n\n# autocomplete_light\nINSTALLED_APPS += (\n 'autocomplete_light',\n)\n\n# celery configuration\n# INSTALLED_APPS += (\n# 'kombu.transport.django',\n#)\nBROKER_URL = 'django://'\n# BROKER_URL = 'redis://localhost:6379/0'\nCELERY_IMPORTS = (\"ain7.tasks\",)\n\n# endless configuration\nINSTALLED_APPS += (\n 'el_pagination',\n)\nEL_PAGINATION_PER_PAGE = 25\n\n# django-crispy-forms\nINSTALLED_APPS += (\n 'crispy_forms',\n)\nCRISPY_TEMPLATE_PACK = 'bootstrap3'\n\nINSTALLED_APPS += (\n 'django_extensions',\n)\n\n# auth and allauth settings\n#INSTALLED_APPS += (\n# 'allauth',\n# 'allauth.account',\n# 'allauth.socialaccount',\n# 'allauth.socialaccount.providers.facebook',\n# 'allauth.socialaccount.providers.google',\n# 'allauth.socialaccount.providers.linkedin',\n#)\n#AUTHENTICATION_BACKENDS = DEFAULT_SETTINGS.AUTHENTICATION_BACKENDS + (\n# 'allauth.account.auth_backends.AuthenticationBackend',\n#)\n#TEMPLATE_CONTEXT_PROCESSORS += (\n# 'allauth.account.context_processors.account',\n# 'allauth.socialaccount.context_processors.socialaccount',\n# 'ain7.context_processors.piwik',\n# 'ain7.context_processors.user_groups',\n#)\n\n\nLOGIN_REDIRECT_URL = '/'\n#SOCIALACCOUNT_QUERY_EMAIL = True\n\n#SOCIALACCOUNT_PROVIDERS = {\n# 'google': {\n# 'SCOPE': ['profile', 'email'],\n# 'AUTH_PARAMS': {'access_type': 'online'}\n# }\n#}\n\n# AIn7 specific stuff\n\nINSTALLED_APPS += (\n 'ain7',\n 'ain7.adhesions',\n 'ain7.annuaire',\n 'ain7.association',\n 'ain7.emploi',\n 'ain7.groups',\n 'ain7.manage',\n 'ain7.news',\n 'ain7.organizations',\n 'ain7.pages',\n 'ain7.shop',\n 'ain7.voyages',\n)\n\nMIDDLEWARE_CLASSES += (\n 'ain7.middleware.useractivity.UserActivityMiddleware',\n 'ain7.middleware.forcelocale.ForceDefaultLanguageMiddleware',\n 'ain7.middleware.portalexceptions.PortalException',\n)\n\n#TEMPLATE_CONTEXT_PROCESSORS += (\n# 'ain7.context_processors.piwik',\n# 'ain7.context_processors.user_groups',\n#)\n\n#STATICFILES_DIRS = (\n# os.path.join(BASE_DIR, 'ain7', 'static'),\n#)\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'ain7', 'media')\nSTATIC_ROOT = os.path.join(BASE_DIR, 'ain7', 'static')\n\nPIWIK_ENABLED = False\nPIWIK_URL = 'http://localhost/piwik/'\nPIWIK_SITE_ID = '0'\n\nPORTAL_ADMIN = 'ain7-admin'\nAIN7_MEMBERS = 'ain7-membre'\nAIN7_CONTRIBUTORS = 'ain7-contributor'\n\nFACEBOOK_AIN7 = 'http://www.facebook.com/ENSEEIHT'\nLINKEDIN_AIN7 = 'http://www.linkedin.com/groups?gid=73525'\nTWITTER_AIN7 = 'http://twitter.com/ENSEEIHT_Alumni'\nGPLUS_AIN7 = 'https://plus.google.com/s/enseeiht#105806841193732839789/posts'\n\nSYSTEM_PAY_URL = 'http://localhost'\nSYSTEM_PAY_SITE_ID = '123456789'\nSYSTEM_PAY_CERTIFICATE = '1234567890912345'\nSYSTEM_PAY_MODE = 'TEST'\n\nAIN7_SIRET = '0000000000000001-001'\n\nREGISTRATION = True\n\nfrom django.contrib.messages import constants as message_constants\nMESSAGE_TAGS = {\n message_constants.ERROR: 'danger',\n}\n\ntry:\n from settings_local import *\nexcept ImportError:\n pass\n","repo_name":"ain7/www.ain7.org","sub_path":"ain7/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6075,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"84"} +{"seq_id":"6239274216","text":"a = int(input('Podaj a dla ax^2 + bx + c = 0: '))\nb = int(input('Podaj b dla ax^2 + bx + c = 0: '))\nc = int(input('Podaj c dla ax^2 + bx + c = 0: '))\n\nprint(a,'x^2 + ', b ,'x + ', c ,' = 0')\n\ndelta = b**2 - 4*a*c\n\n\nif delta < 0:\n print('Brak miejsc zerowych dla tego równania!')\nelif delta == 0:\n x0 = (-b) / 2*a\n print('Równanie ma jeden pierwaistek! x0 = ', x0)\nelse:\n x1 = (-b - delta**(1/2)) / 2*a\n x2 = (-b + delta**(1/2)) / 2*a\n print('Równanie ma dwa pierwiasktki!! x1 = ', x1, 'x2 = ' , x2)","repo_name":"kzlamaniec/Python-Beginnings-2018","sub_path":"02 - 13 pierwiastki równania kwadratowego.py","file_name":"02 - 13 pierwiastki równania kwadratowego.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"5366151479","text":"# import file view.py , data.py\nfrom App.View.View import ModeView, ShowGame\nfrom App.Data.Data import DataView\n\nprint('\\nKuis Matematika (v2.0)')\nprint('@dharma_situmorang')\n\n# Player's Name\n# You can directly give your name if you don't like it use input \nplayerName = input('\\nNama Kamu >> ')\n\n# Base Mode , history score\nmodeGame = 0\nMyHistoryScore = []\nwhile modeGame != 9:\n ModeView(DataView())\n try:\n # user choice the game mode\n modeGame = int(input('\\nMode >> '))\n ShowGame({\n 'playerName': playerName,\n 'history': MyHistoryScore,\n 'mode': modeGame\n })\n\n except ValueError:\n print('Pilih hanya kategori diatas saja\\n')\n \nprint('\\nGood Bye!!! :)')","repo_name":"luhur65/kuis-matematika","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"84"} +{"seq_id":"70454133075","text":"import torch\nimport numpy as np\nimport copy\nimport multiprocessing as mp\n\nfrom RL.models.build_agent_model import build_agent_model\nfrom env.wrapper import EnvWrapper\n\ndef worker(remote: mp.connection.Connection, parent_remote: mp.connection.Connection, shared_queue: mp.Queue,\n worker_id=0) -> None:\n parent_remote.close()\n\n torch.set_num_threads(1)\n\n env = EnvWrapper(dense_reward=True)\n env.reset()\n policy = build_agent_model(device=\"cpu\")\n\n gamma = None\n\n initial_state_to_load = None\n starting_hidden_states = None\n starting_observation = None\n\n first_actions_under_consideration = None\n player_hidden_states_after_first_ac = None\n controlling_player_id = None\n\n while True:\n cmd, data = remote.recv()\n if cmd == \"initialise_policy\":\n state_dict, controlling_player_id, gamma = data.var\n policy.load_state_dict(state_dict)\n policy.eval()\n remote.send(True)\n elif cmd == \"set_start_states\":\n initial_state_to_load, starting_hidden_states, starting_observation = data.var\n remote.send(True)\n elif cmd == \"set_initial_actions\":\n first_actions_under_consideration, player_hidden_states_after_first_ac = data.var\n remote.send(True)\n elif cmd == \"run_simulation\":\n remote.send(True) #let main process know it's started simulation.\n env.reset()\n env.restore_state(initial_state_to_load)\n env.game.randomise_uncertainty(controlling_player_id)\n\n init_ac_id = data[0]\n max_depth = data[1]\n\n pred_val = run_simulation_forward(env, policy, player_id=controlling_player_id,\n init_action=first_actions_under_consideration[init_ac_id],\n init_player_hs=player_hidden_states_after_first_ac[init_ac_id],\n curr_hidden_states = copy.deepcopy(starting_hidden_states),\n curr_obs = copy.deepcopy(starting_observation),\n max_depth=max_depth, gamma=gamma)\n\n shared_queue.put((pred_val, init_ac_id, worker_id))\n\n\ndef run_simulation_forward(env, policy, player_id, init_action, init_player_hs, curr_hidden_states, curr_obs,\n max_depth=20, gamma=0.999):\n current_observations = {player_id: curr_obs}\n actual_rewards = []\n values = []\n\n agent_actions = 0\n game_finished = False\n\n #first step\n next_obs, reward, done, _ = env.step(init_action)\n next_obs = policy.obs_to_torch(next_obs)\n agent_actions += 1\n curr_hidden_states[player_id] = init_player_hs\n actual_rewards.append(reward[player_id])\n if done:\n return actual_rewards[0]\n n_players_go = get_players_turn(env)\n current_observations[n_players_go] = next_obs\n\n while agent_actions < max_depth:\n players_go = get_players_turn(env)\n obs = current_observations[players_go]\n hidden_state = curr_hidden_states[players_go]\n action_masks = policy.act_masks_to_torch(env.get_action_masks())\n terminal_mask = torch.ones(1,1)\n\n value, action, _, next_hidden_state = policy.act(\n obs, hidden_state, terminal_mask, action_masks\n )\n\n if policy.use_value_normalisation:\n value = policy.value_normaliser.denormalise(value)\n\n curr_hidden_states[players_go] = copy.copy(next_hidden_state)\n\n next_obs, reward, done, _ = env.step(policy.torch_act_to_np(action))\n\n if players_go == player_id:\n agent_actions += 1\n actual_rewards.append(reward[player_id])\n values.append(value.squeeze().cpu().data.numpy())\n elif done:\n actual_rewards.append(reward[player_id])\n\n n_players_go = get_players_turn(env)\n current_observations[n_players_go] = policy.obs_to_torch(next_obs)\n\n if done:\n game_finished = True\n break\n\n final_val_est = gae(values, actual_rewards, gamma=gamma, done=game_finished)\n return final_val_est\n\n\ndef gae(values, rewards, gamma, done):\n \"\"\"generalised advantage estimation\"\"\"\n gae_lambda = 0.95\n\n if len(values) <= 1:\n return rewards[0] + gamma * rewards[1]\n\n first_rew = rewards[0]\n rewards_for_gae = rewards[1:-1]\n values_for_gae = values[:-1]\n if done:\n final_value = 0.0\n else:\n final_value = values[-1]\n num_steps = len(values_for_gae) - 1\n values.append(final_value)\n values = np.array(values)\n\n gae = 0.0\n for step in reversed(range(num_steps)):\n delta = rewards_for_gae[step] + gamma * values_for_gae[step + 1] - values_for_gae[step]\n if step == (num_steps - 1) and done:\n gae = delta\n else:\n gae = delta + gamma * gae_lambda * gae\n returns_from_state = gae + values_for_gae[0]\n return first_rew + gamma * returns_from_state\n\n\ndef get_players_turn(env):\n if env.game.must_respond_to_trade:\n player_id = env.game.proposed_trade[\"target_player\"]\n else:\n player_id = env.game.players_go\n return player_id","repo_name":"henrycharlesworth/settlers_of_catan_RL","sub_path":"RL/forward_search_policy/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"84"} +{"seq_id":"72989159956","text":"from typing import TYPE_CHECKING\n\nfrom qbraid.exceptions import ProgramTypeError, QasmError, VisualizationError\nfrom qbraid.qasm_checks import get_qasm_version\n\nif TYPE_CHECKING:\n import qbraid\n\n\ndef circuit_drawer(program: \"qbraid.QPROGRAM\", output=None, **kwargs) -> None:\n \"\"\"Draws circuit diagram.\n\n Args:\n :data:`~.qbraid.QPROGRAM`: Supported quantum program\n\n Raises:\n ProgramTypeError: If quantum program is not of a supported type\n \"\"\"\n if isinstance(program, str):\n try:\n package = get_qasm_version(program)\n except QasmError as err:\n raise ProgramTypeError(\n \"Input of type string must represent a valid OpenQASM program.\"\n ) from err\n else:\n try:\n package = program.__module__\n except AttributeError as err:\n raise ProgramTypeError(program) from err\n\n # pylint: disable=import-outside-toplevel\n\n if \"qiskit\" in package:\n from qiskit.visualization import circuit_drawer as qiskit_drawer\n\n return qiskit_drawer(program, output=output, **kwargs)\n\n if \"braket\" in package:\n if output in (None, \"ascii\"):\n from braket.circuits.ascii_circuit_diagram import AsciiCircuitDiagram\n\n return print(AsciiCircuitDiagram.build_diagram(program))\n raise VisualizationError('The only valid option for braket are \"ascii\"')\n\n if \"cirq\" in package:\n if output in (None, \"text\"):\n return print(program.to_text_diagram(**kwargs))\n if output == \"svg\":\n from cirq.contrib.svg import SVGCircuit\n\n # coverage: ignore\n return SVGCircuit(program)\n if output == \"svg_source\":\n from cirq.contrib.svg import circuit_to_svg\n\n return circuit_to_svg(program)\n raise VisualizationError('The only valid option for cirq are \"text\", \"svg\", \"svf_source\"')\n\n if \"pyquil\" in package:\n if output is None or output == \"text\":\n return print(program)\n if output == \"latex\":\n from pyquil.latex import display\n\n # coverage: ignore\n return display(program, **kwargs)\n raise VisualizationError('The only valid option for pyquil are \"text\", \"latex\"')\n\n if \"pytket\" in package:\n if output in (None, \"jupyter\"):\n from pytket.circuit.display import render_circuit_jupyter\n\n # coverage: ignore\n return render_circuit_jupyter(program) # Render interactive display\n if output == \"view_browser\":\n from pytket.circuit.display import view_browser\n\n # coverage: ignore\n return view_browser(program, **kwargs)\n if output == \"html\":\n from pytket.circuit.display import render_circuit_as_html\n\n # coverage: ignore\n return render_circuit_as_html(program, **kwargs)\n raise VisualizationError(\n 'The only valid option for pytket are \"jupyter\", \"view_browser\", \"html\"'\n )\n\n if package == \"qasm3\":\n from qbraid.interface.qbraid_qasm3.circuit_drawer import draw_circuit\n\n # coverage: ignore\n return print(draw_circuit(program))\n\n if package == \"qasm2\":\n from qbraid.interface.qbraid_qasm3.tools import convert_to_qasm3\n\n # coverage: ignore\n qasm3_str = convert_to_qasm3(program)\n return print(draw_circuit(qasm3_str))\n\n raise ProgramTypeError(package)\n","repo_name":"qBraid/qBraid","sub_path":"qbraid/interface/circuit_drawer.py","file_name":"circuit_drawer.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"84"} +{"seq_id":"71395219476","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nboxdim = 12.5\n\ndef readxyz(filename,datatype):\n file = open(filename + \".xyz\", \"r\")\n contents = file.readlines()\n n = int(contents[0])\n print(n)\n contents = [i.split() for i in contents if len(i) > 1]\n atoms = []\n names = []\n relevent = []\n for i in range(len(contents)):\n if len(contents[i])>1:\n relevent.append(contents[i])\n else:\n pass\n for j in range(n):\n atoms.append([])\n names.append(relevent[j][0])\n for i in range(len(relevent)):\n index = i%n\n atoms[index].append(relevent[i][1:])\n\n atoms = np.array(atoms)\n atoms = atoms.astype(datatype)\n stepsn = len(atoms[0])\n return atoms,stepsn,n,names\n\ndef readtxtfile(filename,datatype):\n file = open(filename + \".txt\",\"r\")\n contents = file.readlines()\n file.close()\n for i in range(len(contents)):\n contents[i] = contents[i][:-1] # to remove the new line \"\\n\" symbol\n return np.array(contents).astype(datatype)\n\ndef ruler(pos1,pos2):\n boxdim=12.5\n diff = np.array(pos1)-np.array(pos2)\n adj = (diff+boxdim*0.5)%boxdim-boxdim*0.5\n return np.linalg.norm(adj)\n\ndef meansqrdisp(atoms,steps,n):\n boxdim=12.5 #find a way to read this in\n msds = []\n for i in range(steps):\n d = []\n for j in range(len(atoms)):\n d.append(ruler(atoms[j][i],atoms[j][0]))\n sd = list(map(lambda x: x**2, d))\n sumsd = sum(sd)\n normedsum = sumsd/len(atoms)\n msds.append(normedsum)\n return(msds)\n\ndef gofr(atoms,steps):\n bins = 5\n ds = []\n for k in range(steps):\n d = []\n for i in range(len(atoms)):\n for j in range(i+1,len(atoms)):\n d.append(ruler(atoms[i][k],atoms[j][k]))\n d = np.array(d)\n ds.append(d)\n sumds = sum(ds)\n avsum = np.array(sumds)/(steps)\n\n hist,edges = np.histogram(avsum,bins)\n dr = edges[1]-edges[0]\n numdens = len(atoms)/(boxdim**3)\n r = edges+(dr/2)\n normalising_factor = (4*numdens*np.pi*dr*r**2)\n ys = (hist/normalising_factor[:-1])\n return ys, r\n\ndef gofrav(atom,atoms,steps):\n#not normalised\n numdens = len(atoms)/(boxdim**3)\n ds = []\n for j in range(steps):\n d=[]\n for i in range(len(atoms)):\n d.append(ruler(atoms[atom][j],atoms[i][j]))\n d = np.array(d)\n ds.append(d)\n sumds = sum(ds)\n avsum = np.array(sumds)/(steps*boxdim)\n return avsum\n\ndef selection(names,atoms,selection):\n newatoms = []\n for i in range(len(names)):\n if names[i] == selection:\n newatoms.append(atoms[i])\n else:\n pass\n return newatoms\n\ndef main():\n\n times = [i*0.5e-15 for i in range(steps)]\n\n atoms,steps,n,names = readxyz(\"/home/s1624534/Mine/icymoons/thomas/castep\",float)\n msds = meansqrdisp(atoms,steps,n)\n plt.plot(times,msds)\n plt.xlabel(\"time\")\n plt.ylabel(\"mean square displacement\")\n plt.show()\n\n carbons=selection(names,atoms, \"C\")\n msds = meansqrdisp(carbons,steps,n)\n plt.plot(times,msds)\n plt.xlabel(\"time\")\n plt.ylabel(\"mean square displacement\")\n plt.show()\n\n oxygens=selection(names,atoms, \"O\")\n msds = meansqrdisp(oxygens,steps,n)\n plt.plot(times,msds)\n plt.xlabel(\"timestep\")\n plt.ylabel(\"mean square displacement\")\n plt.show()\n '''\n\n distribution,r = gofr(atoms,steps)\n print(distribution)\n print(r)\n plt.plot(r[:-1],distribution)\n plt.show()\n #plt.hist(distribution,bins = 50)\n #plt.xlabel(\"distance (angstroms)\")\n #plt.show()\n '''\n\nmain()\n","repo_name":"gralster/icymoons","sub_path":"readxyz.py","file_name":"readxyz.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"73533044113","text":"def roundHalfUp(d):\n # Round to nearest with ties going away from zero.\n import decimal\n rounding = decimal.ROUND_HALF_UP\n return int(decimal.Decimal(d).to_integral_value(rounding=rounding))\n\n# Citation: http://clintbellanger.net/articles/isometric_math/\ndef mapToIso(row, col, cols, halfWidth, halfHeight, screen):\n iso_x = (row-col) * halfWidth\n iso_y = (row+col) * halfHeight\n # adjust the coordinates to be on the center\n newIso_x = iso_x + screen.get_rect().centerx - halfWidth\n newIso_y = iso_y + screen.get_rect().centery - cols*halfHeight\n return (newIso_x, newIso_y)\n \n# Citation: http://clintbellanger.net/articles/isometric_math/\ndef isoToMap(iso_x, iso_y, cols, halfWidth, halfHeight, screen):\n iso_x = iso_x - screen.get_rect().centerx + halfWidth - halfWidth\n iso_y = iso_y - screen.get_rect().centery + halfHeight*cols - halfHeight\n row = 1/2*(iso_x/halfWidth+iso_y/halfHeight)\n col = 1/2*(iso_y/halfHeight - iso_x/halfWidth)\n return (round(row), round(col))","repo_name":"ameliakuang/112TP","sub_path":"trial/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"32938137608","text":"class Solution:\n\tdef dist(self, a,b):\n\t\tx_dist = abs(int(a[0])-int(b[0]))\n\t\ty_dist = abs(int(a[1])-int(b[1]))\n\t\tdiags = min(x_dist,y_dist)\n\n\t\treturn diags + abs(x_dist - y_dist)\n\n\tdef coverPoints(self, X, Y):\n\t\tarr = []\n\t\tfor j in range(len(X)):\n\t\t\tarr.append((X[j], Y[j]))\n\t\tcurr = arr[0]\n\t\tcounter = 0\n\t\tfor i in range(1, len(arr), 1):\n\t\t\tnext = arr[i]\n\t\t\tcounter += self.dist(curr, next)\n\t\t\tcurr = next\n\n\t\treturn counter\n","repo_name":"shubh24/competitive","sub_path":"competitive/Min Steps in Infinite GridBookmark.py","file_name":"Min Steps in Infinite GridBookmark.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"38055203481","text":"import boto3\nfrom decimal import Decimal\nimport json\nimport os\nfrom helper import AwsHelper, S3Helper, DynamoDBHelper\nimport datastore\n\ndef callRekognition(bucketName, objectName, apiName):\n rekognition = AwsHelper().getClient('rekognition')\n \n if(apiName == \"labels\"):\n response = rekognition.detect_labels(\n Image={\n 'S3Object': {\n 'Bucket': bucketName,\n 'Name': objectName\n }\n }\n )\n elif (apiName == \"text\"):\n response = rekognition.detect_text(\n Image={\n 'S3Object': {\n 'Bucket': bucketName,\n 'Name': objectName\n }\n }\n )\n elif (apiName == \"faces\"):\n response = rekognition.detect_faces(\n Image={\n 'S3Object': {\n 'Bucket': bucketName,\n 'Name': objectName\n }\n }\n )\n elif (apiName == \"moderation\"):\n response = rekognition.detect_moderation_labels(\n Image={\n 'S3Object': {\n 'Bucket': bucketName,\n 'Name': objectName\n }\n }\n )\n elif (apiName == \"celebrities\"):\n response = rekognition.recognize_celebrities(\n Image={\n 'S3Object': {\n 'Bucket': bucketName,\n 'Name': objectName\n }\n }\n )\n else:\n response = rekognition.detect_labels(\n Image={\n 'S3Object': {\n 'Bucket': bucketName,\n 'Name': objectName\n }\n }\n )\n return response\n\n\ndef processImage(itemId, bucketName, objectName, outputBucketName, itemsTableName):\n\n \n apiName = objectName.split(\"/\")[0]\n\n response = callRekognition(bucketName, objectName, apiName)\n\n print(\"Generating output for ItemId: {}\".format(itemId))\n print(response)\n\n outputPath = \"sync/{}-analysis/{}/\".format(objectName, itemId)\n opath = \"{}response.json\".format(outputPath)\n S3Helper.writeToS3(json.dumps(response), outputBucketName, opath)\n\n #opg = OutputGenerator(itemId, response, bucketName, objectName, detectForms, detectTables, ddb)\n #opg.run()\n\n print(\"ItemId: {}\".format(itemId))\n\n ds = datastore.ItemStore(itemsTableName)\n ds.markItemComplete(itemId)\n\n# --------------- Main handler ------------------\n\ndef processRequest(request):\n\n output = \"\"\n\n print(\"request: {}\".format(request))\n\n bucketName = request['bucketName']\n objectName = request['objectName']\n itemId = request['itemId']\n outputBucket = request['outputBucket']\n itemsTable = request['itemsTable']\n itemsTable = request[\"itemsTable\"]\n \n if(itemId and bucketName and objectName):\n print(\"ItemId: {}, Object: {}/{}\".format(itemId, bucketName, objectName))\n\n processImage(itemId, bucketName, objectName, outputBucket, itemsTable)\n\n output = \"Item: {}, Object: {}/{} processed.\".format(itemId, bucketName, objectName)\n print(output)\n\n return {\n 'statusCode': 200,\n 'body': output\n }\n\ndef lambda_handler(event, context):\n\n print(\"event: {}\".format(event))\n message = json.loads(event['Records'][0]['body'])\n print(\"Message: {}\".format(message))\n\n request = {}\n request[\"itemId\"] = message['itemId']\n request[\"bucketName\"] = message['bucketName']\n request[\"objectName\"] = message['objectName']\n request[\"outputBucket\"] = os.environ['OUTPUT_BUCKET']\n request[\"itemsTable\"] = os.environ['ITEMS_TABLE']\n\n return processRequest(request)\n","repo_name":"aws-samples/amazon-rekognition-serverless-large-scale-image-and-video-processing","sub_path":"src/syncproc.py","file_name":"syncproc.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"84"} +{"seq_id":"22490807067","text":"from flask import Flask, request, jsonify, render_template\nimport joblib\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\nfrom flask_cors import CORS\n\nimport logging\n\napp = Flask(__name__)\nCORS(app)\n\n# load the pre-trained model and vectorizer\nmodel, vectorizer = None, None\n\n\n@app.route(\"/\")\ndef home():\n return \"

Text Prediction

\"\n\n\n# return \"\"\"\n# \n# \n# Text Prediction\n# \n# \n#

Text Prediction

\n#
\n#
\n#

\n# \n#
\n# \n# \n# \"\"\"\n\n\n@app.route(\"/predict\", methods=[\"POST\", \"OPTIONS\"])\ndef predict():\n # return \"Hello cross-origin-world!\"\n # initialize the data dictionary that will be returned from the view\n data = {\"success\": False}\n\n # ensure text was properly submitted to our endpoint\n if request.method == \"POST\":\n # if request.form.get(\"text\"):\n # read the text from the form\n # text = request.form.get(\"text\")\n text = request.get_json()[\"inputField\"]\n print(text)\n # since we are using just one text sample, we need to convert it to a list and then to a numpy array for vectorization\n\n try:\n # preprocess the text\n text_vector = vectorizer.transform([text])\n\n # classify the input text and then initialize the list of predictions to return to the client\n prediction = model.predict(text_vector)\n data[\"prediction\"] = str(prediction[0])\n\n # indicate that the request was a success\n data[\"success\"] = True\n\n except Exception as e:\n # log the error\n logging.error(str(e))\n\n # indicate that an error occurred\n data[\"error\"] = \"An error occurred while making the prediction.\"\n\n # return the data dictionary as a JSON response\n return data\n\n\ndef load_model():\n global model\n # load the pre-trained model\n model = joblib.load(\"model/pa_model.pkl\")\n\n\ndef load_vectorizer():\n global vectorizer\n # load the pre-trained vectorizer\n vectorizer = joblib.load(\"model/vectorizer.pkl\")\n\n\nif __name__ == \"__main__\":\n print(\n (\n \"* Loading model and starting Flask server...\"\n \"please wait until the server has fully started\"\n )\n )\n # load the model and vectorizer\n load_model()\n load_vectorizer()\n app.run()\n","repo_name":"jonasmaximilian/FakeNewsAnalyzerApp","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"39013970589","text":"import pymysql\nimport pymysql.cursors\nimport json\ndef dbReconnect():\n def real_decorator(function):\n def wrapper(*args, **kwargs):\n try:\n return function(*args, **kwargs)\n except Exception as inst:\n print (\"DB error({0}):\".format(inst))\n print (\"Reconnecting\")\n job.conn=None\n job.setConn()\n return function(*args, **kwargs)\n return wrapper\n return real_decorator\nclass job:\n #(jobId:String,jobClass:String,jobPrams:String)\n conn=None\n @staticmethod\n def setConn():\n if job.conn != None:\n #check for dead connection\n testCursor=job.conn.cursor()\n testCursor.execute(\"select 1\")\n rows = testCursor.fetchall()\n if len(rows) <=0:\n jon.conn = None\n testCursor.close()\n if job.conn==None :\n job.conn = pymysql.connect(host='45.55.0.197',\n database='jobdb',\n user='vvaradar',\n password='arjkar123')\n if job.conn==None:\n print('Connect to database not made - aborting!' )\n sys.exit(1)\n @staticmethod\n def getJob(jobId,jobClass,jobParams):\n job=[]\n job.append(jobId)\n job.append(jobClass)\n job.append(jobParams)\n return job\n @staticmethod \n @dbReconnect()\n def getJobList(categ):\n #job.setConn()\n sql= \"select j.jobId,j.jobClass,j.jobParams from jobs j inner join jobCategory jc \" \\\n + \" on j.jobid=jc.jobid and jc.category='\"+categ+\"'\"\n print(sql)\n try:\n testCursor=job.conn.cursor()\n testCursor.execute(sql)\n jobList=[] #return array of jobs - each job an array of Strings\n hdr=testCursor.description #returns an array of nm, type,etc for each column\n jobList.append(job.getJob(hdr[0][0],hdr[1][0],hdr[2][0]))\n for row in testCursor:\n jobList.append(job.getJob(row[0],row[1],row[2]))\n testCursor.close()\n return jobList \n except Exception as e:\n print(e)\n raise\n \n \n @staticmethod \n @dbReconnect()\n def getJobCategList():\n job.setConn()\n sql = \"select distinct category from jobCategory\"\n try:\n testCursor=job.conn.cursor()\n testCursor.execute(sql)\n categList=[] #return array of jobs - each job an array of Strings\n for row in testCursor:\n categList.append(row[0])\n return categList \n except Exception as e:\n print(e)\n finally:\n testCursor.close()\n @staticmethod\n def getJobListOld():\n jobList=[] #return array of jobs - each job an array of Strings\n jobList.append(job.getJob(\"#Format: jobId\",\"jobClass\",\"jobParams\"))\n jobList.append(job.getJob(\"a\",\"jobClass\",\"{\\\"Dependents\\\":[\\\"d\\\",\\\"e\\\"],\\\"jobTime\\\":1}\"))\n jobList.append(job.getJob(\"b\",\"jobClass\",\"{\\\"Dependents\\\":[\\\"d\\\",\\\"e\\\"],\\\"jobTime\\\":1}\"))\n return jobList\n @staticmethod\n def getLinealTime(jobList):\n lt=0\n for j in jobList:\n print(j)\n if j[0].startswith('#'):\n pass\n else:\n try:\n jb=json.loads(j[2]) #decode into json object\n lt += jb['jobTime']\n except Exception as err:\n print(\"json error for \"+ j[2])\n return lt \n @staticmethod\n def cleanup():\n job.conn.close()\nif __name__ == '__main__':\n jl=job.getJobList(\"ProjectG\")\n print('Lineal time = '+str(job.getLinealTime(jl)))\n print('category List = '+str(job.getJobCategList()))\n #connect()","repo_name":"vvaradarajan/pyJobWeb","sub_path":"pyjobweb/jobInfo/dbUtils.py","file_name":"dbUtils.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"84"} +{"seq_id":"10215976530","text":"from fastapi import Body, Depends, File, Form, Header, Path, Query\nfrom src.database.db import get_db\nfrom src.security_api import get_current_user, get_current_user_optional\n\nMAXIMUM_FILESIZE = 50 * 1024 * 1024 # 50 MB\n\ndependsMaximumFileSize = Header(..., lt=MAXIMUM_FILESIZE)\n\n\nasync def valid_content_length(content_length: int = dependsMaximumFileSize) -> int:\n return content_length\n\n\ndependsLocalization = Query(\n \"ja\",\n description=\"It localizes response items if possible\",\n min_length=1,\n max_length=50,\n)\ndependsPage = Query(0, description=\"Filters contents using pagination\", ge=0, le=10000)\ndependsKeywords = Query(\n \"any\",\n description=\"Filter contents by specified keyword, in title and description\",\n min_length=1,\n max_length=300,\n)\ndependsSort = Query(\n 0, description=\"It sorts contents using specified method\", ge=0, le=50\n)\ndependsOrder = Query(0, description=\"It specifies sort direction\", ge=0, le=50)\ndependsStatus = Query(\n 0, description=\"Filters contents using specified status\", ge=0, le=50\n)\ndependsAuthor = Query(\n \"any\",\n description=\"Filter contents by specified author\",\n min_length=1,\n max_length=100,\n)\ndependsRatingMin = Query(\n 1, description=\"Filter level contents by minimum rating\", ge=1, le=100\n)\ndependsRatingMax: int = Query(\n 50, description=\"Filter level contents by maximum rating\", ge=1, le=100\n)\ndependsGenre = Query(0, description=\"Filter contents by specified genre\", ge=0, le=50)\ndependsLength = Query(\n 0, description=\"Filter level contents by specified length\", ge=0, le=50\n)\ndependsRandom = Query(\n 0,\n description=\"It shuffles response list\",\n ge=0,\n le=1,\n)\ndependsAddBackground = Body(None, description=\"Add background request\")\ndependsAddEffect = Body(None, description=\"Add effect request\")\ndependsAddParticle = Body(None, description=\"Add particle request\")\ndependsAddUser = Body(None, description=\"Add user request\")\ndependsStartSession = Body(None, description=\"Start session request\")\ndependsPath = Path(None, description=\"\")\ndependsBody = Body(None, description=\"\")\ndependsFile = File(None, description=\"\")\ndependsForm = Form(None, description=\"\")\ndependsDatabase = Depends(get_db)\ndependsFirebase = Depends(get_current_user)\ndependsFileSize = Depends(valid_content_length)\ndependsFirebaseOptional = Depends(get_current_user_optional)\n","repo_name":"PurplePalette/sp-api-v3","sub_path":"src/routers/depends.py","file_name":"depends.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"84"} +{"seq_id":"18231184080","text":"# -*- coding: ascii -*-\nr\"\"\"\n:Copyright:\n\n Copyright 2006 - 2016\n Andr\\xe9 Malo or his licensors, as applicable\n\n:License:\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=================\n Factory Caching\n=================\n\nFactory Caching.\n\"\"\"\nif __doc__:\n # pylint: disable = redefined-builtin\n __doc__ = __doc__.encode('ascii').decode('unicode_escape')\n__author__ = r\"Andr\\xe9 Malo\".encode('ascii').decode('unicode_escape')\n__docformat__ = \"restructuredtext en\"\n\n\ndef _copy_doc(func):\n \"\"\"\n Copy docstring\n\n :Parameters:\n `func` : ``callable``\n The method's function\n \"\"\"\n from . import factory as _factory\n method = getattr(_factory.Factory, func.__name__, None)\n if method is not None:\n func.__doc__ = method.__doc__\n\n\nclass MemoizedFactory(object):\n \"\"\"\n Wrapper for providing template factory memoization keys\n\n :IVariables:\n `_factory` : `tdi.factory.Factory`\n Factory\n \"\"\"\n\n def __init__(self, factory):\n \"\"\"\n Initialization\n\n :Parameters:\n `factory` : `tdi.factory.Factory`\n Factory\n \"\"\"\n self._factory = factory\n\n def replace(self, autoupdate=None, eventfilters=None, streamfilters=None,\n default_eventfilters=None, default_streamfilters=None,\n overlay_eventfilters=None, overlay_streamfilters=None,\n overlay_default_eventfilters=None,\n overlay_default_streamfilters=None, default_encoding=None,\n memoizer=None):\n \"\"\" Create factory with replaced parameters \"\"\"\n # pylint: disable = too-many-arguments\n\n return self.__class__(self._factory.replace(\n autoupdate=autoupdate,\n eventfilters=eventfilters,\n streamfilters=streamfilters,\n default_eventfilters=default_eventfilters,\n default_streamfilters=default_streamfilters,\n overlay_eventfilters=overlay_eventfilters,\n overlay_streamfilters=overlay_streamfilters,\n overlay_default_eventfilters=overlay_default_eventfilters,\n overlay_default_streamfilters=overlay_default_streamfilters,\n default_encoding=default_encoding,\n memoizer=memoizer,\n ))\n _copy_doc(replace)\n\n def from_file(self, filename, encoding=None, cls=None, key=None):\n \"\"\" Build template from file \"\"\"\n if key is None:\n key = filename\n return self._factory.from_file(\n filename, encoding=encoding, cls=cls, key=key\n )\n _copy_doc(from_file)\n\n def from_stream(self, stream, encoding=None, filename=None, mtime=None,\n opener=None, cls=None, key=None):\n \"\"\" Build template from stream \"\"\"\n if key is None:\n key = filename\n return self._factory.from_stream(\n stream,\n encoding=encoding,\n filename=filename,\n mtime=mtime,\n opener=opener,\n cls=cls,\n key=key,\n )\n _copy_doc(from_stream)\n\n def from_opener(self, opener, filename, encoding=None, cls=None,\n key=None):\n \"\"\" Build template from stream opener \"\"\"\n if key is None:\n key = filename\n return self._factory.from_opener(\n opener, filename, encoding=encoding, cls=cls, key=key\n )\n _copy_doc(from_opener)\n\n def from_string(self, data, encoding=None, filename=None, mtime=None,\n cls=None, key=None):\n \"\"\" Build template from string \"\"\"\n if key is None:\n key = filename\n return self._factory.from_string(\n data,\n encoding=encoding,\n filename=filename,\n mtime=mtime,\n cls=cls,\n key=key,\n )\n _copy_doc(from_string)\n\n def from_files(self, names, encoding=None, basedir=None, cls=None,\n key=None):\n \"\"\" Load templates from files and overlay them \"\"\"\n if key is None:\n key = (basedir,) + tuple(names)\n return self._factory.from_files(\n names,\n encoding=encoding,\n basedir=basedir,\n cls=cls,\n key=key,\n )\n _copy_doc(from_files)\n\n def from_streams(self, streams, encoding=None, streamopen=None, cls=None,\n key=None):\n \"\"\" Load templates from streams and overlay them \"\"\"\n if key is None:\n key = tuple(streams)\n try:\n hash(key)\n except TypeError:\n key = None\n return self._factory.from_streams(\n streams,\n encoding=encoding,\n streamopen=streamopen,\n cls=cls,\n key=key,\n )\n _copy_doc(from_streams)\n","repo_name":"ndparker/tdi","sub_path":"tdi/factory_memoize.py","file_name":"factory_memoize.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"84"} +{"seq_id":"4813262329","text":"# Right Triangles With Integer Coordinates\n\n\ndef check(x1, y1, x2, y2):\n x3 = x1 - x2\n y3 = y1 - y2\n if x1 * x2 + y1 * y2 == 0:\n return True\n if x1 * x3 + y1 * y3 == 0:\n return True\n if x2 * x3 + y2 * y3 == 0:\n return True\n return False\n\n\noptions = {}\n\nlimit = 51\n\nfor x in range(limit):\n for y in range(limit):\n if not (x == 0 and y == 0):\n for x1 in range(limit):\n for y1 in range(limit):\n if not (x1 == 0 and y1 == 0) and not (x == x1 and y == y1) and check(x, y, x1, y1):\n try:\n a = options[f\"{x} {y} {x1} {y1}\"]\n except KeyError:\n try:\n a = options[f\"{x1} {y1} {x} {y}\"]\n except KeyError:\n options[f\"{x} {y} {x1} {y1}\"] = 0\n\nprint(len(options))\n","repo_name":"cgreggescalante/Challenges","sub_path":"ProjectEuler/Complete/91.py","file_name":"91.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"84"} +{"seq_id":"75267536915","text":"import requests\nfrom urllib.parse import quote\n\nclass YelpAPI(object):\n # code modified from https://github.com/Yelp/yelp-fusion/blob/master/fusion/python/sample.py\n def __init__(self, api_key):\n self.key = api_key\n self.API_HOST = 'https://api.yelp.com'\n self.SEARCH_PATH = '/v3/businesses/search'\n self.BUSINESS_PATH = '/v3/businesses/'\n\n def request(self, host, path, api_key, url_params={}):\n url_params = url_params or {}\n url = '{0}{1}'.format(host, quote(path.encode('utf8')))\n headers = {\n 'Authorization': 'Bearer %s' % api_key,\n }\n response = requests.request('GET', url, headers=headers, params=url_params)\n return response.json()\n\n def get_business(self, business_id):\n \"\"\"Query the Business API by a business ID.\n Args:\n business_id (str): The ID of the business to query.\n Returns:\n dict: The JSON response from the request.\n \"\"\"\n business_path = self.BUSINESS_PATH + business_id\n return self.request(self.API_HOST, business_path, self.key )\n\n def get_reviews(self, business_id):\n reviews_path = self.BUSINESS_PATH + business_id + '/reviews'\n return self.request(self.API_HOST, reviews_path, self.key )\n\n def search(self, term, location, search_limit):\n url_params = {\n 'term': term.replace(' ', '+'),\n 'location': location.replace(' ', '+'),\n 'limit': search_limit,\n 'open_now': True\n }\n return self.request(self.API_HOST, self.SEARCH_PATH, self.key, url_params=url_params)\n","repo_name":"Malekagr/Yelp-Chatbot","sub_path":"yelp.py","file_name":"yelp.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"84"} +{"seq_id":"24313567193","text":"import traceback\n\nimport pandas as pd\n\nfrom lib import bitflyer, message, repository\nfrom lib.config import Bitflyer, HistoricalPrice\n\n\ndef get_historical_price() -> pd.DataFrame or None:\n try:\n limit = CHANNEL_BAR_NUM + 1\n hp = bitflyer.get_historical_price(limit=limit)\n if len(hp) != limit:\n return None\n return hp\n except Exception:\n message.error(traceback.format_exc())\n return None\n\n\ndef save_entry(side):\n message.info(side, \"entry\")\n sql = \"update entry set side='{side}'\".format(side=side)\n repository.execute(database=DATABASE, sql=sql, write=False)\n\n\nTIME_FRAME = HistoricalPrice.TIME_FRAME.value\nCHANNEL_WIDTH = HistoricalPrice.CHANNEL_WIDTH.value\nCHANNEL_BAR_NUM = TIME_FRAME * CHANNEL_WIDTH\n\nbitflyer = bitflyer.API(api_key=Bitflyer.Api.value.KEY.value,\n api_secret=Bitflyer.Api.value.SECRET.value)\n\nDATABASE = \"tradingbot\"\n\nhas_buy = False\nhas_sell = False\nwhile True:\n hp = get_historical_price()\n if hp is None:\n continue\n\n i = len(hp) - 1\n latest = hp.iloc[i]\n Date = latest[\"Date\"]\n Price = latest[\"Close\"]\n\n before = hp.iloc[:i]\n high_line = before[\"High\"].max()\n low_line = before[\"Low\"].min()\n\n should_buy = Price > high_line and not has_buy\n should_sell = Price < low_line and not has_sell\n\n if should_buy:\n save_entry(side=\"BUY\")\n has_buy = True\n has_sell = False\n\n if should_sell:\n save_entry(side=\"SELL\")\n has_buy = False\n has_sell = True\n","repo_name":"yuta-komura/ida","sub_path":"entry.py","file_name":"entry.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"27826489233","text":"from django.urls import path\n\nfrom courses.views import CourseListAPIView, SubscribeCourseAPIVIew, LikesCourseAPIVIew, MaterialsAPIVIew\n\nurlpatterns = [\n path('', CourseListAPIView.as_view(), name='list_courses'),\n path('/subscribe/', SubscribeCourseAPIVIew.as_view(), name='subscribe_course'),\n path('/materials/', MaterialsAPIVIew.as_view(), name='materials_course'),\n path('/like/', LikesCourseAPIVIew.as_view(), name='rated_course')\n]","repo_name":"LeonMaxwell/freeflex_masters","sub_path":"courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"71356924111","text":"\"\"\"\r\n\r\nAn OrderedDict is a dictionary subclass that remembers the order that keys were first inserted.\r\nA regular dict doesn't track the insertion order, and iterating it gives the values in an arbitrary order.\r\n... By contrast, the order the items are inserted is remembered by OrderedDict.\r\n\r\n\"\"\"\r\n\r\n\r\n\r\nfrom collections import OrderedDict #OrderedDict 모듈 선언\r\n\r\n#\r\n# OrderedDict로 선언한 사전형자료는 입력 순서를 기억하여 나열되는 것이 보장된다.\r\n# 본 예제로는 그것을 증명하여 보여주지는 못하고 있다.\r\n\r\nd = OrderedDict()\r\nd['x'] = 100\r\nd['y'] = 200\r\nd['z'] = 300\r\nd['l'] = 500\r\n\r\nprint(d) # 자료 순서가 바뀔 수 있다 함.\r\n# OrderedDict([('x', 100), ('y', 200), ('z', 300), ('l', 500)])\r\n\r\nfor k, v in d.items():\r\n print(k, v)\r\n# x 100\r\n# y 200\r\n# z 300\r\n# l 500","repo_name":"shinDongMin1/study","sub_path":"python/Ch07/ordereddict2.py","file_name":"ordereddict2.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"28058313428","text":"import pytest\nimport numpy as np\nimport toppra\n\n\n@pytest.fixture\ndef coefficients_functions():\n \"Coefficients for the equation: A(q) ddot q + dot q B(q) dot q + C(q) = w\"\n def A(q):\n return np.array([[np.sin(q[0]), 0],\n [np.cos(q[1]), q[0] + q[1]]])\n\n def B(q):\n ret = np.zeros((2, 2, 2))\n ret[:, :, 0] = [[np.sin(2 * q[0]), 0], [0, q[1] ** 2]]\n ret[:, :, 1] = [[1, 2], [3, q[0]]]\n return ret\n\n def C(q):\n return np.array([q[0] * q[1], 0])\n\n def F(q):\n ret = np.zeros((4, 2))\n ret[:, 0] = [1, 1, 1, 1]\n ret[:, 1] = [10 * np.sin(q[0]), q[1], q[0] + q[1], 10]\n return ret\n\n def g(q):\n return np.array([100, 200])\n\n def inv_dyn(q, qd, qdd):\n return A(q).dot(qdd) + np.dot(qd.T, np.dot(B(q), qd)) + C(q)\n\n np.random.seed(0)\n path = toppra.SplineInterpolator([0, 1, 2, 4], np.random.randn(4, 2))\n return A, B, C, F, g, path, inv_dyn\n\n\ndef test_wrong_dimension(coefficients_functions):\n \"\"\"If the given path has wrong dimension, raise error.\"\"\"\n A, B, C, cnst_F, cnst_g, path, inv_dyn = coefficients_functions\n constraint = toppra.constraint.SecondOrderConstraint(inv_dyn, cnst_F, cnst_g, dof=2)\n path_wrongdim = toppra.SplineInterpolator(np.linspace(0, 1, 5), np.random.randn(5, 10))\n with pytest.raises(ValueError) as e_info:\n constraint.compute_constraint_params(path_wrongdim, np.r_[0, 0.5, 1])\n assert e_info.value.args[0] == \"Wrong dimension: constraint dof ({:d}) not equal to path dof ({:d})\".format(\n constraint.dof, 10)\n\n\ndef test_correctness(coefficients_functions):\n \"\"\" For randomly set A, B, C, F, g functions. The generated parameters must equal\n those given by equations.\n \"\"\"\n A, B, C, cnst_F, cnst_g, path, inv_dyn = coefficients_functions\n constraint = toppra.constraint.SecondOrderConstraint(\n inv_dyn, cnst_F, cnst_g, dof=2,\n discretization_scheme=toppra.constraint.DiscretizationType.Collocation)\n a, b, c, F, g, _, _ = constraint.compute_constraint_params(\n path, np.linspace(0, path.duration, 10))\n\n # Correct params\n q_vec = path(np.linspace(0, path.duration, 10))\n qs_vec = path(np.linspace(0, path.duration, 10), 1)\n qss_vec = path(np.linspace(0, path.duration, 10), 2)\n\n for i in range(10):\n ai_ = A(q_vec[i]).dot(qs_vec[i])\n bi_ = A(q_vec[i]).dot(qss_vec[i]) + np.dot(qs_vec[i].T, B(q_vec[i]).dot(qs_vec[i]))\n ci_ = C(q_vec[i])\n np.testing.assert_allclose(ai_, a[i])\n np.testing.assert_allclose(bi_, b[i])\n np.testing.assert_allclose(ci_, c[i])\n np.testing.assert_allclose(cnst_F(q_vec[i]), F[i])\n np.testing.assert_allclose(cnst_g(q_vec[i]), g[i])\n\n\n@pytest.fixture\ndef friction():\n def randomized_friction(q):\n \"\"\"Randomize with fixed input/output.\"\"\"\n np.random.seed(int(abs(np.sum(q)) * 1000))\n return 2 + np.sin(q) + np.random.rand(len(q))\n yield randomized_friction\n\n\ndef test_joint_torque(coefficients_functions, friction):\n \"\"\" Same as the above test, but has frictional effect.\n \"\"\"\n # setup\n A, B, C, cnst_F, cnst_g, path, _ = coefficients_functions\n def inv_dyn(q, qd, qdd):\n return A(q).dot(qdd) + np.dot(qd.T, np.dot(B(q), qd)) + C(q)\n friction = np.random.rand(2)\n taulim = np.random.randn(2, 2)\n constraint = toppra.constraint.SecondOrderConstraint.joint_torque_constraint(\n inv_dyn, taulim, friction)\n constraint.set_discretization_type(0)\n a, b, c, F, g, _, _ = constraint.compute_constraint_params(\n path, np.linspace(0, path.duration, 10))\n\n # Correct params\n p_vec = path(np.linspace(0, path.duration, 10))\n ps_vec = path(np.linspace(0, path.duration, 10), 1)\n pss_vec = path(np.linspace(0, path.duration, 10), 2)\n\n dof = 2\n F_actual = np.vstack((np.eye(dof), - np.eye(dof)))\n g_actual = np.hstack((taulim[:, 1], - taulim[:, 0]))\n\n for i in range(10):\n ai_ = A(p_vec[i]).dot(ps_vec[i])\n bi_ = A(p_vec[i]).dot(pss_vec[i]) + np.dot(ps_vec[i].T, B(p_vec[i]).dot(ps_vec[i]))\n ci_ = C(p_vec[i]) + np.sign(ps_vec[i]) * friction\n np.testing.assert_allclose(ai_, a[i])\n np.testing.assert_allclose(bi_, b[i])\n np.testing.assert_allclose(ci_, c[i])\n np.testing.assert_allclose(F_actual, F[i])\n np.testing.assert_allclose(g_actual, g[i])\n","repo_name":"hungpham2511/toppra","sub_path":"tests/tests/constraint/test_second_order.py","file_name":"test_second_order.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","stars":511,"dataset":"github-code","pt":"83"} +{"seq_id":"9390773368","text":"import os\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom utils.filterbank import choose_filterbank\nfrom utils.model import choose_nonlinear\nfrom utils.tasnet import choose_layer_norm\nfrom models.tdcn import TimeDilatedConvNet\n\nSAMPLE_RATE_MUSDB18 = 44100\nSAMPLE_RATE_LIBRISPEECH = 16000\nEPS = 1e-12\n\nclass ConvTasNet(nn.Module):\n pretrained_model_ids = {\n \"wsj0-mix\": {\n 8000: {\n 2: {\n \"enc_relu\": \"1yy-o7TyS1EcBWZ41rskMAVavtuEi4fMe\",\n },\n 3: {\n \"enc_relu\": \"1-4Abl7LnEtwqMnAFQOcNLUOaDbgp3NoG\"\n }\n },\n 16000: {\n 2: \"\", # TODO\n 3: \"\" # TODO\n }\n },\n \"wham/enhance-single\": {\n 8000: \"1-6oiSK_CEE5Vl4OCy8TinA0cKsFFfGUg\",\n 16000: \"\" # TODO\n },\n \"wham/enhance-both\": {\n 8000: \"1-GISUVcWjMeP3GLvojz9b0svw6gkmd2G\",\n 16000: \"\" # TODO\n },\n \"wham/separate-noisy\": {\n 8000: \"1-0ckoPjaIiTJwv9Qotz6fkY2xeC77xdi\",\n 16000: \"\" # TODO\n },\n \"musdb18\": {\n SAMPLE_RATE_MUSDB18: {\n \"4sec_L20\": \"1A6dIofHZJQCUkyq-vxZ6KbPmEHLcf4WK\",\n \"8sec_L20\": \"1C4uv2z0w1s4rudIMaErLyEccNprJQWSZ\",\n \"8sec_L64\": \"1paXNGgH8m0kiJTQnn1WH-jEIurCKXwtw\"\n }\n },\n \"librispeech\": {\n SAMPLE_RATE_LIBRISPEECH: {\n 2: \"1NI6Q_WZHiTKkgkNTEcZE1yHskHgYUHpy\"\n }\n }\n }\n def __init__(self,\n n_basis, kernel_size, stride=None, enc_basis=None, dec_basis=None,\n sep_hidden_channels=256, sep_bottleneck_channels=128, sep_skip_channels=128, sep_kernel_size=3, sep_num_blocks=3, sep_num_layers=8,\n dilated=True, separable=True,\n sep_nonlinear='prelu', sep_norm=True, mask_nonlinear='sigmoid',\n causal=True,\n n_sources=2,\n eps=EPS,\n **kwargs\n ):\n super().__init__()\n\n if stride is None:\n stride = kernel_size // 2\n\n assert kernel_size % stride == 0, \"kernel_size is expected divisible by stride\"\n\n # Encoder-decoder\n self.in_channels = kwargs.get('in_channels', 1)\n self.n_basis = n_basis\n self.kernel_size, self.stride = kernel_size, stride\n self.enc_basis, self.dec_basis = enc_basis, dec_basis\n\n if enc_basis == 'trainable' and not dec_basis == 'pinv':\n self.enc_nonlinear = kwargs['enc_nonlinear']\n else:\n self.enc_nonlinear = None\n\n if enc_basis in ['Fourier', 'trainableFourier', 'trainableFourierTrainablePhase'] or dec_basis in ['Fourier', 'trainableFourier', 'trainableFourierTrainablePhase']:\n self.window_fn = kwargs['window_fn']\n self.enc_onesided, self.enc_return_complex = kwargs['enc_onesided'], kwargs['enc_return_complex']\n else:\n self.window_fn = None\n self.enc_onesided, self.enc_return_complex = None, None\n\n # Separator configuration\n self.sep_hidden_channels, self.sep_bottleneck_channels, self.sep_skip_channels = sep_hidden_channels, sep_bottleneck_channels, sep_skip_channels\n self.sep_kernel_size = sep_kernel_size\n self.sep_num_blocks, self.sep_num_layers = sep_num_blocks, sep_num_layers\n\n self.dilated, self.separable, self.causal = dilated, separable, causal\n self.sep_nonlinear, self.sep_norm = sep_nonlinear, sep_norm\n self.mask_nonlinear = mask_nonlinear\n\n self.n_sources = n_sources\n self.eps = eps\n\n # Network configuration\n encoder, decoder = choose_filterbank(n_basis, kernel_size=kernel_size, stride=stride, enc_basis=enc_basis, dec_basis=dec_basis, **kwargs)\n\n self.encoder = encoder\n self.separator = Separator(\n n_basis, bottleneck_channels=sep_bottleneck_channels, hidden_channels=sep_hidden_channels, skip_channels=sep_skip_channels,\n kernel_size=sep_kernel_size, num_blocks=sep_num_blocks, num_layers=sep_num_layers,\n dilated=dilated, separable=separable, causal=causal, nonlinear=sep_nonlinear, norm=sep_norm, mask_nonlinear=mask_nonlinear,\n n_sources=n_sources, eps=eps\n )\n self.decoder = decoder\n\n def forward(self, input):\n output, _ = self.extract_latent(input)\n\n return output\n\n def extract_latent(self, input):\n \"\"\"\n Args:\n input (batch_size, C_in, T)\n Returns:\n output (batch_size, n_sources, T) or (batch_size, n_sources, C_in, T)\n latent (batch_size, n_sources, n_basis, T'), where T' = (T-K)//S+1\n \"\"\"\n n_sources = self.n_sources\n n_basis = self.n_basis\n kernel_size, stride = self.kernel_size, self.stride\n\n n_dims = input.dim()\n\n if n_dims == 3:\n batch_size, C_in, T = input.size()\n assert C_in == 1, \"input.size() is expected (?, 1, ?), but given {}\".format(input.size())\n elif n_dims == 4:\n batch_size, C_in, n_mics, T = input.size()\n assert C_in == 1, \"input.size() is expected (?, 1, ?, ?), but given {}\".format(input.size())\n input = input.view(batch_size, n_mics, T)\n else:\n raise ValueError(\"Not support {} dimension input\".format(n_dims))\n\n padding = (stride - (T - kernel_size) % stride) % stride\n padding_left = padding // 2\n padding_right = padding - padding_left\n\n input = F.pad(input, (padding_left, padding_right))\n w = self.encoder(input)\n\n if torch.is_complex(w):\n amplitude, phase = torch.abs(w), torch.angle(w)\n mask = self.separator(amplitude)\n amplitude, phase = amplitude.unsqueeze(dim=1), phase.unsqueeze(dim=1)\n w_hat = amplitude * mask * torch.exp(1j * phase)\n else:\n mask = self.separator(w)\n w = w.unsqueeze(dim=1)\n w_hat = w * mask\n\n latent = w_hat\n w_hat = w_hat.view(batch_size*n_sources, n_basis, -1)\n x_hat = self.decoder(w_hat)\n if n_dims == 3:\n x_hat = x_hat.view(batch_size, n_sources, -1)\n else: # n_dims == 4\n x_hat = x_hat.view(batch_size, n_sources, n_mics, -1)\n output = F.pad(x_hat, (-padding_left, -padding_right))\n\n return output, latent\n\n def get_config(self):\n config = {\n 'in_channels': self.in_channels,\n 'n_basis': self.n_basis,\n 'kernel_size': self.kernel_size, 'stride': self.stride,\n 'enc_basis': self.enc_basis, 'dec_basis': self.dec_basis,\n 'enc_nonlinear': self.enc_nonlinear,\n 'window_fn': self.window_fn,\n 'enc_onesided': self.enc_onesided, 'enc_return_complex': self.enc_return_complex,\n 'sep_hidden_channels': self.sep_hidden_channels, 'sep_bottleneck_channels': self.sep_bottleneck_channels, 'sep_skip_channels': self.sep_skip_channels,\n 'sep_kernel_size': self.sep_kernel_size,\n 'sep_num_blocks': self.sep_num_blocks, 'sep_num_layers': self.sep_num_layers,\n 'dilated': self.dilated, 'separable': self.separable,\n 'causal': self.causal,\n 'sep_nonlinear': self.sep_nonlinear,\n 'sep_norm': self.sep_norm,\n 'mask_nonlinear': self.mask_nonlinear,\n 'n_sources': self.n_sources,\n 'eps': self.eps\n }\n\n return config\n\n def get_package(self):\n return self.get_config()\n\n @classmethod\n def build_model(cls, model_path, load_state_dict=False):\n config = torch.load(model_path, map_location=lambda storage, loc: storage)\n\n in_channels = config.get('in_channels') or 1\n n_basis = config.get('n_bases') or config['n_basis']\n kernel_size, stride = config['kernel_size'], config['stride']\n enc_basis, dec_basis = config.get('enc_bases') or config['enc_basis'], config.get('dec_bases') or config['dec_basis']\n enc_nonlinear = config['enc_nonlinear']\n enc_onesided, enc_return_complex = config.get('enc_onesided') or None, config.get('enc_return_complex') or None\n window_fn = config['window_fn']\n\n sep_hidden_channels, sep_bottleneck_channels, sep_skip_channels = config['sep_hidden_channels'], config['sep_bottleneck_channels'], config['sep_skip_channels']\n sep_kernel_size = config['sep_kernel_size']\n sep_num_blocks, sep_num_layers = config['sep_num_blocks'], config['sep_num_layers']\n\n dilated, separable, causal = config['dilated'], config['separable'], config['causal']\n sep_nonlinear, sep_norm = config['sep_nonlinear'], config['sep_norm']\n mask_nonlinear = config['mask_nonlinear']\n\n n_sources = config['n_sources']\n\n eps = config['eps']\n\n model = cls(\n n_basis, in_channels=in_channels, kernel_size=kernel_size, stride=stride, enc_basis=enc_basis, dec_basis=dec_basis, enc_nonlinear=enc_nonlinear,\n window_fn=window_fn, enc_onesided=enc_onesided, enc_return_complex=enc_return_complex,\n sep_hidden_channels=sep_hidden_channels, sep_bottleneck_channels=sep_bottleneck_channels, sep_skip_channels=sep_skip_channels,\n sep_kernel_size=sep_kernel_size, sep_num_blocks=sep_num_blocks, sep_num_layers=sep_num_layers,\n dilated=dilated, separable=separable, causal=causal, sep_nonlinear=sep_nonlinear, sep_norm=sep_norm, mask_nonlinear=mask_nonlinear,\n n_sources=n_sources,\n eps=eps\n )\n\n if load_state_dict:\n model.load_state_dict(config['state_dict'])\n\n return model\n\n @classmethod\n def build_from_pretrained(cls, root=\"./pretrained\", quiet=False, load_state_dict=True, **kwargs):\n from utils.utils import download_pretrained_model_from_google_drive\n\n task = kwargs.get('task')\n\n if not task in cls.pretrained_model_ids:\n raise KeyError(\"Invalid task ({}) is specified.\".format(task))\n\n pretrained_model_ids_task = cls.pretrained_model_ids[task]\n additional_attributes = {}\n\n if task in ['wsj0-mix', 'wsj0']:\n sample_rate = kwargs.get('sample_rate') or 8000\n n_sources = kwargs.get('n_sources') or 2\n config = kwargs.get('config') or 'enc_relu'\n model_choice = kwargs.get('model_choice') or 'best'\n\n model_id = pretrained_model_ids_task[sample_rate][n_sources][config]\n download_dir = os.path.join(root, cls.__name__, task, \"sr{}/{}speakers/{}\".format(sample_rate, n_sources, config))\n\n additional_attributes.update({\n 'n_sources': n_sources\n })\n elif task == 'musdb18':\n sample_rate = kwargs.get('sample_rate') or SAMPLE_RATE_MUSDB18\n config = kwargs.get('config') or '4sec_L20'\n model_choice = kwargs.get('model_choice') or 'best'\n\n model_id = pretrained_model_ids_task[sample_rate][config]\n download_dir = os.path.join(root, cls.__name__, task, \"sr{}\".format(sample_rate), config)\n elif task in ['wham/separate-noisy', 'wham/enhance-single', 'wham/enhance-both']:\n sample_rate = kwargs.get('sample_rate') or 8000\n model_choice = kwargs.get('model_choice') or 'best'\n\n model_id = pretrained_model_ids_task[sample_rate]\n download_dir = os.path.join(root, cls.__name__, task, \"sr{}\".format(sample_rate))\n elif task == 'librispeech':\n sample_rate = kwargs.get('sample_rate') or SAMPLE_RATE_LIBRISPEECH\n n_sources = kwargs.get('n_sources') or 2\n model_choice = kwargs.get('model_choice') or 'best'\n\n model_id = pretrained_model_ids_task[sample_rate][n_sources]\n download_dir = os.path.join(root, cls.__name__, task, \"sr{}/{}speakers\".format(sample_rate, n_sources))\n\n additional_attributes.update({\n 'n_sources': n_sources\n })\n else:\n raise NotImplementedError(\"Not support task={}.\".format(task))\n\n additional_attributes.update({\n 'sample_rate': sample_rate\n })\n\n model_path = os.path.join(download_dir, \"model\", \"{}.pth\".format(model_choice))\n\n if not os.path.exists(model_path):\n download_pretrained_model_from_google_drive(model_id, download_dir, quiet=quiet)\n\n config = torch.load(model_path, map_location=lambda storage, loc: storage)\n model = cls.build_model(model_path, load_state_dict=load_state_dict)\n\n if task == 'musdb18':\n additional_attributes.update({\n 'sources': config['sources'],\n 'n_sources': len(config['sources'])\n })\n\n for key, value in additional_attributes.items():\n setattr(model, key, value)\n\n return model\n\n @property\n def num_parameters(self):\n _num_parameters = 0\n\n for p in self.parameters():\n if p.requires_grad:\n _num_parameters += p.numel()\n\n return _num_parameters\n\nclass Separator(nn.Module):\n def __init__(\n self, num_features, bottleneck_channels=128, hidden_channels=256, skip_channels=128, kernel_size=3, num_blocks=3, num_layers=8,\n dilated=True, separable=True, causal=True, nonlinear='prelu', norm=True, mask_nonlinear='sigmoid',\n n_sources=2,\n eps=EPS\n ):\n super().__init__()\n\n self.num_features, self.n_sources = num_features, n_sources\n\n norm_name = 'cLN' if causal else 'gLN'\n self.norm1d = choose_layer_norm(norm_name, num_features, causal=causal, eps=eps)\n self.bottleneck_conv1d = nn.Conv1d(num_features, bottleneck_channels, kernel_size=1, stride=1)\n self.tdcn = TimeDilatedConvNet(\n bottleneck_channels, hidden_channels=hidden_channels, skip_channels=skip_channels, kernel_size=kernel_size, num_blocks=num_blocks, num_layers=num_layers,\n dilated=dilated, separable=separable, causal=causal, nonlinear=nonlinear, norm=norm\n )\n self.prelu = nn.PReLU()\n self.mask_conv1d = nn.Conv1d(skip_channels, n_sources*num_features, kernel_size=1, stride=1)\n\n if mask_nonlinear == 'sigmoid':\n self.mask_nonlinear = nn.Sigmoid()\n elif mask_nonlinear == 'softmax':\n self.mask_nonlinear = nn.Softmax(dim=1)\n else:\n raise ValueError(\"Cannot support {}\".format(mask_nonlinear))\n\n if mask_nonlinear == 'sigmoid':\n kwargs = {}\n elif mask_nonlinear == 'softmax':\n kwargs = {\n \"dim\": 1\n }\n\n self.mask_nonlinear = choose_nonlinear(mask_nonlinear, **kwargs)\n\n def forward(self, input):\n \"\"\"\n Args:\n input (batch_size, num_features, n_frames)\n Returns:\n output (batch_size, n_sources, n_basis, n_frames)\n \"\"\"\n num_features, n_sources = self.num_features, self.n_sources\n\n batch_size, _, n_frames = input.size()\n\n x = self.norm1d(input)\n x = self.bottleneck_conv1d(x)\n x = self.tdcn(x)\n x = self.prelu(x)\n x = self.mask_conv1d(x)\n x = self.mask_nonlinear(x)\n output = x.view(batch_size, n_sources, num_features, n_frames)\n\n return output\n\ndef _test_conv_tasnet():\n batch_size = 4\n C = 1\n T = 64\n\n input = torch.randn((batch_size, C, T), dtype=torch.float)\n\n H, B, Sc = 128, 64, 64\n P = 3\n R, X = 3, 8\n sep_norm = True\n\n # Causal\n print(\"-\"*10, \"Fourier Basis & Causal\", \"-\"*10)\n L, stride = 16, 8\n N = L // 2 + 1\n enc_basis, dec_basis = 'Fourier', 'Fourier'\n causal = True\n mask_nonlinear = 'softmax'\n window_fn = 'hamming'\n enc_onesided, enc_return_complex = True, True\n n_sources = 3\n\n model = ConvTasNet(\n N, kernel_size=L, stride=stride, enc_basis=enc_basis, dec_basis=dec_basis,\n window_fn=window_fn, enc_onesided=enc_onesided, enc_return_complex=enc_return_complex,\n sep_hidden_channels=H, sep_bottleneck_channels=B, sep_skip_channels=Sc,\n sep_kernel_size=P, sep_num_blocks=R, sep_num_layers=X,\n causal=causal, sep_norm=sep_norm, mask_nonlinear=mask_nonlinear,\n n_sources=n_sources\n )\n print(model)\n print(\"# Parameters: {}\".format(model.num_parameters))\n \n output = model(input)\n print(input.size(), output.size())\n print()\n\n basis = model.encoder.get_basis()\n\n plt.figure()\n plt.pcolormesh(basis.squeeze(dim=1).detach(), cmap='bwr', norm=Normalize(vmin=-1, vmax=1))\n plt.colorbar()\n plt.savefig('data/conv-tasnet/basis_enc-Fourier.png', bbox_inches='tight')\n plt.close()\n\n # Non causal\n print(\"-\"*10, \"Fourier Basis & Non-causal\", \"-\"*10)\n L, stride = 16, 4\n N = 2 * L\n enc_basis, dec_basis = 'Fourier', 'Fourier'\n causal = False\n mask_nonlinear = 'softmax'\n window_fn = 'hann'\n enc_onesided, enc_return_complex = False, False\n n_sources = 2\n\n model = ConvTasNet(\n N, kernel_size=L, stride=stride, enc_basis=enc_basis, dec_basis=dec_basis,\n window_fn=window_fn, enc_onesided=enc_onesided, enc_return_complex=enc_return_complex,\n sep_hidden_channels=H, sep_bottleneck_channels=B, sep_skip_channels=Sc,\n sep_kernel_size=P, sep_num_blocks=R, sep_num_layers=X,\n causal=causal, sep_norm=sep_norm, mask_nonlinear=mask_nonlinear,\n n_sources=n_sources\n )\n print(model)\n print(\"# Parameters: {}\".format(model.num_parameters))\n\n output = model(input)\n print(input.size(), output.size())\n print()\n\n # Pseudo inverse\n print(\"-\"*10, \"Decoder is a pseudo inverse of encoder\", \"-\"*10)\n L, stride = 16, 4\n N = 64\n enc_basis, dec_basis = 'trainable', 'pinv'\n enc_nonlinear = None\n causal = False\n mask_nonlinear = 'sigmoid'\n n_sources = 2\n\n model = ConvTasNet(\n N, kernel_size=L, stride=stride, enc_basis=enc_basis, dec_basis=dec_basis, enc_nonlinear=enc_nonlinear,\n sep_hidden_channels=H, sep_bottleneck_channels=B, sep_skip_channels=Sc,\n sep_kernel_size=P, sep_num_blocks=R, sep_num_layers=X,\n causal=causal, sep_norm=sep_norm, mask_nonlinear=mask_nonlinear, n_sources=n_sources\n )\n print(model)\n print(\"# Parameters: {}\".format(model.num_parameters))\n\n output = model(input)\n print(input.size(), output.size())\n\ndef _test_multichannel_conv_tasnet():\n batch_size = 4\n C = 2\n T = 64\n\n input = torch.randn((batch_size, 1, C, T), dtype=torch.float)\n\n L, stride = 16, 8\n N = 64\n H, B, Sc = 128, 64, 64\n P = 3\n R, X = 3, 8\n sep_norm = True\n\n enc_basis, dec_basis = 'trainable', 'trainable'\n enc_nonlinear = 'relu'\n causal = False\n mask_nonlinear = 'softmax'\n n_sources = 3\n\n model = ConvTasNet(\n N, in_channels=C, kernel_size=L, stride=stride, enc_basis=enc_basis, dec_basis=dec_basis, enc_nonlinear=enc_nonlinear,\n sep_hidden_channels=H, sep_bottleneck_channels=B, sep_skip_channels=Sc,\n sep_kernel_size=P, sep_num_blocks=R, sep_num_layers=X, causal=causal, sep_norm=sep_norm, mask_nonlinear=mask_nonlinear,\n n_sources=n_sources\n )\n print(model)\n print(\"# Parameters: {}\".format(model.num_parameters))\n\n output = model(input)\n print(input.size(), output.size())\n print()\n\ndef _test_conv_tasnet_paper():\n batch_size = 4\n C = 1\n T = 64\n\n input = torch.randn((batch_size, C, T), dtype=torch.float)\n\n L, stride = 16, 8\n N = 512\n H, B, Sc = 512, 128, 128\n P = 3\n R, X = 3, 8\n sep_norm = True\n\n # Non causal\n print(\"-\"*10, \"Trainable Basis & Non causal\", \"-\"*10)\n enc_basis, dec_basis = 'trainable', 'trainable'\n enc_nonlinear = None\n causal = False\n mask_nonlinear = 'sigmoid'\n n_sources = 2\n\n model = ConvTasNet(\n N, kernel_size=L, stride=stride, enc_basis=enc_basis, dec_basis=dec_basis, enc_nonlinear=enc_nonlinear,\n sep_hidden_channels=H, sep_bottleneck_channels=B, sep_skip_channels=Sc, sep_kernel_size=P, sep_num_blocks=R, sep_num_layers=X,\n causal=causal, sep_norm=sep_norm, mask_nonlinear=mask_nonlinear,\n n_sources=n_sources\n )\n print(model)\n print(\"# Parameters: {}\".format(model.num_parameters))\n\n output = model(input)\n print(input.size(), output.size())\n\n basis = model.encoder.get_basis()\n\n plt.figure()\n plt.pcolormesh(basis.squeeze(dim=1).detach(), cmap='bwr', norm=Normalize(vmin=-1, vmax=1))\n plt.colorbar()\n plt.savefig('data/conv-tasnet/basis_enc-trainable.png', bbox_inches='tight')\n plt.close()\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n from matplotlib.colors import Normalize\n\n torch.manual_seed(111)\n\n print(\"=\"*10, \"Conv-TasNet\", \"=\"*10)\n _test_conv_tasnet()\n print()\n\n print(\"=\"*10, \"Conv-TasNet (multichannel)\", \"=\"*10)\n _test_multichannel_conv_tasnet()\n print()\n\n print(\"=\"*10, \"Conv-TasNet (same configuration in the paper)\", \"=\"*10)\n _test_conv_tasnet_paper()\n print()","repo_name":"tky823/DNN-based_source_separation","sub_path":"src/models/conv_tasnet.py","file_name":"conv_tasnet.py","file_ext":"py","file_size_in_byte":21042,"program_lang":"python","lang":"en","doc_type":"code","stars":244,"dataset":"github-code","pt":"83"} +{"seq_id":"1780047832","text":"# coding: utf-8\ntry:\n from inspect import getfullargspec\nexcept ImportError:\n from inspect import getargspec as getfullargspec\nimport pprint\nimport re # noqa: F401\nimport six\n\nfrom cloudtower.configuration import Configuration\n\n\nclass GlobalAlertRule(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'alert_rules': 'list[NestedAlertRule]',\n 'boolean': 'bool',\n 'cause': 'str',\n 'default_thresholds': 'list[NestedThresholds]',\n 'disabled': 'bool',\n 'id': 'str',\n 'impact': 'str',\n 'message': 'str',\n 'name': 'str',\n 'object': 'AlertRuleObject',\n 'operator': 'str',\n 'solution': 'str',\n 'thresholds': 'list[NestedThresholds]',\n 'unit': 'AlertRuleUnit'\n }\n\n attribute_map = {\n 'alert_rules': 'alert_rules',\n 'boolean': 'boolean',\n 'cause': 'cause',\n 'default_thresholds': 'default_thresholds',\n 'disabled': 'disabled',\n 'id': 'id',\n 'impact': 'impact',\n 'message': 'message',\n 'name': 'name',\n 'object': 'object',\n 'operator': 'operator',\n 'solution': 'solution',\n 'thresholds': 'thresholds',\n 'unit': 'unit'\n }\n\n def __init__(self, **kwargs): # noqa: E501\n \"\"\"GlobalAlertRule - a model defined in OpenAPI\"\"\" # noqa: E501\n self.local_vars_configuration = kwargs.get(\"local_vars_configuration\", Configuration.get_default_copy())\n\n self._alert_rules = None\n self._boolean = None\n self._cause = None\n self._default_thresholds = None\n self._disabled = None\n self._id = None\n self._impact = None\n self._message = None\n self._name = None\n self._object = None\n self._operator = None\n self._solution = None\n self._thresholds = None\n self._unit = None\n self.discriminator = None\n\n self.alert_rules = kwargs.get(\"alert_rules\", None)\n if \"boolean\" in kwargs:\n self.boolean = kwargs[\"boolean\"]\n if \"cause\" in kwargs:\n self.cause = kwargs[\"cause\"]\n if \"default_thresholds\" in kwargs:\n self.default_thresholds = kwargs[\"default_thresholds\"]\n if \"disabled\" in kwargs:\n self.disabled = kwargs[\"disabled\"]\n if \"id\" in kwargs:\n self.id = kwargs[\"id\"]\n if \"impact\" in kwargs:\n self.impact = kwargs[\"impact\"]\n if \"message\" in kwargs:\n self.message = kwargs[\"message\"]\n if \"name\" in kwargs:\n self.name = kwargs[\"name\"]\n self.object = kwargs.get(\"object\", None)\n if \"operator\" in kwargs:\n self.operator = kwargs[\"operator\"]\n if \"solution\" in kwargs:\n self.solution = kwargs[\"solution\"]\n if \"thresholds\" in kwargs:\n self.thresholds = kwargs[\"thresholds\"]\n if \"unit\" in kwargs:\n self.unit = kwargs[\"unit\"]\n\n @property\n def alert_rules(self):\n \"\"\"Gets the alert_rules of this GlobalAlertRule. # noqa: E501\n\n\n :return: The alert_rules of this GlobalAlertRule. # noqa: E501\n :rtype: list[NestedAlertRule]\n \"\"\"\n return self._alert_rules\n\n @alert_rules.setter\n def alert_rules(self, alert_rules):\n \"\"\"Sets the alert_rules of this GlobalAlertRule.\n\n\n :param alert_rules: The alert_rules of this GlobalAlertRule. # noqa: E501\n :type alert_rules: list[NestedAlertRule]\n \"\"\"\n\n self._alert_rules = alert_rules\n\n @property\n def boolean(self):\n \"\"\"Gets the boolean of this GlobalAlertRule. # noqa: E501\n\n\n :return: The boolean of this GlobalAlertRule. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._boolean\n\n @boolean.setter\n def boolean(self, boolean):\n \"\"\"Sets the boolean of this GlobalAlertRule.\n\n\n :param boolean: The boolean of this GlobalAlertRule. # noqa: E501\n :type boolean: bool\n \"\"\"\n if self.local_vars_configuration.client_side_validation and boolean is None: # noqa: E501\n raise ValueError(\"Invalid value for `boolean`, must not be `None`\") # noqa: E501\n\n self._boolean = boolean\n\n @property\n def cause(self):\n \"\"\"Gets the cause of this GlobalAlertRule. # noqa: E501\n\n\n :return: The cause of this GlobalAlertRule. # noqa: E501\n :rtype: str\n \"\"\"\n return self._cause\n\n @cause.setter\n def cause(self, cause):\n \"\"\"Sets the cause of this GlobalAlertRule.\n\n\n :param cause: The cause of this GlobalAlertRule. # noqa: E501\n :type cause: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and cause is None: # noqa: E501\n raise ValueError(\"Invalid value for `cause`, must not be `None`\") # noqa: E501\n\n self._cause = cause\n\n @property\n def default_thresholds(self):\n \"\"\"Gets the default_thresholds of this GlobalAlertRule. # noqa: E501\n\n\n :return: The default_thresholds of this GlobalAlertRule. # noqa: E501\n :rtype: list[NestedThresholds]\n \"\"\"\n return self._default_thresholds\n\n @default_thresholds.setter\n def default_thresholds(self, default_thresholds):\n \"\"\"Sets the default_thresholds of this GlobalAlertRule.\n\n\n :param default_thresholds: The default_thresholds of this GlobalAlertRule. # noqa: E501\n :type default_thresholds: list[NestedThresholds]\n \"\"\"\n if self.local_vars_configuration.client_side_validation and default_thresholds is None: # noqa: E501\n raise ValueError(\"Invalid value for `default_thresholds`, must not be `None`\") # noqa: E501\n\n self._default_thresholds = default_thresholds\n\n @property\n def disabled(self):\n \"\"\"Gets the disabled of this GlobalAlertRule. # noqa: E501\n\n\n :return: The disabled of this GlobalAlertRule. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._disabled\n\n @disabled.setter\n def disabled(self, disabled):\n \"\"\"Sets the disabled of this GlobalAlertRule.\n\n\n :param disabled: The disabled of this GlobalAlertRule. # noqa: E501\n :type disabled: bool\n \"\"\"\n if self.local_vars_configuration.client_side_validation and disabled is None: # noqa: E501\n raise ValueError(\"Invalid value for `disabled`, must not be `None`\") # noqa: E501\n\n self._disabled = disabled\n\n @property\n def id(self):\n \"\"\"Gets the id of this GlobalAlertRule. # noqa: E501\n\n\n :return: The id of this GlobalAlertRule. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this GlobalAlertRule.\n\n\n :param id: The id of this GlobalAlertRule. # noqa: E501\n :type id: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and id is None: # noqa: E501\n raise ValueError(\"Invalid value for `id`, must not be `None`\") # noqa: E501\n\n self._id = id\n\n @property\n def impact(self):\n \"\"\"Gets the impact of this GlobalAlertRule. # noqa: E501\n\n\n :return: The impact of this GlobalAlertRule. # noqa: E501\n :rtype: str\n \"\"\"\n return self._impact\n\n @impact.setter\n def impact(self, impact):\n \"\"\"Sets the impact of this GlobalAlertRule.\n\n\n :param impact: The impact of this GlobalAlertRule. # noqa: E501\n :type impact: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and impact is None: # noqa: E501\n raise ValueError(\"Invalid value for `impact`, must not be `None`\") # noqa: E501\n\n self._impact = impact\n\n @property\n def message(self):\n \"\"\"Gets the message of this GlobalAlertRule. # noqa: E501\n\n\n :return: The message of this GlobalAlertRule. # noqa: E501\n :rtype: str\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, message):\n \"\"\"Sets the message of this GlobalAlertRule.\n\n\n :param message: The message of this GlobalAlertRule. # noqa: E501\n :type message: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and message is None: # noqa: E501\n raise ValueError(\"Invalid value for `message`, must not be `None`\") # noqa: E501\n\n self._message = message\n\n @property\n def name(self):\n \"\"\"Gets the name of this GlobalAlertRule. # noqa: E501\n\n\n :return: The name of this GlobalAlertRule. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this GlobalAlertRule.\n\n\n :param name: The name of this GlobalAlertRule. # noqa: E501\n :type name: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501\n raise ValueError(\"Invalid value for `name`, must not be `None`\") # noqa: E501\n\n self._name = name\n\n @property\n def object(self):\n \"\"\"Gets the object of this GlobalAlertRule. # noqa: E501\n\n\n :return: The object of this GlobalAlertRule. # noqa: E501\n :rtype: AlertRuleObject\n \"\"\"\n return self._object\n\n @object.setter\n def object(self, object):\n \"\"\"Sets the object of this GlobalAlertRule.\n\n\n :param object: The object of this GlobalAlertRule. # noqa: E501\n :type object: AlertRuleObject\n \"\"\"\n\n self._object = object\n\n @property\n def operator(self):\n \"\"\"Gets the operator of this GlobalAlertRule. # noqa: E501\n\n\n :return: The operator of this GlobalAlertRule. # noqa: E501\n :rtype: str\n \"\"\"\n return self._operator\n\n @operator.setter\n def operator(self, operator):\n \"\"\"Sets the operator of this GlobalAlertRule.\n\n\n :param operator: The operator of this GlobalAlertRule. # noqa: E501\n :type operator: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and operator is None: # noqa: E501\n raise ValueError(\"Invalid value for `operator`, must not be `None`\") # noqa: E501\n\n self._operator = operator\n\n @property\n def solution(self):\n \"\"\"Gets the solution of this GlobalAlertRule. # noqa: E501\n\n\n :return: The solution of this GlobalAlertRule. # noqa: E501\n :rtype: str\n \"\"\"\n return self._solution\n\n @solution.setter\n def solution(self, solution):\n \"\"\"Sets the solution of this GlobalAlertRule.\n\n\n :param solution: The solution of this GlobalAlertRule. # noqa: E501\n :type solution: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and solution is None: # noqa: E501\n raise ValueError(\"Invalid value for `solution`, must not be `None`\") # noqa: E501\n\n self._solution = solution\n\n @property\n def thresholds(self):\n \"\"\"Gets the thresholds of this GlobalAlertRule. # noqa: E501\n\n\n :return: The thresholds of this GlobalAlertRule. # noqa: E501\n :rtype: list[NestedThresholds]\n \"\"\"\n return self._thresholds\n\n @thresholds.setter\n def thresholds(self, thresholds):\n \"\"\"Sets the thresholds of this GlobalAlertRule.\n\n\n :param thresholds: The thresholds of this GlobalAlertRule. # noqa: E501\n :type thresholds: list[NestedThresholds]\n \"\"\"\n if self.local_vars_configuration.client_side_validation and thresholds is None: # noqa: E501\n raise ValueError(\"Invalid value for `thresholds`, must not be `None`\") # noqa: E501\n\n self._thresholds = thresholds\n\n @property\n def unit(self):\n \"\"\"Gets the unit of this GlobalAlertRule. # noqa: E501\n\n\n :return: The unit of this GlobalAlertRule. # noqa: E501\n :rtype: AlertRuleUnit\n \"\"\"\n return self._unit\n\n @unit.setter\n def unit(self, unit):\n \"\"\"Sets the unit of this GlobalAlertRule.\n\n\n :param unit: The unit of this GlobalAlertRule. # noqa: E501\n :type unit: AlertRuleUnit\n \"\"\"\n if self.local_vars_configuration.client_side_validation and unit is None: # noqa: E501\n raise ValueError(\"Invalid value for `unit`, must not be `None`\") # noqa: E501\n\n self._unit = unit\n\n def to_dict(self, serialize=False):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n def convert(x):\n if hasattr(x, \"to_dict\"):\n args = getfullargspec(x.to_dict).args\n if len(args) == 1:\n return x.to_dict()\n else:\n return x.to_dict(serialize)\n else:\n return x\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n attr = self.attribute_map.get(attr, attr) if serialize else attr\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: convert(x),\n value\n ))\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], convert(item[1])),\n value.items()\n ))\n else:\n result[attr] = convert(value)\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GlobalAlertRule):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, GlobalAlertRule):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"smartxworks/cloudtower-python-sdk","sub_path":"cloudtower/models/global_alert_rule.py","file_name":"global_alert_rule.py","file_ext":"py","file_size_in_byte":14473,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"83"} +{"seq_id":"6333521046","text":"import pandas as pd\nimport sys\nimport numpy as np\n\n\ndef single_hamming(s1, s2):\n dist = 0\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n dist += 1\n return dist\n\n\n# There are two command line parameters: p1 p2\n# p1: path to the input file (valid path).\n# p2: is a float of how predominant the wildcard must be.\ndef main():\n threshold = float(sys.argv[2])\n data = pd.read_csv(sys.argv[1])\n data = data.iloc[:, 1:]\n stream = []\n for i in range(len(data)):\n data.iloc[i, :] = [\"{0:{fill}4b}\".format(j, fill='0') for j in data.iloc[i, :]]\n for i in range(len(data.iloc[0, :])):\n stream += list(data.iloc[:, i].values)\n N = len(stream)\n unique = np.unique(data)\n wildcards = []\n for item in unique:\n for i in range(len(item)):\n wildcard = item[:i] + 'x' + item[i+1:]\n wildcards.append(wildcard)\n candidates = list(set(wildcards))\n print(candidates)\n popularity = {}\n for candidate in candidates:\n for item in stream:\n if single_hamming(candidate, item) == 1:\n if candidate in popularity.keys():\n popularity[candidate] += 1\n else:\n popularity[candidate] = 0\n\n for key, value in popularity.items():\n if value >= threshold * N:\n print(key)\n\n\nmain()\n","repo_name":"jvitorbarbosa/thesis_project","sub_path":"do_wildcards.py","file_name":"do_wildcards.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"3199334792","text":"\"\"\"\nThis script explores as a baseline check whether PCA can recover the L, S, M cone wavelength selectivities from a hyperspectral image\n\"\"\"\nfrom spectral import *\nimport os\nfrom sklearn.decomposition import PCA\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport h5py\nfrom glob import glob\n\nnow = datetime.datetime.now() # current timestamp\n\nIM_PATH = '/media/big_hdd/opt-color/hyperspec_ims'\nim_list = glob(os.path.join(IM_PATH, '*.mat'))\nims = []\nfor im in im_list[:15]:\n try:\n temp = h5py.File(im)['rad'][:]\n if temp.shape == (31, 1392, 1300):\n ims.append(temp)\n except(OSError):\n print(f'Could not load {im}')\nims = np.stack(ims)\n\nwavelength_i = h5py.File(im)['bands'][:]\nwavelength_i = np.array([int(i) for i in wavelength_i])\n\n# Collapse across pixels and across images\nims = ims.transpose(1,0,2,3)\nims = ims.reshape(ims.shape[0], -1)\n\npca = PCA(n_components=4)\npca.fit(ims.T)\n\n\n# Project to first three dimensions and plot results\ncomp = pca.components_\nfig = plt.figure(figsize=(15,5))\nplt.plot(comp.T)\nlocs, labels = plt.xticks()\nplt.legend(['Photoreceptor 1', 'Photoreceptor 2', 'Photoreceptor 3', 'Photoreceptor 4'])\nplt.xticks(np.arange(len(wavelength_i)), wavelength_i)\nplt.ylabel('Weight Value')\nplt.xlabel('Wavelength')\nplt.title('PCA Projection to 4 Photoreceptors')\nplt.savefig(f'pca_4_{now}.png', bbox_inches='tight')\nplt.close()\n# Skree plot\n# import ipdb; ipdb.set_trace()\nplt.plot(pca.explained_variance_ratio_)\nplt.ylabel('PCA explained variance ratio')\nplt.xlabel('Components')\nplt.title('Explained Variance of PCA Components')\nplt.savefig(f'pca_scree_4_{now}.png', bbox_inches='tight')\n","repo_name":"micwinter/optimal-coding-color","sub_path":"pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"15209794746","text":"def message():\n print(\"Command List\")\n print(\"show-\\tdisplay all Guitars list\")\n print(\"add-\\tadd Guitar \")\n print(\"edit-\\tedit Guitar \")\n print(\"del\\tdelete a Guitar \")\n print(\"exit-\\texit program\")\n\n\ndef show_guitar_catalog(Guitar_Catalog):\n Guitar_type = input(\"Guitar Type ? \")\n if Guitar_type in Guitar_Catalog:\n Guitar = Guitar_Catalog[Guitar_type]\n print(\"Guitar Type Is: \" + Guitar_type)\n print(\"Guiar Description\" + Guitar[\"description\"])\n print(\"Guitar Price\" + str(Guitar[\"price\"]))\n else:\n print(\"sorry this type is not found in our database\")\n\n\ndef add_edit_guitar(Guitar_Catalog, mode):\n Guitar_type = input(\"Guitar Type Is: \")\n if mode == \"add\" and Guitar_type in Guitar_Catalog:\n print(Guitar_type + \" is already exists in the Catalog\")\n response = input(\"would you like to edit it? (y/n) \").lower()\n if response != \"y\":\n return\n elif mode == \"edit\" and Guitar_type in Guitar_Catalog:\n print(Guitar_type + \"dosn't exist in the catalog \")\n response = input(\"would you like to edit it ? (y/n) \").lower()\n if response != \"y\":\n return\n description = input(\"Description: \")\n price = int(input(\"Price: \"))\n Guitar = {\"Type\": Guitar_type, \"description\": description, \"price\": price}\n Guitar_Catalog[Guitar_type] = Guitar\n\n\n\ndef delete_guitar(Guitar_Catalog):\n Guitar_type = input(\"Guitar Type Is: \")\n if Guitar_type in Guitar_Catalog:\n del Guitar_Catalog[Guitar_type]\n print(Guitar_type, \"removed from our catalog \")\n else:\n print(Guitar_type, \"is not exists in our catalog\")\n\n\n\ndef main():\n Guitar_Catalog = {\"Type\": \"Full Size Blue Electric Guitar with Amp\", \n \"description\": \"Constructed with a hardwood body and fingerboard with truss rod neck\",\n \"price\": 300\n }\n message()\n while True:\n command = input(\"Enter The Command: \")\n if command == \"show\":\n show_guitar_catalog(Guitar_Catalog)\n elif command == \"add\":\n add_edit_guitar(Guitar_Catalog, mode=\"add\")\n elif command == \"edit\":\n add_edit_guitar(Guitar_Catalog, mode=\"edit\")\n elif command == \"del\":\n delete_guitar(Guitar_Catalog)\n elif command == \"exit\":\n print(\"bye\")\n break\n else:\n print(\"unkonwn commmand please try again \")\n\nif __name__ == \"__main__\":\n main()\n \n \n\n\n\n \n\n\n\n\n\n\n\n \n \n \n \n\n\n\n \n \n \n","repo_name":"Gharib84/Python_Programs","sub_path":"Guitar_Shop/guitar.py","file_name":"guitar.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"13598995837","text":"geoid_list = [4030723]\nname_list = [\"Adamstown\"]\nascii_name_list = [0]\nalternate_names_list = [[\"Adams Town\"]]\nlatitude_list = [-25.06597]\nlongitude_list = [-130.10147]\ncountry_code_list = [\"PN\"]\npopulation_list = [46]\ndem_list = [67]\ntimezone_list = [348]\naltitude_list = [-1]\n_feature_class_list = [\"P\"]\n_feature_code_list = [\"PPLC\"]\n_parent_code_list = [\"PN\"]\n_states = {}\n_districts = {}","repo_name":"ufukk/plaincities","sub_path":"src/plaincities/_values/en/PN_en.py","file_name":"PN_en.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"17304161487","text":"import datetime\r\nfrom django.utils import timezone\r\nfrom django.shortcuts import render\r\nfrom django.http import HttpResponse\r\nfrom django.contrib import messages\r\nfrom django.db import transaction\r\nfrom django.contrib.auth import authenticate, login, logout\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.models import User\r\nfrom .models import MyUser\r\n\r\n\r\ndef index(request):\r\n if request.user.is_authenticated:\r\n myuser = MyUser.objects.get(user=request.user)\r\n if myuser.money == 0:\r\n diff = timezone.now() - myuser.time_zero\r\n if diff.days >= 1:\r\n myuser.money = 30000\r\n myuser.save()\r\n\r\n return render(request, 'main/index.html')\r\n\r\n@transaction.atomic\r\ndef signup(request):\r\n context = dict()\r\n if request.POST:\r\n try:\r\n user = User() \r\n user.first_name = request.POST['name']\r\n if not request.POST['username'].isalnum():\r\n raise Exception('Nickname must be alphanumeric!')\r\n user.username = request.POST['username'] \r\n user.set_password(request.POST['password'])\r\n user.save()\r\n\r\n myuser = MyUser()\r\n myuser.user = user\r\n myuser.email = request.POST['email'] \r\n myuser.country = request.POST['country']\r\n myuser.money = 30000\r\n myuser.save()\r\n\r\n authenticate(request, username=request.POST['username'], password=request.POST['password'])\r\n login(request, user) \r\n except Exception as error:\r\n messages.add_message(request, messages.ERROR, 'Error: ' + str(error))\r\n context = {'show_signup': True}\r\n\r\n return render(request, 'main/index.html', context)\r\n\r\ndef signin(request):\r\n context = dict()\r\n if request.POST:\r\n try:\r\n myuser = MyUser.objects.get(email=request.POST['email'])\r\n user = authenticate(request, username=myuser.user.username, password=request.POST['password'])\r\n login(request, user)\r\n myuser.token = str(hash(datetime.datetime.now())) \r\n myuser.save()\r\n\r\n if myuser.money == 0:\r\n diff = timezone.now() - myuser.time_zero \r\n if diff.days >= 1:\r\n myuser.money = 30000\r\n myuser.save()\r\n\r\n except Exception as error:\r\n messages.add_message(request, messages.ERROR, 'Invalid email or password! ' + str(error))\r\n context = {'show_signin': True}\r\n\r\n return render(request, 'main/index.html', context)\r\n\r\ndef signout(request):\r\n logout(request)\r\n return render(request, 'main/index.html')\r\n\r\ndef contact(request):\r\n return render(request, 'main/index.html')\r\n\r\n@login_required\r\ndef play(request):\r\n myuser = MyUser.objects.get(user=request.user)\r\n if myuser.money == 0:\r\n return render(request, 'main/index.html', {'show_cannotplay': True})\r\n\r\n return render(request, 'main/game.html', {'token': myuser.token})\r\n\r\n\r\ndef ack(request): \r\n try:\r\n myuser = MyUser.objects.get(token=request.GET['token'])\r\n return HttpResponse('OK')\r\n except Exception:\r\n return HttpResponse('ERROR')\r\n\r\n\r\ndef update_money(request):\r\n if '127.0.0.1' in request.META['HTTP_HOST']:\r\n username = request.GET['name']\r\n money = request.GET['money']\r\n user = User.objects.get(username=username)\r\n myuser = MyUser.objects.get(user=user)\r\n myuser.money = money\r\n if money == 0:\r\n myuser.time_zero = datetime.datetime.now()\r\n myuser.save()\r\n return HttpResponse('OK')\r\n return HttpResponse('ERROR')","repo_name":"rafapaz/poker","sub_path":"django/poker/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"72813585230","text":"# thermal is our template image for registration\n\nimport os\nimport cv2\nimport time\nimport numpy as np\nfrom skimage.measure import shannon_entropy, compare_ssim\nfrom imageai.Detection import ObjectDetection\nfrom skimage.exposure import adjust_gamma\nfrom imutils.video import VideoStream, FileVideoStream, FPS\n\ndef ecc_registration(thermal, visible, warp_mode = cv2.MOTION_AFFINE):\n is_thermal_reference = True\n template_img = None\n register_img = None\n\n if is_thermal_reference:\n template_img = thermal\n register_img = visible\n else:\n template_img = visible\n register_img = thermal\n\n (h,w) = template_img.shape[:2]\n register_img = cv2.resize(register_img, (w,h))\n\n # template_img_gray = template_img\n # register_img_gray = register_img\n\n template_img_gray = cv2.cvtColor(template_img, cv2.COLOR_RGB2GRAY)\n register_img_gray = cv2.cvtColor(register_img, cv2.COLOR_RGB2GRAY)\n\n # cv2.imshow(\"Template Image\", template_img_gray)\n # cv2.imshow(\"Register Image\", register_img_gray)\n # cv2.waitKey()\n\n # Preprocessing\n if is_thermal_reference:\n register_img_gray = adjust_gamma(register_img_gray, 0.5)\n # kernel = np.array([[-1, -1, -1],\n # [-1, 9, -1],\n # [-1, -1, -1]])\n # register_img_gray = cv2.filter2D(register_img_gray, -1, kernel)\n else:\n template_img = adjust_gamma(template_img, 0.5)\n # kernel = np.array([[-1, -1, -1],\n # [-1, 9, -1],\n # [-1, -1, -1]])\n # template_img = cv2.filter2D(template_img, -1, kernel)\n\n # Find warp matrix\n warp_matrix = align(template_img_gray, register_img_gray, warp_mode, 50, 1e-3, 2)\n\n # if warp_mode == cv2.MOTION_HOMOGRAPHY:\n # # Use warpPerspective for Homography\n # aligned_img = cv2.warpPerspective(register_img, warp_matrix, (w, h), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)\n # else:\n # # Use warpAffine for Translation, Euclidean and Affine\n # aligned_img = cv2.warpAffine(register_img, warp_matrix, (w, h), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)\n\n # print(warp_matrix)\n # dst = cv2.addWeighted(thermal, 0.5, aligned_img, 0.5, 0.0)\n # cv2.imshow(\"Blending Image\", dst)\n # cv2.waitKey()\n # cv2.destroyAllWindows()\n return warp_matrix\n\ndef align(ref_img, match_img, warp_mode=cv2.MOTION_AFFINE, max_iterations=300, epsilon_threshold=1e-10, pyramid_levels=2,\n is_video=False):\n if pyramid_levels is None:\n w = ref_img.shape[1]\n nol = int(w / (1280 / 3)) - 1\n else:\n nol = pyramid_levels\n\n # Initialize the matrix to identity\n if warp_mode == cv2.MOTION_HOMOGRAPHY:\n # warp_matrix = np.eye(3, 3, dtype=np.float32)\n warp_matrix = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32)\n else:\n # warp_matrix = np.eye(2, 3, dtype=np.float32)\n warp_matrix = np.array([[1, 0, 0], [0, 1, 0]], dtype=np.float32)\n\n ref_img = cv2.fastNlMeansDenoising(ref_img, None, 5, 21)\n match_img = cv2.fastNlMeansDenoising(match_img, None, 5, 21)\n\n kernel = np.ones((11, 11), np.uint8)\n ref_img = cv2.morphologyEx(ref_img, cv2.MORPH_OPEN, kernel)\n match_img = cv2.morphologyEx(match_img, cv2.MORPH_OPEN, kernel)\n\n ref_img = gradient(ref_img)\n match_img = gradient(match_img)\n\n ref_img_pyr = [ref_img]\n match_img_pyr = [match_img]\n\n for level in range(nol):\n ref_img_pyr[0] = normalize(ref_img_pyr[0])\n ref_img_pyr.insert(0, cv2.resize(ref_img_pyr[0], None, fx=1/2, fy=1/2, interpolation=cv2.INTER_LINEAR))\n match_img_pyr[0] = normalize(match_img_pyr[0])\n match_img_pyr.insert(0, cv2.resize(match_img_pyr[0], None, fx=1/2, fy=1/2, interpolation=cv2.INTER_LINEAR))\n\n # Terminate the optimizer if either the max iterations or the threshold are reached\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, max_iterations, epsilon_threshold)\n # run pyramid ECC\n for level in range(nol):\n ref_img_grad = ref_img_pyr[level]\n match_img_grad = match_img_pyr[level]\n try:\n cc, warp_matrix = cv2.findTransformECC(ref_img_grad, match_img_grad, warp_matrix, warp_mode, criteria, inputMask=None, gaussFiltSize=1)\n except TypeError:\n cc, warp_matrix = cv2.findTransformECC(ref_img_grad, match_img_grad, warp_matrix, warp_mode, criteria)\n\n if level != nol: # scale up only the offset by a factor of 2 for the next (larger image) pyramid level\n if warp_mode == cv2.MOTION_HOMOGRAPHY:\n warp_matrix = warp_matrix * np.array([[1, 1, 2], [1, 1, 2], [0.5, 0.5, 1]], dtype=np.float32)\n else:\n warp_matrix = warp_matrix * np.array([[1, 1, 2], [1, 1, 2]], dtype=np.float32)\n \n # return warp_matrix\n return warp_matrix\n\ndef gradient(im, ksize=15):\n im = normalize(im)\n grad_x = cv2.Sobel(im, cv2.CV_32FC1, 1, 0, ksize=ksize)\n grad_y = cv2.Sobel(im, cv2.CV_32FC1, 0, 1, ksize=ksize)\n grad = cv2.addWeighted(np.absolute(grad_x), 0.5, np.absolute(grad_y), 0.5, 0)\n return convert_to_img(grad)\n\ndef normalize(im, min=None, max=None):\n width, height = im.shape\n norm = np.zeros((width, height), dtype=np.float32)\n if min is not None and max is not None:\n norm = (im - min) / (max - min)\n else:\n cv2.normalize(im, dst=norm, alpha=0.0, beta=1.0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32FC1)\n norm[norm < 0.0] = 0.0\n norm[norm > 1.0] = 1.0\n return norm\n\ndef convert_to_img(img):\n img = np.multiply(np.divide(img - np.min(img), (np.max(img) - np.min(img))), 255)\n img = img.astype(np.uint8)\n return img\n\ndef corr2d(a,b):\n a = a - np.mean(a)\n b = b - np.mean(b)\n r = np.sum(a*b) / float(np.sqrt(np.sum(a**2) * np.sum(b**2)))\n return r\n\ndef calculate_correlation_coef(thermal, visible):\n thermal_gray = cv2.cvtColor(thermal, cv2.COLOR_BGR2GRAY)\n visible_gray = cv2.cvtColor(visible, cv2.COLOR_BGR2GRAY)\n return corr2d(visible_gray, thermal_gray)\n\ndef fixBorder(frame):\n s = frame.shape\n # Scale the image 4% without moving the center\n T = cv2.getRotationMatrix2D((s[1]/2, s[0]/2), 0, 1.04)\n frame = cv2.warpAffine(frame, T, (s[1], s[0]))\n return frame\n\ndef get_initial_transformaton_matrix(thermal_cap, visible_cap, frame_count):\n initial_matrix = None\n # frame_num = int(frame_count/4)\n frame_indexes = np.random.choice(range(0, frame_count), size = 10, replace = False)\n warp_matrix_list = []\n \n print()\n print(\"*************************************\")\n print(\"Get initial transformation matrix....\")\n print(frame_indexes)\n print(\"Processing \" + str(len(frame_indexes)) + \" selected frames\")\n\n for i, frame_index in enumerate(frame_indexes):\n print(\"Frame \" + str(i+1) + \"/\" + str(len(frame_indexes)))\n thermal_cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)\n visible_cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)\n _, thermal_frame = thermal_cap.read()\n _, visible_frame = visible_cap.read()\n\n (h, w) = visible_frame.shape[:2]\n thermal_frame = cv2.resize(thermal_frame, (w, h))\n warp_matrix_list.append(ecc_registration(thermal_frame, visible_frame))\n \n initial_matrix = np.mean(np.array(warp_matrix_list), axis=0)\n\n print(\"Initial transformatrion matrix:\")\n print(initial_matrix)\n print(\"*************************************\")\n print()\n\n # set camera capture to init position\n thermal_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n visible_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n return initial_matrix\n\ndef finetune_registration(detector, custom, thermal, visible, fused, corr_coef_after_registration):\n (h, w) = visible.shape[:2]\n \n after_registration_object, after_registration_detections = detector.detectCustomObjectsFromImage(custom_objects = custom,\n input_type = \"array\",\n input_image = fused,\n output_type = \"array\",\n minimum_percentage_probability=30)\n \n # cv2.imshow(\"Bounding Box\", cv2.resize(after_registration_object, (800, 500)))\n # cv2.waitKey()\n\n if len(after_registration_detections) == 0 :\n print(\"No human object detection!\")\n return visible\n\n # get biggest bounding boxes (closest object)\n final_bounding_box = after_registration_detections[0][\"box_points\"]\n max_area = (final_bounding_box[2] - final_bounding_box[0]) * (final_bounding_box[3] - final_bounding_box[1])\n if len(after_registration_detections) > 1:\n for bounding_box in after_registration_detections:\n local_width = bounding_box[\"box_points\"][2] - bounding_box[\"box_points\"][0]\n local_height = bounding_box[\"box_points\"][3] - bounding_box[\"box_points\"][1]\n local_area = local_width * local_height\n if(local_area > max_area):\n final_bounding_box = bounding_box[\"box_points\"]\n max_area = local_area\n\n # set bounding boxes location\n x1 = final_bounding_box[0] - 50\n y1 = final_bounding_box[1] - 50\n x2 = final_bounding_box[2] + 50\n y2 = final_bounding_box[3] + 50\n\n start_point = (x1 if x1 > 0 else 0, y1 if y1 > 0 else 0)\n end_point = (x2 if x2 < w-1 else w-1, y2 if y2 < h-1 else h-1)\n\n object_thermal = thermal[start_point[1]:end_point[1], start_point[0]:end_point[0]]\n object_visible = visible[start_point[1]:end_point[1], start_point[0]:end_point[0]]\n\n # get fintune matrix for object\n finetune_matrix = ecc_registration(object_thermal, object_visible, warp_mode=cv2.MOTION_TRANSLATION)\n finetuned_visible = cv2.warpAffine(visible, finetune_matrix, (w, h), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)\n\n if np.abs(calculate_correlation_coef(fixBorder(thermal), fixBorder(finetuned_visible))) > np.abs(corr_coef_after_registration):\n return finetuned_visible\n return visible\n\ndef run(detector, custom, thermal_video_path, visible_video_path, output_video):\n thermal_cap = cv2.VideoCapture(thermal_video_path)\n visible_cap = cv2.VideoCapture(visible_video_path)\n\n # get thermal and visible video primary info\n video_fps = thermal_cap.get(cv2.CAP_PROP_FPS)\n frame_count = int(thermal_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n print(\"Video FPS:\", video_fps)\n print(\"Number of frames:\", frame_count)\n\n # resolution for both thermal and visible\n fps = FPS().start() \n # (w, h) = (2048, 1536)\n (w, h) = int(visible_cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(visible_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n # init video writer\n out = cv2.VideoWriter(output_video, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30, (2*w, h), True)\n \n initial_transformation_matrix = get_initial_transformaton_matrix(thermal_cap, visible_cap, frame_count)\n # initial_transformation_matrix = np.array([[9.9126685e-01, 5.3021866e-03, 1.8741880e+01], [9.3280076e-04, 1.0312355e+00, -2.4526514e+01]])\n\n print(\"Processing thermal and visible videos...\")\n print(\"+++++++++++++++++++++++++++++++++++++\")\n\n index = 1\n while True:\n _, thermal_frame = thermal_cap.read()\n _, visible_frame = visible_cap.read()\n\n # if index < 89:\n # index += 1\n # continue\n\n if thermal_frame is None or visible_frame is None:\n break\n \n print(\"Frame \" + str(index) + \"/\" + str(frame_count))\n # resize thermal to visible resolution\n thermal_frame = cv2.resize(thermal_frame, (w, h))\n\n # visualize before registration\n print(\"Correlation Coef Before Registration:\", calculate_correlation_coef(fixBorder(thermal_frame), fixBorder(visible_frame)))\n before_registration = cv2.addWeighted(thermal_frame, 0.5, visible_frame, 0.5, 0.0)\n cv2.imshow(\"Before Registration\", cv2.resize(before_registration, (800, 500)))\n cv2.waitKey(1)\n\n # get registered visible frame\n registered_visible_frame = cv2.warpAffine(visible_frame, initial_transformation_matrix, (w, h), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)\n \n # visualize after applying initial transformation matrix\n after_registration = cv2.addWeighted(thermal_frame, 0.5, registered_visible_frame, 0.5, 0.0)\n corr_coef_after_registration = calculate_correlation_coef(fixBorder(thermal_frame), fixBorder(registered_visible_frame))\n print(\"Correlation Coef After Initial Registration:\", corr_coef_after_registration)\n cv2.imshow(\"After Initial Registration\", cv2.resize(after_registration, (800, 500)))\n cv2.waitKey(1)\n \n\n # finetune registration\n finetuned_visible_frame = finetune_registration(detector, custom, thermal_frame, registered_visible_frame, after_registration, corr_coef_after_registration)\n after_finetune = cv2.addWeighted(thermal_frame, 0.5, finetuned_visible_frame, 0.5, 0.0)\n print(\"Correlation Coef After Finetune Registration:\", calculate_correlation_coef(fixBorder(thermal_frame), fixBorder(finetuned_visible_frame)))\n cv2.imshow(\"After Finetune Registration\", cv2.resize(after_finetune, (800, 500)))\n cv2.waitKey(1)\n\n frame_out = cv2.hconcat([after_finetune, after_registration])\n out.write(frame_out)\n index += 1\n fps.update()\n # cv2.destroyAllWindows()\n print(\"+++++++++++++++++++++++++++++++++++++\")\n\n fps.stop()\n print(\"Elasped time: {:.2f}\".format(fps.elapsed()))\n print(\"Approx. FPS: {:.2f}\".format(fps.fps()))\n thermal_cap.release()\n visible_cap.release()\n # out.release()\n # cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n # init YOLOv3 object detector for person\n execution_path = os.getcwd()\n detector = ObjectDetection()\n detector.setModelTypeAsYOLOv3()\n detector.setModelPath(os.path.join(execution_path , \"yolo.h5\"))\n detector.loadModel()\n custom = detector.CustomObjects(person=True)\n \n # paths to videos\n thermal_video_path = \"./440/thermal_440.avi\"\n visible_video_path = \"./440/visible_440.avi\"\n output_video = \"./auto_registration_440.avi\"\n\n # run auto registration\n run(detector, custom, thermal_video_path, visible_video_path, output_video)","repo_name":"tdhcuong/Anomaly_Detection","sub_path":"auto_registration.py","file_name":"auto_registration.py","file_ext":"py","file_size_in_byte":14192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"7602730367","text":"from multi_parser.settings import ChannelToLocales\nfrom multi_parser.shared import (\n ParsingResponse,\n LocalizedParsingResponse,\n ParsingRequest,\n)\n\n\n__all__ = [\n 'I18n',\n]\n\n\nclass I18n:\n\n _DEFAULT_LOCALE = 'en'\n\n def __init__(\n self,\n channel_to_locales: ChannelToLocales,\n ) -> None:\n\n self._channel_to_locales = channel_to_locales\n\n def translate_channel_user_data(\n self,\n request: ParsingRequest,\n parsing_response: ParsingResponse\n ) -> LocalizedParsingResponse:\n\n localized_channel_user_data = {}\n if request.channel in self._channel_to_locales:\n channel_locales = self._channel_to_locales[request.channel]\n for field, locale_field in channel_locales.items():\n localized_channel_user_data[locale_field[self._DEFAULT_LOCALE]] = \\\n parsing_response.channel_user_data[field] \\\n if field in parsing_response.channel_user_data else 'unknown'\n\n return LocalizedParsingResponse(\n localized_channel_user_data=localized_channel_user_data or parsing_response.channel_user_data,\n )\n","repo_name":"ilya-mezentsev/multi-parser","sub_path":"multi_parser/channels/i18n.py","file_name":"i18n.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"26801123263","text":"from __future__ import annotations\n\nimport logging\nimport os\nfrom typing import TYPE_CHECKING\n\nimport pytest\nfrom colorama import Style, deinit\n\nfrom tox.report import setup_report\n\nif TYPE_CHECKING:\n from pytest_mock import MockerFixture\n\n from tox.pytest import CaptureFixture\n\n\n@pytest.mark.parametrize(\"color\", [True, False], ids=[\"on\", \"off\"])\n@pytest.mark.parametrize(\"verbosity\", range(7))\ndef test_setup_report(mocker: MockerFixture, capsys: CaptureFixture, verbosity: int, color: bool) -> None:\n color_init = mocker.patch(\"tox.report.init\")\n\n setup_report(verbosity=verbosity, is_colored=color)\n try:\n logging.critical(\"critical\")\n logging.error(\"error\")\n # special warning line that should be auto-colored\n logging.warning(\"%s%s> %s\", \"warning\", \"foo\", \"bar\")\n logging.info(\"info\")\n logging.debug(\"debug\")\n logging.log(logging.NOTSET, \"not-set\") # this should not be logged\n disabled = \"distlib.util\", \"filelock\"\n for name in disabled:\n logger = logging.getLogger(name)\n logger.warning(\"%s-warn\", name)\n logger.info(\"%s-info\", name)\n logger.debug(\"%s-debug\", name)\n logger.log(logging.NOTSET, \"%s-notset\", name)\n finally:\n deinit()\n\n assert color_init.call_count == (1 if color else 0)\n\n msg_count = min(verbosity + 1, 5)\n is_debug_or_more = verbosity >= 4\n if is_debug_or_more:\n msg_count += 1 # we log at debug level setting up the logger\n\n out, err = capsys.readouterr()\n assert not err\n assert out\n assert \"filelock\" not in out\n assert \"distlib.util\" not in out\n lines = out.splitlines()\n assert len(lines) == msg_count, out\n\n if is_debug_or_more and lines: # assert we start with relative created, contain path\n line = lines[0]\n int(line.split(\" \")[1]) # first element is an int number\n assert f\"[tox{os.sep}report.py\" in line # relative file location\n\n if color:\n assert f\"{Style.RESET_ALL}\" in out\n # check that our Warning line using special format was colored\n expected_warning_text = \"W\\x1b[0m\\x1b[36m warning\\x1b[22mfoo\\x1b[2m>\\x1b[0m bar\\x1b[0m\\x1b[2m\"\n else:\n assert f\"{Style.RESET_ALL}\" not in out\n expected_warning_text = \"warningfoo> bar\"\n if verbosity >= 4: # where warnings are logged\n assert expected_warning_text in lines[3]\n","repo_name":"tox-dev/tox","sub_path":"tests/test_report.py","file_name":"test_report.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","stars":3399,"dataset":"github-code","pt":"83"} +{"seq_id":"33329906508","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\n# disable: accessing protected members, too many methods\n# pylint: disable=W0212,R0904\n\nfrom hamcrest import is_\nfrom hamcrest import not_\nfrom hamcrest import none\nfrom hamcrest import is_not\nfrom hamcrest import has_key\nfrom hamcrest import has_entry\nfrom hamcrest import has_length\nfrom hamcrest import assert_that\nfrom hamcrest import has_property\n\nimport os\nimport copy\nimport unittest\nimport simplejson\n\nfrom nti.app.contenttypes.presentation.decorators.lessons import _LessonPublicationConstraintsDecorator\n\nfrom nti.contenttypes.presentation.interfaces import INTIVideoRef\nfrom nti.contenttypes.presentation.interfaces import ILessonPublicationConstraints\nfrom nti.contenttypes.presentation.interfaces import INTIAssignmentRef\nfrom nti.contenttypes.presentation.interfaces import INTICourseOverviewGroup\n\nfrom nti.contenttypes.presentation.lesson import NTICourseOverViewSpacer\nfrom nti.contenttypes.presentation.lesson import NTILessonOverView\nfrom nti.contenttypes.presentation.lesson import AssignmentCompletionConstraint\n\nfrom nti.contenttypes.presentation.utils import prepare_json_text\nfrom nti.contenttypes.presentation.utils import create_object_from_external\nfrom nti.contenttypes.presentation.utils import create_ntilessonoverview_from_external\n\nfrom nti.externalization.externalization import to_external_object\n\nfrom nti.externalization.interfaces import StandardExternalFields\n\nfrom nti.testing.matchers import is_false\nfrom nti.testing.matchers import validly_provides\n\nfrom . import SharedConfiguringTestLayer\n\n\nITEMS = StandardExternalFields.ITEMS\n\n\nclass TestLesson(unittest.TestCase):\n\n layer = SharedConfiguringTestLayer\n\n def test_property(self):\n s = NTICourseOverViewSpacer()\n ntiid = s.ntiid\n assert_that(ntiid, is_not(none()))\n assert_that(s, has_property('ntiid', is_(ntiid)))\n assert_that(s.ntiid, is_(ntiid))\n\n def test_nticourseoverviewspacer(self):\n path = os.path.join(os.path.dirname(__file__), 'nticourseoverviewspacer.json')\n with open(path, \"r\") as fp:\n source = simplejson.loads(prepare_json_text(fp.read()))\n original = copy.deepcopy(source)\n\n spacer = create_object_from_external(source)\n assert_that(spacer, has_property('ntiid', is_not(none())))\n assert_that(spacer,\n\t\t\t\t\thas_property('mimeType', is_(\"application/vnd.nextthought.nticourseoverviewspacer\")))\n\n ext_obj = to_external_object(spacer)\n for k, v in original.items():\n assert_that(ext_obj, has_entry(k, is_(v)))\n\n def test_ntilessonoverview(self):\n path = os.path.join(os.path.dirname(__file__), 'ntilessonoverview.json')\n with open(path, \"r\") as fp:\n source = simplejson.loads(prepare_json_text(fp.read()))\n\n lesson = create_ntilessonoverview_from_external(source)\n assert_that(lesson,\n\t\t\t\t\thas_property('ntiid', is_('tag:nextthought.com,2011-10:OU-NTILessonOverview-LSTD1153_S_2015_History_United_States_1865_to_Present.lec:11.06_LESSON')))\n assert_that(lesson,\n\t\t\t\t\thas_property('lesson', is_('tag:nextthought.com,2011-10:OU-HTML-LSTD1153_S_2015_History_United_States_1865_to_Present.lec:11.06_LESSON')))\n assert_that(lesson, has_property('Items', has_length(5)))\n assert_that(lesson,\n\t\t\t\t\thas_property('mimeType', is_(\"application/vnd.nextthought.ntilessonoverview\")))\n\n assert_that(lesson, has_length(5))\n assert_that(list(lesson), has_length(5))\n for item in lesson:\n assert_that(item, validly_provides(INTICourseOverviewGroup))\n\n for item in lesson[1]:\n assert_that(item, validly_provides(INTIAssignmentRef))\n\n for item in lesson[3]:\n assert_that(item, validly_provides(INTIVideoRef))\n\n assert_that(lesson[4], has_length(0))\n\n ext_obj = to_external_object(lesson)\n assert_that(ext_obj, has_key('Class'))\n assert_that(ext_obj,\n\t\t\t\t\thas_entry('NTIID', is_(\"tag:nextthought.com,2011-10:OU-NTILessonOverview-LSTD1153_S_2015_History_United_States_1865_to_Present.lec:11.06_LESSON\")))\n assert_that(ext_obj,\n\t\t\t\t\thas_entry('MimeType', is_(\"application/vnd.nextthought.ntilessonoverview\")))\n assert_that(ext_obj,\n\t\t\t\t\thas_entry('title', is_(\"11.6 Apply Your Knowledge\")))\n assert_that(ext_obj, has_entry('Items', has_length(5)))\n\n assert_that(lesson.remove(lesson.Items[0]), is_(True))\n assert_that(lesson, has_length(4))\n\n def test_ntilessonoverview_exporter(self):\n path = os.path.join(os.path.dirname(__file__), 'ntilessonoverview.json')\n with open(path, \"r\") as fp:\n source = simplejson.loads(prepare_json_text(fp.read()))\n\n lesson = create_ntilessonoverview_from_external(source)\n ext_obj = to_external_object(lesson, name=\"exporter\")\n assert_that(ext_obj, has_key('Class'))\n assert_that(ext_obj,\n\t\t\t\t\thas_entry('NTIID', is_(\"tag:nextthought.com,2011-10:OU-NTILessonOverview-LSTD1153_S_2015_History_United_States_1865_to_Present.lec:11.06_LESSON\")))\n assert_that(ext_obj,\n\t\t\t\t\thas_entry('MimeType', is_(\"application/vnd.nextthought.ntilessonoverview\")))\n assert_that(ext_obj,\n\t\t\t\t\thas_entry('title', is_(\"11.6 Apply Your Knowledge\")))\n assert_that(ext_obj, has_entry('Items', has_length(5)))\n assert_that(ext_obj, has_entry('isPublished', is_false()))\n assert_that(ext_obj, has_entry('isLocked', is_false()))\n assert_that(ext_obj, has_entry('isChildOrderLocked', is_false()))\n\n\nclass TestDecoration(unittest.TestCase):\n\n layer = SharedConfiguringTestLayer\n\n def _decorate(self, decorator, context):\n external = to_external_object(context, decorate=False)\n decorator = decorator(context, None)\n decorator.authenticated_userid = 'testuser'\n decorator.decorateExternalMapping(context, external)\n return external\n\n def testPublicationConstraints(self):\n context = NTILessonOverView()\n\n external = self._decorate(_LessonPublicationConstraintsDecorator, context)\n assert_that(external, not_(has_key('PublicationConstraints')))\n\n assignment_ntiid = u'tag:nextthought.com,2011-10:specific'\n constraint = AssignmentCompletionConstraint(assignments=(assignment_ntiid,))\n ILessonPublicationConstraints(context).append(constraint)\n\n external = self._decorate(_LessonPublicationConstraintsDecorator, context)\n assert_that(external, has_key('PublicationConstraints'))\n","repo_name":"OpenNTI/nti.app.contenttypes.presentation","sub_path":"src/nti/app/contenttypes/presentation/decorators/tests/test_lesson.py","file_name":"test_lesson.py","file_ext":"py","file_size_in_byte":6640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"12915943051","text":"from flask import Flask, render_template, request, jsonify\nimport aiml\nimport os\nimport mnbpy\nimport logpy\nimport pickle\nimport pandas as pd\nimport csv\n\nmnb = pickle.load(open('mnb.pickle', 'rb'))\nlog = pickle.load(open('log.pickle', 'rb'))\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return render_template('chat.html')\n\n@app.route(\"/ask\", methods=['POST'])\ndef ask():\n\n message =request.form['messageText'].strip()\n\n kernel = aiml.Kernel()\n\n if os.path.isfile(\"bot_brain.brn\"):\n kernel.bootstrap(brainFile = \"bot_brain.brn\")\n else:\n kernel.bootstrap(learnFiles = os.path.abspath(\"aiml/startup.xml\"), commands = \"load aiml b\")\n kernel.saveBrain(\"bot_brain.brn\")\n\n while True:\n if message == \"quit\":\n exit()\n elif message == \"save\":\n kernel.saveBrain(\"bot_brain.brn\")\n else:\n bot_response = kernel.respond(message)\n if (bot_response == \"NULL\"):\n\n testa=mnbpy.clean_text(message)\n if(len(testa.split())>1):\n\n X_test=pd.Series(testa)\n y_prednb = mnb.predict(X_test)\n y_predlog = log.predict(X_test)\n\n if(y_prednb==y_predlog):\n csv_f = csv.reader(open('answers.csv',encoding='utf-8'))\n\n for row in csv_f:\n if(row[0]==str(y_prednb[0])):\n gt=row[1]\n print (row[1])\n\n else:\n gt=\"Please provide more information\"\n else:\n gt=\"Please provide more information\"\n\n return jsonify({'status':'OK','answer':'$'+gt})\n\n\n else:\n return jsonify({'status':'OK','answer':bot_response})\n\n\nif __name__ == \"__main__\":\n app.run(host='localhost', debug=True)\n","repo_name":"rutu14/chatbot","sub_path":"main-raw.py","file_name":"main-raw.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"32460576517","text":"from decorators import *\nclass Account:\n\n @number_checker\n def __init__(self, number : int, name : str, balance : int):\n self.__number = number\n self.__name = name\n self.__balance = balance\n print('Аккаунт успешно создан')\n bank.accounts.append(self)\n\n @staticmethod\n def account_exists(number) -> bool:\n return len(list(filter(lambda x: x.number == number, bank.accounts))) != 0\n\n @property\n def number(self):\n return self.__number\n\n @property\n def name(self):\n return self.__name\n\n @property\n def balance(self):\n return self.__balance\n\n @balance.setter\n def balance(self, value):\n self.__balance = value\n\n @deposit_validation\n def deposit(self,amount):\n self.__balance+=amount\n print('счет успешно пополнен')\n\n @withdraw_validation\n def withdraw(self,amount):\n self.__balance-=amount\n print('Снятие средств прошло успешно')\n\n def getbalance(self):\n print(self.__number,self.__name,self.__balance)\n\n\nclass Bank:\n\n def __init__(self):\n self.__accounts = []\n\n @property\n def accounts(self):\n return self.__accounts\n\n @accounts.setter\n def accounts(self, value):\n self.__accounts = value\n\n @transfer_validation\n def transfer(self, sender : Account, receiver: Account, amount : int):\n sender.balance -= amount\n receiver.balance += amount\n print ('Перевод выполнен успешно')\n\n #def robbery(self):\n #self.__accounts = list(map(lambda x: x.balance * 0, self.__accounts))\n #print('Все ваши деньги украдены хе хе')\n #Паша, помоги плиз, я хотела сделать эту функция по приколу,а по итогу оно не работает и\n #создает другой массив в у которого все атрибуты=0, не только баланс\n\n\nbank=Bank()\nGasin=Account(1,'Misha',1000)\nZhukov=Account(2,'Pasha',1000)\nFofanov=Account(3,'Sasha',1000)\nKobzev=Account(3,'Sasha',1000)\nKobzev=Account(4,'Sasha',1000)\nGordov=Account(5,'Sasha',-6)\nGordov=Account(5,'Sasha',1000)\n\n#Нормальные значения\nFofanov.getbalance()\nGasin.deposit(500)\nGasin.getbalance()\nbank.transfer(Kobzev,Zhukov,700)\nKobzev.getbalance()\nZhukov.getbalance()\n\n#ошибки\nFofanov.withdraw(5000)\nbank.transfer(Gordov,Gasin,-6)\nbank.transfer(Gordov,Gasin,10000)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"TuringClubMPEI/PythonCourse","sub_path":"ch02/Manzheeva/Home2.py","file_name":"Home2.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"25834245717","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\n\r\n\r\n# plot in the same figure 2 plots. One above and the other below. The upper one is the real data over time, the lower one is the fft output over frequency\r\ndef plot_fft(time, signal, fft_output, frequencies_x, file_name):\r\n fig, (ax1, ax2) = plt.subplots(2, 1,constrained_layout=True)\r\n #fig.tight_layout()\r\n ax1.plot(time, signal)\r\n ax1.set_xlabel('Time [us]')\r\n ax1.set_ylabel('Signal [arb.un]')\r\n ax2.set_xlim(0,15)\r\n ax2.plot(frequencies_x / 1e3, fft_output)\r\n ax2.set_yscale('log')\r\n ax2.set_ylabel('FFT [arb.un]')\r\n ax2.set_xlabel('Frequency [kHz]')\r\n #plt.savefig(f\"./plots/{file_name}.png\")\r\n plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n files_list = os.listdir(\"./rlc\")\r\n # remove the extension from the file name\r\n files_list = [file_name.split(\".\")[0] for file_name in files_list]\r\n # leave in files_list only the string that contains \"fft\"\r\n files_list = [file_name for file_name in files_list if \"fft\" in file_name or \"nomed\" in file_name]\r\n\r\n for file_name in files_list:\r\n time, signal = np.loadtxt(f'./rlc/{file_name}.txt', delimiter=' ', unpack=True)\r\n N = len(time)\r\n time = time * 1e-6\r\n\r\n # real data\r\n C = 0.22e-6 # F\r\n L = 0.5 # H\r\n omega = 1 / np.sqrt(L*C)\r\n print(f\"frequency = {omega / (2*np.pi)} Hz\")\r\n\r\n # calculate the sampling frequency\r\n fs = 1 / (np.mean(np.diff(time)) )\r\n dteff = np.mean(np.diff(time))\r\n f_max = 1 / (2 * dteff)\r\n print(f\"delta t while sampling data: {dteff} us\")\r\n print(f\"max frequency in fourier analysis {f_max}\")\r\n\r\n # perform fft real\r\n fft_output = abs(np.fft.rfft(signal))\r\n print(f\"how many fft data?: {len(fft_output)}\") # should be N/2 + 1 = 1025\r\n\r\n # calculate the frequency axis\r\n frequencies_x = np.linspace(0,f_max,len(fft_output))\r\n\r\n plot_fft(time, signal, fft_output, frequencies_x, file_name)\r\n","repo_name":"LucaPalumbo/four_2022","sub_path":"fft/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"8144975107","text":"from django.db import models\nfrom django.db.models.signals import post_delete\nfrom django.dispatch import receiver\n\n\n# Create your models here.\nclass Image(models.Model):\n file = models.ImageField(upload_to='images/', null=True)\n bgrHist = models.BinaryField(blank=True, null=True)\n hsvHist = models.BinaryField(blank=True, null=True)\n texture = models.BinaryField(blank=True, null=True)\n lbpHist = models.BinaryField(blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True, auto_now=False)\n updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)\n\n def __str__(self):\n return str(self.file)\n\n\n# delete associated image file when image model is removed\n@receiver(post_delete, sender=Image)\ndef image_post_delete_handler(sender, **kwargs):\n image = kwargs['instance']\n storage, path = image.file.storage, image.file.path\n storage.delete(path)\n\n\n# table to hold training set for machine learning algorithms\nclass Example(models.Model):\n file = models.ImageField(upload_to='images/training/', null=True)\n lbpHist = models.BinaryField(blank=True, null=True)\n label = models.CharField(max_length=45, blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True, auto_now=False)\n updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)\n\n def __str__(self):\n return str(self.file)\n\n\n# machine learning models\nclass Classifier(models.Model):\n model = models.BinaryField(blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True, auto_now=False)\n updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)\n","repo_name":"Topbantsman/cbir","sub_path":"cbir/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"38678366258","text":"import logging\r\nimport json\r\n\r\nimport falcon\r\n\r\nfrom subscriptionServer2.client import SubscriptionClient\r\n\r\n\r\nDEFAULT_PORT = 10794\r\nDEFAULT_SUBSCRIPTIONSERVER_URI = 'ws://localhost:9873'\r\n\r\nlog = logging.getLogger(__name__)\r\n\r\n\r\nclass URLtoSubscriptionServerBridge():\r\n def __init__(self, subscription_client):\r\n self.client = subscription_client\r\n\r\n def on_get(self, request, response):\r\n # Construct messages\r\n try:\r\n messages = json.load(request.bounded_stream)\r\n except json.decoder.JSONDecodeError:\r\n messages = {}\r\n if not isinstance(messages, (list, tuple)):\r\n messages = (messages, )\r\n deviceids = ','.join(request.path.strip('/').split('/'))\r\n if deviceids:\r\n request.params['deviceid'] = deviceids\r\n messages[0].update(request.params)\r\n log.info(messages)\r\n\r\n # Send messages\r\n if self.client.queue_send.empty(): # TODO: actually check if connected?\r\n self.client.send_message(*messages)\r\n response.status = falcon.HTTP_200\r\n response.media = {'status': 'ok'}\r\n else:\r\n response.status = falcon.HTTP_500\r\n response.media = {'status': 'socket connection issue'}\r\n\r\n #def on_post(self, request, response):\r\n # # TODO: POST request\r\n # response.status = falcon.HTTP_200\r\n\r\n\r\n# Setup App -------------------------------------------------------------------\r\n\r\ndef create_wsgi_app(subscriptionserver_uri=None, **kwargs):\r\n subscription_client = SubscriptionClient(subscriptionserver_uri or DEFAULT_SUBSCRIPTIONSERVER_URI)\r\n subscription_client.start_process()\r\n\r\n handler = URLtoSubscriptionServerBridge(subscription_client)\r\n\r\n app = falcon.API()\r\n app.add_sink(handler.on_get, prefix='/')\r\n #app.add_route('/', URLtoSubscriptionServerBridge(subscription_client))\r\n return app\r\n\r\n\r\n# Commandlin Args -------------------------------------------------------------\r\n\r\ndef get_args():\r\n import argparse\r\n\r\n parser = argparse.ArgumentParser(\r\n prog=__name__,\r\n description='''\r\n Provide a URL endpoint to send event triggers via a url to a running subscription_server.py\r\n\r\n curl -GET http://localhost:10794/front?func=text.html_bubble&html=test\r\n curl -XGET http://localhost/event/ -d '{\"deviceid\": \"main\", \"func\": \"text.html_bubble\", \"html\": \"

Test

test

\"}'\r\n curl -XGET http://localhost:9873/ -d '{\"function\": \"screen_size.set\", \"deviceid\": \"main\", \"top\":\"100px\", \"left\":\"100px\", \"width\": \"400px\", \"height\":\"300px\"}'\r\n\r\n\r\n ''',\r\n )\r\n\r\n parser.add_argument('subscriptionserver_uri', action='store', default=DEFAULT_SUBSCRIPTIONSERVER_URI, help='')\r\n\r\n parser.add_argument('--host', action='store', default='0.0.0.0', help='')\r\n parser.add_argument('--port', action='store', default=DEFAULT_PORT, type=int, help='')\r\n parser.add_argument('--log_level', type=int, help='log level', default=logging.INFO)\r\n\r\n kwargs = vars(parser.parse_args())\r\n return kwargs\r\n\r\n\r\ndef init_sigterm_handler():\r\n \"\"\"\r\n Docker Terminate\r\n https://lemanchet.fr/articles/gracefully-stop-python-docker-container.html\r\n \"\"\"\r\n import signal\r\n def handle_sigterm(*args):\r\n raise KeyboardInterrupt()\r\n signal.signal(signal.SIGTERM, handle_sigterm)\r\n\r\n\r\n\r\n# Main ------------------------------------------------------------------------\r\n\r\nif __name__ == '__main__':\r\n init_sigterm_handler()\r\n kwargs = get_args()\r\n logging.basicConfig(level=kwargs['log_level'])\r\n\r\n from wsgiref import simple_server\r\n log.info('falcon webserver {host}:{port}'.format(**kwargs))\r\n httpd = simple_server.make_server(kwargs['host'], kwargs['port'], create_wsgi_app(**kwargs))\r\n try:\r\n httpd.serve_forever()\r\n except KeyboardInterrupt:\r\n pass\r\n","repo_name":"superLimitBreak/multisocketServer","sub_path":"webBridge/webBridge.py","file_name":"webBridge.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"16413064181","text":"from turtle import Turtle\n\nPADDLE_WIDTH = 20\nPADDLE_HEIGHT = 100\nSTEP_DISTANCE = 20\n\n\nclass Paddle(Turtle):\n def __init__(self, xcor, ycor):\n super().__init__()\n self.shape(\"square\")\n self.resizemode(\"user\")\n self.penup()\n self.goto(xcor, ycor)\n self.setheading(90)\n self.color(\"white\")\n self.shapesize(stretch_wid=1, stretch_len=5)\n\n def move_up(self):\n self.forward(STEP_DISTANCE)\n\n def move_down(self):\n self.backward(STEP_DISTANCE)\n","repo_name":"zhd204/Python","sub_path":"day22_pong-game/paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"22971429359","text":"# import the necessary packages\nimport numpy as np\n\n# Malisiewicz et al.\n# Python port by Adrian Rosebrock\ndef non_max_suppression_fast(boxes, overlapThresh):\n # if there are no boxes, return an empty list\n if len(boxes) == 0:\n return []\n\n # if the bounding boxes integers, convert them to floats --\n # this is important since we'll be doing a bunch of divisions\n if boxes.dtype.kind == \"i\":\n boxes = boxes.astype(\"float\")\n\n # initialize the list of picked indexes \n pick = []\n\n # grab the coordinates of the bounding boxes\n x1 = boxes[:,0]\n y1 = boxes[:,1]\n x2 = boxes[:,2]\n y2 = boxes[:,3]\n scores = boxes[:,4]\n # compute the area of the bounding boxes and sort the bounding\n # boxes by the score/probability of the bounding box\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n idxs = np.argsort(scores)[::-1]\n\n # keep looping while some indexes still remain in the indexes\n # list\n while len(idxs) > 0:\n # grab the last index in the indexes list and add the\n # index value to the list of picked indexes\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n\n # find the largest (x, y) coordinates for the start of\n # the bounding box and the smallest (x, y) coordinates\n # for the end of the bounding box\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\n\n # compute the width and height of the bounding box\n w = np.maximum(0, xx2 - xx1 + 1)\n h = np.maximum(0, yy2 - yy1 + 1)\n\n # compute the ratio of overlap\n overlap = (w * h) / area[idxs[:last]]\n\n # delete all indexes from the index list that have\n idxs = np.delete(idxs, np.concatenate(([last],\n np.where(overlap > overlapThresh)[0])))\n\n # return only the bounding boxes that were picked using the\n # integer data type\n return boxes[pick].astype(\"int\")\n","repo_name":"techfort/pycv","sub_path":"chapter7/car_detector/non_maximum.py","file_name":"non_maximum.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":540,"dataset":"github-code","pt":"83"} +{"seq_id":"31615351616","text":"\"\"\"\nGiven a string with paranthesis return 0 if balanced or -1 for unbalanced paranthesis\n\nConstruct an array with 0 for balanced paranthesis or -1 for unbalanced part all non-paranthesis are 0's\ninput = ((abc)*d+(ab+ad)))\noutput = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1]\n\"\"\"\n\nOPEN_PARAN = '('\nCLOSED_PARAN = ')'\n\ndef check_balanced_paranthesis(str):\n chars = list(str)\n stack = []\n output = [0] * len(chars)\n\n for i, item in enumerate(chars):\n if item == OPEN_PARAN:\n stack.append(i)\n elif item == CLOSED_PARAN:\n if stack:\n stack.pop()\n else:\n output[i] = -1\n else:\n continue\n\n for idx in stack:\n output[idx] = -1\n\n print(output)\n\ncheck_balanced_paranthesis('((abc)*d+(ab+ad)))')\ncheck_balanced_paranthesis('(a+b))')\ncheck_balanced_paranthesis('((a+b)')\n\n","repo_name":"madhuri-majety/IK","sub_path":"11_Interview_Questions/Awake_balanced_paranthesis.py","file_name":"Awake_balanced_paranthesis.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"38206163659","text":"from __future__ import division\nimport numpy as np\nfrom .histogram import fullhistogram\nfrom . import _histogram\nfrom .internal import _verify_is_integer_type\n__all__ = [\n 'otsu',\n 'rc',\n 'soft_threshold',\n 'bernsen',\n 'gbernsen',\n ]\n\n\ndef otsu(img, ignore_zeros=False):\n \"\"\"\n T = otsu(img, ignore_zeros=False)\n\n Calculate a threshold according to the Otsu method.\n\n Example::\n\n import mahotas as mh\n import mahotas.demos\n\n im = mahotas.demos.nuclear_image()\n # im is stored as RGB, let's convert to single 2D format:\n im = im.max(2)\n\n #Now, we compute Otsu:\n t = mh.otsu(im)\n\n # finally, we use the value to form a binary image:\n bin = (im > t)\n\n See Wikipedia for details on methods:\n https://en.wikipedia.org/wiki/Otsu's_method\n\n Parameters\n ----------\n img : an image as a numpy array.\n This should be of an unsigned integer type.\n ignore_zeros : Boolean\n whether to ignore zero-valued pixels\n (default: False)\n\n Returns\n -------\n T : integer\n the threshold\n \"\"\"\n _verify_is_integer_type(img, 'otsu')\n hist = fullhistogram(img)\n hist = np.asanyarray(hist, dtype=np.double)\n if ignore_zeros:\n hist[0] = 0\n return _histogram.otsu(hist)\n\n\ndef rc(img, ignore_zeros=False):\n \"\"\"\n T = rc(img, ignore_zeros=False)\n\n Calculate a threshold according to the Riddler-Calvard method.\n\n Example::\n\n import mahotas as mh\n import mahotas.demos\n\n im = mahotas.demos.nuclear_image()\n # im is stored as RGB, let's convert to single 2D format:\n im = im.max(2)\n\n #Now, we compute a threshold:\n t = mh.rc(im)\n\n # finally, we use the value to form a binary image:\n bin = (im > t)\n\n Parameters\n ----------\n img : ndarray\n Image of any type\n ignore_zeros : boolean, optional\n Whether to ignore zero valued pixels (default: False)\n\n Returns\n -------\n T : float\n threshold\n \"\"\"\n hist = fullhistogram(img)\n if ignore_zeros:\n if hist[0] == img.size:\n return 0\n hist[0] = 0\n N = hist.size\n\n # Precompute most of what we need:\n first_moment = np.cumsum(np.arange(N) * hist)\n cumsum = np.cumsum(hist)\n\n r_first_moment = np.flipud(np.cumsum(np.flipud(np.arange(N) * hist)))\n r_cumsum = np.flipud(np.cumsum(np.flipud(hist)))\n\n maxt = N-1\n while hist[maxt] == 0:\n maxt -= 1\n\n res = maxt\n t = 0\n while t < min(maxt, res):\n if cumsum[t] and r_cumsum[t+1]:\n res = (first_moment[t]/cumsum[t] + r_first_moment[t+1]/r_cumsum[t+1])/2\n t += 1\n return res\n\ndef soft_threshold(f, tval):\n '''\n thresholded = soft_threshold(f, tval)\n\n Soft threshold function::\n\n ^\n | /\n | /\n | /\n | /\n | /\n - - - - - - - - - - - - - - - - - ->\n / |\n / |\n / |\n / |\n / |\n / |\n\n Parameters\n ----------\n f : ndarray\n tval : scalar\n\n Returns\n -------\n thresholded : ndarray\n '''\n\n f = f * (np.abs(f) > tval)\n f -= tval * (f > tval)\n f += tval * (f < -tval)\n return f\n\ndef bernsen(f, radius, contrast_threshold, gthresh=None):\n '''\n thresholded = bernsen(f, radius, contrast_threshold, gthresh={128})\n\n Bernsen local thresholding\n\n Parameters\n ----------\n f : ndarray\n input image\n radius : integer\n radius of circle (to consider \"local\")\n contrast_threshold : integer\n contrast threshold\n gthresh : numeric, optional\n global threshold to fall back in low contrast regions\n\n Returns\n -------\n thresholded : binary ndarray\n\n See Also\n --------\n gbernsen : function\n Generalised Bernsen thresholding\n '''\n from mahotas.morph import circle_se\n if gthresh is None:\n gthresh = 128\n return gbernsen(f, circle_se(radius), contrast_threshold, gthresh)\n\ndef gbernsen(f, se, contrast_threshold, gthresh):\n '''\n thresholded = gbernsen(f, se, contrast_threshold, gthresh)\n\n Generalised Bernsen local thresholding\n\n Parameters\n ----------\n f : ndarray\n input image\n se : boolean ndarray\n structuring element to use for \"locality\"\n contrast_threshold : integer\n contrast threshold\n gthresh : numeric, optional\n global threshold to fall back in low contrast regions\n\n Returns\n -------\n thresholded : binary ndarray\n\n See Also\n --------\n bernsen : function\n Bernsen thresholding with a circular region\n '''\n from mahotas.convolve import rank_filter\n fmax = rank_filter(f, se, se.sum()-1)\n fmin = rank_filter(f, se, 0)\n fptp = fmax - fmin\n fmean = fmax/2. + fmin/2. # Do not use (fmax + fmin) as that may overflow\n return np.choose(fptp < contrast_threshold, (fmean < gthresh, fmean > f))\n\n","repo_name":"luispedro/mahotas","sub_path":"mahotas/thresholding.py","file_name":"thresholding.py","file_ext":"py","file_size_in_byte":5238,"program_lang":"python","lang":"en","doc_type":"code","stars":814,"dataset":"github-code","pt":"83"} +{"seq_id":"74852909391","text":"'''\n1일 총 입장객이 100명이라고 할 때, 1일 전체 입장 요금을 구하는 프로그램\n단, 입장 고객의 나이는 난수를 이용한다.\n\n영유아 : 0-7세, 무료; 어린이 : 8-13세, 200원; 청소년 : 14-19세, 300원\n성인 : 20-64세, 500원; 어르신 : 65세 이상, 무료\n'''\n\nimport random\n\nvisitors = []\n\nfor n in range(100):\n visitors.append(random.randint(1, 100))\n\ngroup1, group2, group3, group4, group5 = 0,0,0,0,0\nfor age in visitors:\n\n if age >= 0 and age <= 7:\n group1 += 1\n elif age >= 8 and age <= 13:\n group2 += 1\n elif age >= 14 and age <= 19:\n group3 += 1\n elif age >= 20 and age <= 64:\n group4 += 1\n else:\n group5 += 1\n\ngroup1Price = group1 * 0\ngroup2Price = group2 * 200\ngroup3Price = group3 * 300\ngroup4Price = group4 * 500\ngroup5Price = group5 * 0\n\nprint('-' * 25)\nprint(f'영유아\\t: {group1}명\\t: {group1Price}원')\nprint(f'어린이\\t: {group2}명\\t: {group2Price}원')\nprint(f'청소년\\t: {group3}명\\t: {group3Price}원')\nprint(f'성인\\t: {group4}명\\t: {group4Price}원')\nprint(f'어르신\\t: {group5}명\\t: {group5Price}원')\n\nsum = group1Price + group2Price + group3Price + group4Price + group5Price\nsumFormat = format(sum, ',')\nprint('-' * 25)\nprint(f'1일 요금 총합계: {sumFormat}원')\nprint('-' * 25)\n\n\n","repo_name":"hhaemin/practice_python","sub_path":"자료구조/04_041.py","file_name":"04_041.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"22996099433","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 11 17:05:20 2018\n\n@author: mtmiec\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.ndimage\n\nfilename = 'phist.out'\nmodeno = 1\nstart = 40000\nend = 100000\n\ndata = np.genfromtxt(filename)\nt = data[start:end,0]\nre = data[start:end,2*modeno-1]\nim = data[start:end:,2*modeno]\nam = np.sqrt(re**2+im**2)\n\ndt = t[1] - t[0]\nN = t.size\nn2 = np.array(range(N))\nftre = np.fft.fft(im)\nomega = 2*np.pi*n2/dt/N\n\nplt.figure(1)\nplt.plot(t,re,t,im,t,am)\nplt.xlabel('$\\Omega_i t$')\nplt.legend(['Real','Imaginary','Amplitude'],loc=3)\nplt.show()\n\n#plot frequency spectrum\nplt.figure(2)\n\nplt.plot(2*np.pi*n2/dt/N,np.absolute(ftre[n2])**2)\nplt.yscale('log')\nplt.xlabel('$\\omega$')\nplt.show()","repo_name":"mattmiec/pic-diagnostics","sub_path":"satft.py","file_name":"satft.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"29351955954","text":"import cv2\nimport numpy as np\nimport os\n\n\ndef get_template_features(template):\n sift = cv2.xfeatures2d.SIFT_create()\n kp_template, desc_template = sift.detectAndCompute(template, None)\n index_params = dict(algorithm=0, trees=5)\n search_params = dict()\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n return flann, sift, desc_template, kp_template\n\n\ndef get_image_features(img, sift, desc_template, flann):\n kp_img, desc_img = sift.detectAndCompute(img, None)\n matches = flann.knnMatch(desc_template, desc_img, k=2)\n return matches, kp_img\n\n\ndef get_perspective(matches, kp_template, kp_image, image, template):\n good_points = []\n for m, n in matches:\n if m.distance < 0.6 * n.distance:\n good_points.append(m)\n source_pts = np.float32([kp_template[m.queryIdx].pt for m in good_points]).reshape(-1, 1, 2)\n dest_pts = np.float32([kp_image[m.trainIdx].pt for m in good_points]).reshape(-1, 1, 2)\n matrix, mask = cv2.findHomography(dest_pts, source_pts, cv2.RANSAC, 5.0)\n warped_image = cv2.warpPerspective(image, matrix, (template.shape[1], template.shape[0]))\n return warped_image\n\n\ndef get_template(path):\n template = cv2.imread(path, 0)\n return template\n\n\ndef get_image(path):\n images = []\n print(\"Importing Images...\")\n for items in os.listdir(path):\n newPath = path + '/' + items\n curImg = cv2.imread(newPath, 0)\n images.append(curImg)\n print(f\"{len(images)} Images imported.\")\n return images\n\n\nif __name__ == '__main__':\n images = []\n template = get_template('Resources/Homo_template.jpg')\n flann, sift, desc_template, kp_template = get_template_features(template)\n images = get_image('Resources')\n for i in images:\n matches, kp_img = get_image_features(i, sift, desc_template, flann)\n warped_image = get_perspective(matches, kp_template, kp_img, i, template)\n cv2.namedWindow(\"Original Image\", cv2.WINDOW_NORMAL)\n cv2.namedWindow(\"Warped Image\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"Original Image\", i)\n cv2.imshow(\"Warped Image\", warped_image)\n cv2.waitKey(0)\n","repo_name":"treeleafrnd/OCR_services","sub_path":"homographic_matching.py","file_name":"homographic_matching.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"11017674605","text":"import numpy as np\nfrom scipy.fftpack import rfft, irfft, fftfreq\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\n# Session Seven / Spectrograms and Gabor Transforms\n\nT = 10 # Time domain\nn = 2048 # Sampling\n\nt = np.linspace(0, T, n+1)\ntime = t[:n]\n#t = t2[:n]\n# Actual frequency component Cos0T , Cos1T, Cos2T ...\n#freq = [(2 * np.pi / T) * ii for jj in (np.arange(0,n/2), np.arange(-n/2, 0)) for ii in jj]\nsignal = (3*np.sin(2*time) + 0.5*np.tanh(0.5*(time-3)) + 0.2*np.exp(-(time-4)**2) + 1.5*np.sin(5*time) \\\n + 4*np.cos(3*(time-6)**2)) / 10 + (time/20)**3\nfreq = np.fft.fftfreq(signal.size, d=time[1]-time[0])\nfourier = np.fft.fft(signal) # Heisenberg Uncertainty Principle is associated with fft\nfreq_shift = np.fft.fftshift(freq)\nplt.figure(1)\nplt.subplot(211)\nplt.plot(time, signal, color='lightblue', linewidth=1)\n\nplt.subplot(212)\nplt.plot(freq_shift, np.fft.fftshift(np.abs(fourier)), color='blue', linewidth=1)\nplt.show()\n\n# Gabor Transform\nwidth = 0.3\nslide = np.arange(0, 10, 0.1)\nspec = np.zeros(shape=(len(slide),len(time)))\nplt.figure(2)\nfor i in range(len(slide)):\n filter = np.exp(-width*(time-slide[i])**2)\n signal_filter = filter * signal\n fourier_filterr = np.fft.fft(signal_filter)\n\n plt.subplot(311)\n plt.plot(time, signal, color='lightblue', linewidth=1)\n plt.plot(time, filter, color='lightgreen', linewidth=1)\n\n plt.subplot(312)\n plt.plot(time, signal_filter, color='blue', linewidth=1)\n\n plt.subplot(313)\n plt.plot(freq_shift, np.fft.fftshift(np.abs(fourier_filterr)), color='green', linewidth=1)\n\n spec[i, :] = np.fft.fftshift(np.abs(fourier_filterr)).reshape(-1)\n plt.xlim(-T , T )\n plt.pause(0.005)\n plt.clf()\n\n# plotting the spectrogram\n\nslide_mesh, freq_mesh = np.meshgrid(slide, freq_shift)\n\nfig, ax = plt.subplots()\nax.set_yscale('symlog')\nax.pcolormesh(slide_mesh, freq_mesh, spec.transpose())\nplt.xlim([0,10])\nplt.ylim([-60,60])\n#ٍplt.zlim([-10,10])\nplt.show()","repo_name":"Mohamadnet/Time-Frequency-Analysis","sub_path":"Multi-Resolution-Analysis.py","file_name":"Multi-Resolution-Analysis.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"34072593984","text":"class Solution:\n def differenceOfSum(self, nums: List[int]) -> int:\n def digit_sum(n):\n x=[int(i) for i in str(n)]\n return sum(x)\n ele_sm=0\n d_sm=0\n for i in range(len(nums)):\n ele_sm+=nums[i]\n d_sm+=digit_sum(nums[i])\n return abs(ele_sm-d_sm)\n \n ","repo_name":"chandralok-31/leetcode","sub_path":"2535-difference-between-element-sum-and-digit-sum-of-an-array/2535-difference-between-element-sum-and-digit-sum-of-an-array.py","file_name":"2535-difference-between-element-sum-and-digit-sum-of-an-array.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"16761236178","text":"import cv2\r\nimport numpy as np\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n _, frame = cap.read()\r\n #_is function which is return from the function and we dont care about it\r\n\r\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n cv2.imshow('frame', frame)\r\n\r\n lower_or = np.array([0,30,0])\r\n upper_or = np.array([255,255,255])\r\n\r\n '''\r\n we can covert single color into hsv color using\r\n \r\n dark_red = np.uint8([[[12,22,121]]])\r\n dark_red = cv2.cvtColor(dark_red,cv2.COLOR_BGR2HSV)\r\n '''\r\n\r\n mask = cv2.inRange(hsv, lower_or, upper_or)\r\n cv2.imshow('mask', mask)\r\n \r\n #Mask will be with in the mask frame will be with in the frame\r\n res = cv2.bitwise_and(frame, frame, mask = mask) \r\n cv2.imshow('result', res)\r\n \r\n k = cv2.waitKey(5) & 0xFF\r\n\r\n if k == 27:\r\n break\r\n\r\ncv2.destroyAllWindows()\r\ncap.release()\r\n","repo_name":"varul29/OpenCV","sub_path":"Image_Color_Filtering.py","file_name":"Image_Color_Filtering.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"83"} +{"seq_id":"22037805766","text":"# This code is part of Ansible, but is an independent component.\n# This particular file snippet, and this file snippet only, is BSD licensed.\n# Modules you write using this snippet, which is embedded dynamically by Ansible\n# still belong to the author of the module, and may assign their own license\n# to the complete work.\n#\n# (c) 2020 Red Hat Inc.\n#\n# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)\n# SPDX-License-Identifier: BSD-2-Clause\n\n\"\"\" A shim class for the NetworkTemplate\nthis was done in case there is a need to\nmodify the resource module parser class\nor extend it a split it from the cli parsers.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\n\n__metaclass__ = type\n\nfrom ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.network_template import (\n NetworkTemplate,\n)\n\n\nclass CliParserTemplate(NetworkTemplate):\n \"\"\"The parser template base class\"\"\"\n\n def __init__(self, lines=None):\n super(CliParserTemplate, self).__init__(lines=lines, tmplt=self)\n","repo_name":"ansible-collections/ansible.netcommon","sub_path":"plugins/module_utils/cli_parser/cli_parsertemplate.py","file_name":"cli_parsertemplate.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":124,"dataset":"github-code","pt":"83"} +{"seq_id":"73995522191","text":"'''\n [CS 180] Team Waveform's Sound Visualizer\n Authors: Dylan Moon, Richie R. CastleBomber, Luke Lewis, Joey Barcia\n'''\n\nfrom samplebase import SampleBase\n#from team_show import TeamShow\nfrom team_show import *\nfrom sound_manager import *\n\nimport pyaudio\nimport re\nimport os\nimport time\n\nfrom struct import unpack\nimport numpy as np\n\n'''\n 32x32\n'''\nclass SoundShow(SoundManager):\n def __init__(self, *args, **kwargs):\n super(SoundShow, self).__init__(*args, **kwargs)\n\n def run(self):\n self.soundVisualizer()\n\n\n def soundVisualizer(self):\n canvas = self.matrix.CreateFrameCanvas()\n while True:\n data = stream.read(chunk)\n self.usleep(5000)\n height = calculate_levels(data, chunk, sample_rate)\n i=0\n for x in range(1,31,3):\n for y in range(0,32):\n if(y < height[i]):\n canvas.SetPixel( x, y,red(y),green(y),255)\n canvas.SetPixel(x+1,y,red(y),green(y),255)\n canvas.SetPixel(x+2,y,red(y),green(y),255)\n else:\n canvas.SetPixel( x, y,0,0,0)\n canvas.SetPixel(x+1,y,0,0,0)\n canvas.SetPixel(x+2,y,0,0,0)\n i+=1\n canvas = self.matrix.SwapOnVSync(canvas)\n","repo_name":"CastleBomber/Fire-vs-Bombs","sub_path":"src/sound_show.py","file_name":"sound_show.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"902432564","text":"''' Read Simon Fernbachs HEPMC directories.\nBoring but must be done.\n'''\n\nhepmc_directory = \"/afs/hephy.at/data/rschoefbeck01/TTXPheno/HEPMC\"\n\n# RootTools\nfrom RootTools.core.standard import *\n\n# Standard imports\nimport os\nimport pickle\n\n# Logging\nimport logging\nlogger = logging.getLogger(__name__)\n\n# Logging\nif __name__ == \"__main__\":\n import TTXPheno.Tools.logger as logger\n logger = logger.get_logger('DEBUG')\n import RootTools.core.logger as logger_rt\n logger_rt = logger_rt.get_logger('DEBUG')\n\nclass HEPMCData(object):\n\n processes = [\"GH\", \"HG\", \"HH\"]\n\n def __init__ ( self, name, hepmc_directory, sub_directory, pdfs, root_directory = None, isSplit = False):\n self.name = name\n self.pdfs = pdfs\n # a .hepmc single file or, if I split it up, a directory of the same name\n # Add PP:\n self.samples_dict = { 'PP':\\\n HEPMCSample.fromFiles( name+\"_PP\", os.path.join( hepmc_directory, sub_directory, 'PP.hepmc') ) if not isSplit else HEPMCSample.fromDirectory( name+\"_PP\", os.path.join( hepmc_directory, sub_directory, 'PP') ) }\n # Add root file for PP\n if root_directory is not None:\n self.root_samples_dict = {'PP': Sample.fromDirectory( name+\"_PP\", os.path.join( root_directory, name+\"_PP\" ) )}\n # Add the variations \n for pdf in self.pdfs:\n for process in HEPMCData.processes:\n self.samples_dict[pdf+'_'+process] = HEPMCSample.fromDirectory( name+'_'+pdf+'_'+process, os.path.join( hepmc_directory, sub_directory, '%s_%s'%(pdf, process)) )\n # Add the root files for the variations\n if root_directory is not None:\n for process in HEPMCData.processes:\n self.root_samples_dict[pdf+'_'+process] = Sample.fromDirectory( name+'_'+pdf+'_'+process, os.path.join( root_directory, name+'_%s_%s'%(pdf, process)) )\n\n # Read nEvents, xsec but we rather count ourselves\n _, xsecs = HEPMCData.read_crosssection( os.path.join( hepmc_directory, sub_directory, '%s_crosssections.txt'%pdf) )\n if xsecs is not None:\n if hasattr( self.samples_dict['PP'], \"xsec\"):\n if xsecs[0]!=self.samples_dict['PP'].xsec:\n logger.waring( \"Inconsistent PP cross sections! file: %s\", os.path.join( hepmc_directory, sub_directory, '1d0_%s_crosssections.txt'%pdf) )\n\n self.samples_dict['PP'].xsec = xsecs[0]\n self.samples_dict[pdf+\"_GH\"].xsec = xsecs[1]\n self.samples_dict[pdf+\"_HG\"].xsec = xsecs[2]\n self.samples_dict[pdf+\"_HH\"].xsec = xsecs[3]\n self.samples_dict['PP'].nEvents = pickle.load(file( os.path.join( hepmc_directory, sub_directory, 'PP.pkl') ))\n self.samples_dict[pdf+\"_GH\"].nEvents = pickle.load(file( os.path.join( hepmc_directory, sub_directory, '%s_GH.pkl'%pdf) )) \n self.samples_dict[pdf+\"_HG\"].nEvents = pickle.load(file( os.path.join( hepmc_directory, sub_directory, '%s_HG.pkl'%pdf) )) \n self.samples_dict[pdf+\"_HH\"].nEvents = pickle.load(file( os.path.join( hepmc_directory, sub_directory, '%s_HH.pkl'%pdf) )) \n\n def __getitem__( self, key ):\n return self.samples_dict[key]\n\n @staticmethod\n def read_crosssection( filename ):\n\n nEvents = None\n xsecs = None\n with open(filename) as fp:\n for i, line in enumerate(fp):\n if i == 1: #Simon writes the x-sec in the 2nd line\n line = line.rstrip().lstrip()\n vals = map( float, line.split() )\n nEvents, xsecs = vals[0], vals[1:]\n\n return nEvents, xsecs \n\n @property\n def samples( self ):\n return self.samples_dict.values() \n\n @property\n def files( self ):\n return sum( [s.files for s in self.samples], [] ) \n\n @property\n def root_samples( self ):\n return self.root_samples_dict.values() \n\n @property\n def root_files( self ):\n return sum( [s.files for s in self.root_samples], [] ) \n \nhepmc_directory = \"/afs/hephy.at/data/cms06/TTXPheno/HEPMC/12_05/\"\nroot_directory = \"/afs/hephy.at/data/rschoefbeck01/TTXPheno/skims/gen/RunII_v01/19_04/\"\n#bbar = HEPMCData( \"bbbar\", os.path.join( hepmc_directory, \"C89_BBBAR\" ) )\n#ttbar = HEPMCData( \"ttbar\", os.path.join( hepmc_directory, \"C89_TTBAR\" ), isSplit = True, root_directory = root_directory)\n\n\nttbarZ_fr_C6_woMT = HEPMCData( \"ttbarZ_fr_C6_woMT\",\n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBARZ/full_range/C6/without_massterm/HEPMC\", \n pdfs = [\"1d0\", \"10d0\", \"100d0\", \"0d1\", \"0d01\"], \n isSplit = True, \n root_directory = root_directory, \n )\nttbarZ_fr_C6_wMT = HEPMCData( \"ttbarZ_fr_C6_wMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBARZ/full_range/C6/with_massterm/HEPMC\", \n pdfs = [\"1d0\", \"10d0\", \"100d0\", \"0d1\", \"0d01\"], \n isSplit = True, \n root_directory = root_directory, \n )\nttbarZ_lr_C6_woMT = HEPMCData( \"ttbarZ_lr_C6_woMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBARZ/limited_range/C6/without_massterm/HEPMC\", \n pdfs = [\"10d0\", \"1d0\", \"3d25\", \"5d5\", \"7d75\"], \n isSplit = True, \n root_directory = root_directory, \n )\nttbarZ_lr_C6_wMT = HEPMCData( \"ttbarZ_lr_C6_wMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBARZ/limited_range/C6/with_massterm/HEPMC\", \n pdfs = [\"10d0\", \"1d0\", \"3d25\", \"5d5\", \"7d75\"], \n isSplit = True, \n root_directory = root_directory, \n )\n\nttbar_fr_C6_woMT = HEPMCData( \"ttbar_fr_C6_woMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBAR/full_range/C6/without_massterm/HEPMC\", \n pdfs = [\"1d0\", \"10d0\", \"100d0\", \"0d1\", \"0d01\"], \n isSplit = True, \n root_directory = root_directory, \n )\nttbar_fr_C6_wMT = HEPMCData( \"ttbar_fr_C6_wMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBAR/full_range/C6/with_massterm/HEPMC\", \n pdfs = [\"1d0\", \"10d0\", \"100d0\", \"0d1\", \"0d01\"], \n isSplit = True, \n root_directory = root_directory, \n )\nttbar_lr_C6_woMT = HEPMCData( \"ttbar_lr_C6_woMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBAR/limited_range/C6/without_massterm/HEPMC\", \n pdfs = [\"10d0\", \"1d0\", \"3d25\", \"5d5\", \"7d75\"], \n isSplit = True, \n root_directory = root_directory, \n )\nttbar_lr_C6_wMT = HEPMCData( \"ttbar_lr_C6_wMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBAR/limited_range/C6/with_massterm/HEPMC\", \n pdfs = [\"10d0\", \"1d0\", \"3d25\", \"5d5\", \"7d75\"], \n isSplit = True, \n root_directory = root_directory, \n )\n\nroot_directory = \"/afs/hephy.at/data/rschoefbeck01/TTXPheno/skims/gen/RunII_v02/19_04/\"\nttbar_fr_C6_wMT_v02 = HEPMCData( \"ttbar_fr_C6_wMT\", \n hepmc_directory = hepmc_directory, \n sub_directory = \"DATA_TTBAR/full_range/C6/with_massterm/HEPMC\", \n pdfs = [\"1d0\", \"10d0\", \"100d0\", \"0d1\", \"0d01\"], \n isSplit = True, \n root_directory = root_directory, \n )\n","repo_name":"TTXPheno/TTXPheno","sub_path":"samples/python/hepmc_samples_19_04.py","file_name":"hepmc_samples_19_04.py","file_ext":"py","file_size_in_byte":8802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"22101004533","text":"#!/usr/bin/env python3\n\nimport cv2\nimport numpy as np\nfrom time import sleep\nimport math\nimport ARLO.robot\nfrom time import perf_counter\n# from goDist import go\n\narlo = ARLO.robot.Robot()\n\nleftSpeed = math.floor(64 * 0.97)\nrightSpeed = 64\ndegSec = 0.005\n\ndef picPos():\n markerLength = 0.145\n cameraMatrix =np.array([[506.94,0,640/2],\n [0,506.94,480/2],\n [0,0,1],])\n distCoeffs = 0\n\n#distCoeffs[, rvecs[, tvecs[, _objPoints]]]\n\n cap = cv2.VideoCapture(0) # video capture source camera (Here webcam of laptop)\n ret,frame = cap.read() # return a single frame in variable `frame`\n\n#Grabbing dictionary\n arucoDict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_250)\n arucoParams = cv2.aruco.DetectorParameters_create()\n corners, ids, rejected = cv2.aruco.detectMarkers(frame, arucoDict, parameters=arucoParams)\n tvec = []\n if (ids is not None):\n rvec, tvec, markerPoints = cv2.aruco.estimatePoseSingleMarkers(corners, markerLength, cameraMatrix, distCoeffs)\n return tvec\n\n\n# få sider\ndef getAng():\n tvec = picPos()\n if (tvec == []):\n return (45, 10000)\n a = tvec[0][0][0]\n b = tvec[0][0][2]\n dist = math.sqrt(a**2+b**2)\n print(\"a = \", a, \"b = \", b, \"dist = \", dist)\n print(\"ang with minus = \", math.degrees(math.asin(a/dist)), \"ang -a = \", math.degrees(math.asin(-a/dist)))\n return (round(math.degrees(math.asin(a/dist)), 5), dist)\n\n# turn\ndef turn(deg):\n global rightSpeed\n global LeftSpeed\n global degSec\n isRight = deg > 0\n print(\"isRight\", isRight, \"Degrees to turn \", deg)\n print(\"Turning to box\")\n if (not isRight):\n print(\"Advusting to left deg\")\n deg = deg * (-1)\n print(arlo.go_diff(leftSpeed, rightSpeed, 0, 1))\n else:\n print(arlo.go_diff(leftSpeed, rightSpeed, 1, 0))\n sleep(round(deg * degSec, 5))\n print(arlo.stop())\n print(\"amount of degrees to go\", deg * degSec)\n\n\n\nsafeDist = 300\nsafeDistSide = 150\n\nsecMeter = 2.55\n\nstopDist = 400\nstopDistSide = 200\n\n\ndef go():\n emStop = False\n sensFront = arlo.read_front_ping_sensor()\n picDist = getAng()[1]*1000\n sensLeft = arlo.read_left_ping_sensor()\n sensRight = arlo.read_right_ping_sensor()\n distTime = (((min(sensFront, picDist) - stopDist)/1000)*0.66)*secMeter\n while (distTime > 0.1 and (not emStop)):\n print(\"time to go\", distTime)\n start = perf_counter()\n t = start\n arlo.go_diff(leftSpeed, rightSpeed, 1, 1)\n while ((t - start) < distTime):\n sensFront = arlo.read_front_ping_sensor()\n sensLeft = arlo.read_left_ping_sensor()\n sensRight = arlo.read_right_ping_sensor()\n if (sensFront < safeDist or\n sensRight < safeDistSide or\n sensLeft < safeDistSide):\n print(\"Emercency stop!!! sensors :\\nR \", sensRight,\n \",\\n L \", sensLeft,\n \",\\n F \", sensFront,\n \"\\n time traveled = \", t)\n emStop = True\n break\n t = perf_counter()\n arlo.stop()\n if not emStop:\n turn(getAng()[0])\n sensFront = arlo.read_front_ping_sensor()\n picDist = getAng()[1]*1000\n sensLeft = arlo.read_left_ping_sensor()\n sensRight = arlo.read_right_ping_sensor()\n distTime = (((min(sensFront, picDist) - stopDist)/1000)*(2/3))*secMeter\n return\n\n# def go():\n# sensFront = arlo.read_front_ping_sensor()\n# sensLeft = arlo.read_left_ping_sensor()\n# sensRight = arlo.read_right_ping_sensor()\n# distTime = (((sensFront - stopDist)/1000)*0.66)*secMeter\n# while (distTime > 0.1):\n# arlo.go_diff(leftSpeed, rightSpeed, 1, 1)\n# sleep(distTime)\n# arlo.stop()\n# sensFront = arlo.read_front_ping_sensor()\n# sensLeft = arlo.read_left_ping_sensor()\n# sensRight = arlo.read_right_ping_sensor()\n# distTime = (((sensFront - stopDist)/1000)*(2/3))*secMeter\n# turn(getAng())\n# return\n\n\n\nprint(getAng()[0])\nwhile (picPos() == []):\n turn(getAng()[0])\nturn(getAng()[0])\ngo()\n","repo_name":"jonathanclausen/REX","sub_path":"goToBox.py","file_name":"goToBox.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"14336653024","text":"from pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\n\n'''\nBasic test for Spark Stream to be used with a Tweet Tester, to see if we can parse the twitter stream just like we did with the netcat example.\nConsumes the tweets sampled by the Tweet Tester app.\n\nOn Terminal 1 run,\n$ TweetTester4-BasicStreamingTweepy.py\n\nOn Terminal 2 run,\n$ SparkTester4-BasicStreamingTweepy.py\n\nas the tweet tester streams tweet text into the spark streaming app, we should see some counts\n\n-------------------------------------------\nTime: 2017-11-24 14:55:33\n-------------------------------------------\n('https://t.co/UsLEjlLRNFRT', 1)\n('Drop', 1)\n('is', 3)\n('K-pop', 1)\n('group', 1)\n('#1', 1)\n('latest', 1)\n('#Portsmouth,', 1)\n('click', 1)\n('SAP', 1)\n...\n\n-------------------------------------------\nTime: 2017-11-24 15:02:12\n-------------------------------------------\n('#NotAlınBunuRT', 1)\n('@ms_hudgins:', 1)\n('Ryan', 1)\n('was', 3)\n('trying', 1)\n('trooper,', 1)\n('he', 1)\n('this', 4)\n('lady’s', 1)\n('yard', 1)\n...\n\nSee \n* http://www.awesomestats.in/spark-twitter-stream/\n* https://spark.apache.org/docs/latest/streaming-programming-guide.html\n'''\n\nmy_port = 5555\nmy_host = \"spark-2-1\"\n\n# Create a local StreamingContext with two working thread and batch interval of 1 second\nsc = SparkContext(\"local[2]\", \"NetworkWordCount\")\nssc = StreamingContext(sc, 1)\n\n# Create a DStream that will connect to hostname:port, like localhost:9999\nlines = ssc.socketTextStream(my_host, my_port)\n\n# Split each line into words\nwords = lines.flatMap(lambda line: line.split(\" \"))\n\n# Count each word in each batch\npairs = words.map(lambda word: (word, 1))\nwordCounts = pairs.reduceByKey(lambda x, y: x + y)\n\n# Print the first ten elements of each RDD generated in this DStream to the console\nwordCounts.pprint()\n\nssc.start() # Start the computation\nssc.awaitTermination() # Wait for the computation to terminate\n","repo_name":"ucbiyyq/ucbiyyq-w251","sub_path":"w251_hw09/hw9_py/SparkTester4-BasicStreamingTweepy.py","file_name":"SparkTester4-BasicStreamingTweepy.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"42564679198","text":"from datetime import datetime\n\nfrom building.models import Building\nfrom event.models import SourceSystem\nfrom plan.models import Plan, PlanEvent, PlanRead, PlanWork\nfrom share.services import get_one as get_plan\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlmodel import col, select\nfrom worker.tasks import predict\n\n\nasync def create(\n street: str, type_fund_id: int, sourcesystem_id: int, date_start: str, date_end: str, session: AsyncSession\n) -> PlanRead:\n plan = Plan(\n name=f\"Планировние от {datetime.now()}\",\n )\n session.add(plan)\n await session.commit()\n await session.refresh(plan)\n predict.delay(\n id=plan.id,\n street=street,\n source_id=sourcesystem_id,\n type_fund_id=type_fund_id,\n date_start=date_start,\n date_end=date_end,\n )\n\n return PlanRead(**(plan.dict()))\n\n\nasync def get_file(id: int, session: AsyncSession):\n import io\n\n import pandas as pd\n\n statement = select(PlanWork).where(PlanWork.plan_id == id)\n result = await session.execute(statement)\n plan_works = result.scalars().all()\n plan_works = [plan_work.dict() for plan_work in plan_works]\n\n statement = select(PlanEvent).where(PlanEvent.plan_id == id)\n result = await session.execute(statement)\n plan_events = result.scalars().all()\n plan_events = [plan_event.dict() for plan_event in plan_events]\n\n df_works = pd.DataFrame.from_records(plan_works)\n df_events = pd.DataFrame.from_records(plan_events)\n in_memory_fp = io.BytesIO()\n with pd.ExcelWriter(\n in_memory_fp,\n ) as writer:\n df_works.to_excel(writer, index=False, sheet_name=\"Works\")\n df_events.to_excel(writer, index=False, sheet_name=\"Events\")\n in_memory_fp.seek(0, 0)\n return in_memory_fp\n","repo_name":"progressionnetwork/comexp","sub_path":"apps/api/plan/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"30604016613","text":"from datetime import date\nfrom django import forms\nfrom django.forms.widgets import SelectDateWidget\n\nfrom .models import CalcRequest, Order\n\n\nclass CalcRequestForm(forms.ModelForm):\n class Meta:\n model = CalcRequest\n fields = (\"email\",)\n widgets = {\n \"email\": forms.EmailInput(\n attrs={\n \"class\": (\n \"form-control border-8 mb-4 py-3 px-5 border-0 fs_24 \"\n \"SelfStorage__bg_lightgrey\"\n ),\n \"placeholder\": \"Укажите ваш e-mail\",\n }\n )\n }\n\n\nclass OrderForm(forms.ModelForm):\n lease_start = forms.DateField(\n label=\"Начальная дата\", widget=SelectDateWidget(), initial=date.today\n )\n term = forms.IntegerField(label=\"Срок аренды, мес\")\n\n class Meta:\n model = Order\n fields = (\"id\",)\n\n\nclass ProlongationForm(forms.ModelForm):\n term = forms.IntegerField(label=\"Продлить на срок, мес\")\n\n class Meta:\n model = Order\n fields = (\"id\",)\n","repo_name":"LuFent/SelfStorage","sub_path":"boxes/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"1108594159","text":"\n\"\"\" Yapay Sinir Ağları örnek 2 \"\"\"\n\nfrom numpy import exp, array, random, dot\n\negitim_girisler = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])\negitim_cikislar = array([[0, 1, 1, 0]]).T\n\nrandom.seed(1)\n\nagirliklar = 2 * random.random((3, 1)) - 1\n\nfor iterasyon in range(10000):\n cikis = 1 / (1 + exp(-(dot(egitim_girisler, agirliklar))))\n agirliklar += dot(egitim_girisler.T, (egitim_cikislar - cikis) * cikis * (1 - cikis))\n\nprint(1 / (1 + exp(-(dot(array([1, 0, 0]), agirliklar)))))\n\n# ------------- son -------------","repo_name":"AhmetFurkanDEMIR/Python-Workouts","sub_path":"Artificial-Neural-Networks-master/ysa2.py","file_name":"ysa2.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"tr","doc_type":"code","stars":42,"dataset":"github-code","pt":"83"} +{"seq_id":"24578927712","text":"class Base():\n \n def __init__(self, params, exceptions = []):\n super().__init__()\n self.__store__(params, exceptions)\n\n def __store__(self, params, exceptions = []):\n exceptions += ['self', '__class__']\n self.__params = []\n for key, value in params.items():\n if key not in exceptions:\n setattr(self, key, value)\n self.__params.append(key)\n \n self.__name__ = self.__class__.__name__\n\n def __repr__(self):\n params = {key : getattr(self, key) for key in self.__params}\n params = [f'{key}={value}' for key, value in params.items()]\n return f'{self.__name__}({\", \".join(params)})'\n","repo_name":"jordan-wei-taylor/imagined-goals","sub_path":"src/rlig/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"32036613775","text":"from sympy import *\nfrom sympy.core.sympify import SympifyError\n\ndef calculate_sum(expr, n_max):\n n = Symbol('n')\n sum = summation(expr, (n, 1, n_max))\n return sum\n \nif __name__ == '__main__':\n expr = input('Enter expression : ')\n n_max = input('Number : ')\n try:\n expr = sympify(expr)\n n_max = int(n_max)\n except SympifyError:\n print('Invalid input')\n else:\n sum = calculate_sum(expr, n_max)\n pprint(sum)\n","repo_name":"yutakahashi114/python_lesson","sub_path":"src/math/04/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"12427541193","text":"from __future__ import annotations\n\nfrom collections.abc import Callable\nimport dataclasses\nfrom typing import Protocol\n\nimport chex\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n\nArray = jax.Array\nScheduleFn = Callable[[chex.Numeric], chex.Numeric]\n\nMIN_DIFFUION_TIME = 0.0\nMAX_DIFFUION_TIME = 1.0\n\n\n@dataclasses.dataclass(frozen=True)\nclass InvertibleSchedule:\n \"\"\"An invertible schedule.\n\n The schedule consists of a forward function that maps diffusion times to\n noise/scale/logsnr values, and an inverse that maps noise/scale/logsnr\n values back to the corresponding diffusion times, such that\n t = inverse(forward(t)). These functions should be monotonic wrt their input\n argument.\n\n Attributes:\n forward: A monotonic schedule function that maps diffusion times (scalar or\n array) to the noise/scale/logsnr values.\n inverse: The inverse schedule that maps scheduled values (scalar or array)\n back to the corresponding diffusion times.\n \"\"\"\n\n forward: ScheduleFn\n inverse: ScheduleFn\n\n def __call__(self, t: chex.Numeric) -> chex.Numeric:\n return self.forward(t)\n\n\ndef sigma2logsnr(sigma: InvertibleSchedule) -> InvertibleSchedule:\n \"\"\"Converts a sigma schedule to a logsnr schedule.\"\"\"\n forward = lambda t: -2 * jnp.log(sigma(t))\n inverse = lambda logsnr: sigma.inverse(jnp.exp(-logsnr / 2))\n return InvertibleSchedule(forward, inverse)\n\n\ndef logsnr2sigma(logsnr: InvertibleSchedule) -> InvertibleSchedule:\n \"\"\"Converts a logsnr schedule to a sigma schedule.\"\"\"\n forward = lambda t: jnp.exp(-logsnr(t) / 2)\n inverse = lambda sigma: logsnr.inverse(-2 * jnp.log(sigma))\n return InvertibleSchedule(forward, inverse)\n\n\n@dataclasses.dataclass(frozen=True)\nclass Diffusion:\n \"\"\"Diffusion scheme.\n\n Fully parametrizes the Gaussian perturbation kernel:\n\n p(x_t|x_0) = N(x_t; s_t * x_0, s_t * σ_t * I)\n\n where x_0 and x_t are original and noised samples. s_t and σ_t are the scale\n and noise schedules. t ∈ [0, 1]. I denotes the identity matrix. This\n particular parametrization follows Karras et al.\n (https://arxiv.org/abs/2206.00364).\n\n Attributes:\n scale: The scale schedule (as a function of t).\n sigma: The noise schedule (as monotonically increasing function of t).\n logsnr: The log signal-to-noise (LogSNR) schedule equivalent to the sigma\n schedule.\n sigma_max: The maximum noise level of the scheme.\n \"\"\"\n\n scale: ScheduleFn\n sigma: InvertibleSchedule\n\n @property\n def logsnr(self) -> InvertibleSchedule:\n return logsnr2sigma(self.sigma)\n\n @property\n def sigma_max(self) -> chex.Numeric:\n return self.sigma(MAX_DIFFUION_TIME)\n\n @classmethod\n def create_variance_preserving(\n cls, sigma: InvertibleSchedule, data_std: float = 1.0\n ) -> Diffusion:\n \"\"\"Creates a variance preserving diffusion scheme.\n\n Derive the scale schedule s_t from the noise schedule σ_t such that\n s_t^2 * (σ_d^2 + σ_t^2) (where σ_d denotes data standard deviation) remains\n constant (at σ_d^2) for all t. See Song et al.\n (https://arxiv.org/abs/2011.13456) for reference.\n\n Args:\n sigma: The sigma (noise) schedule.\n data_std: The standard deviation (scalar) of the data.\n\n Returns:\n A variance preserving diffusion scheme.\n \"\"\"\n var = jnp.square(data_std)\n scale = lambda t: jnp.sqrt(var / (var + jnp.square(sigma(t))))\n return cls(scale=scale, sigma=sigma)\n\n @classmethod\n def create_variance_exploding(\n cls, sigma: InvertibleSchedule, data_std: float = 1.0\n ) -> Diffusion:\n \"\"\"Creates a variance exploding diffusion scheme.\n\n Scale s_t is kept constant at 1. The noise schedule is scaled by the\n data standard deviation such that the amount of noise added is proportional\n to the data variation. See Song et al.\n (https://arxiv.org/abs/2011.13456) for reference.\n\n Args:\n sigma: The sigma (noise) schedule.\n data_std: The standard deviation (scalar) of the data.\n\n Returns:\n A variance exploding diffusion scheme.\n \"\"\"\n scaled_forward = lambda t: sigma(t) * data_std\n scaled_inverse = lambda y: sigma.inverse(y / data_std)\n scaled_sigma = InvertibleSchedule(scaled_forward, scaled_inverse)\n return cls(scale=jnp.ones_like, sigma=scaled_sigma)\n\n\ndef _linear_rescale(\n in_min: float, in_max: float, out_min: float, out_max: float\n) -> InvertibleSchedule:\n \"\"\"Linearly rescale input between specified ranges.\"\"\"\n in_range = in_max - in_min\n out_range = out_max - out_min\n fwd = lambda x: out_min + (x - in_min) / in_range * out_range\n inv = lambda y: in_min + (y - out_min) / out_range * in_range\n return InvertibleSchedule(fwd, inv)\n\n\ndef tangent_noise_schedule(\n clip_max: float = 100.0, start: float = 0.0, end: float = 1.5\n) -> InvertibleSchedule:\n \"\"\"Tangent noise schedule.\n\n This schedule is obtained by taking the section of the tan(t) function\n inside domain [`start`, `end`], and applying linear rescaling such that the\n input domain is [0, 1] and output range is [0, `clip_max`].\n\n This is really the \"cosine\" schedule proposed in Dhariwal and Nicol\n (https://arxiv.org/abs/2105.05233). The original schedule is\n a cosine function in γ, i.e. γ = cos(pi/2 * t) for t in [0, 1]. With\n γ = 1 / (σ^2 + 1), the corresponding σ schedule is a tangent function.\n\n The \"shifted\" cosine schedule proposed in Hoogeboom et al.\n (https://arxiv.org/abs/2301.11093) simply corresponds to adjusting\n the `clip_max` parameter. Empirical evidence suggests that one should consider\n increasing this maximum noise level when modeling higher resolution images.\n\n Args:\n clip_max: The maximum noise level in the schedule.\n start: The left endpoint of the tangent function domain used.\n end: The right endpoint of the tangent function domain used.\n\n Returns:\n A tangent noise schedule.\n \"\"\"\n if not -np.pi / 2 < start < end < np.pi / 2:\n raise ValueError(\"Must have -pi/2 < `start` < `end` < pi/2.\")\n\n in_rescale = _linear_rescale(\n in_min=0.0, in_max=MAX_DIFFUION_TIME, out_min=start, out_max=end\n )\n out_rescale = _linear_rescale(\n in_min=np.tan(start), in_max=np.tan(end), out_min=0.0, out_max=clip_max\n )\n sigma = lambda t: out_rescale(jnp.tan(in_rescale(t)))\n inverse = lambda y: in_rescale.inverse(jnp.arctan(out_rescale.inverse(y)))\n return InvertibleSchedule(sigma, inverse)\n\n\ndef power_noise_schedule(\n clip_max: float = 100.0,\n p: float = 1.0,\n start: float = 0.0,\n end: float = 1.0,\n) -> InvertibleSchedule:\n \"\"\"Power noise schedule.\n\n This schedule is obtained by taking the section of the t^p (where p > 0)\n function inside domain [`start`, `end`], and applying linear rescaling such\n that the input domain is [0, 1] and output range is [0, `clip_max`].\n\n Variance exploding schedules in Karras et al.\n (https://arxiv.org/abs/2206.00364) and Song et al.\n (https://arxiv.org/abs/2011.13456) use p = 1 and p = 0.5 respectively.\n\n Args:\n clip_max: The maximum noise level in the schedule.\n p: The degree of power schedule.\n start: The left endpoint of the power function domain used.\n end: The right endpoint of the power function domain used.\n\n Returns:\n A power noise schedule.\n \"\"\"\n if not (0 <= start < end and p > 0):\n raise ValueError(\"Must have `p` > 0 and 0 <= `start` < `end`.\")\n\n in_rescale = _linear_rescale(\n in_min=MIN_DIFFUION_TIME,\n in_max=MAX_DIFFUION_TIME,\n out_min=start,\n out_max=end,\n )\n out_rescale = _linear_rescale(\n in_min=start**p, in_max=end**p, out_min=0.0, out_max=clip_max\n )\n sigma = lambda t: out_rescale(jnp.power(in_rescale(t), p))\n inverse = lambda y: in_rescale.inverse( # pylint:disable=g-long-lambda\n jnp.power(out_rescale.inverse(y), 1 / p)\n )\n return InvertibleSchedule(sigma, inverse)\n\n\ndef exponential_noise_schedule(\n clip_max: float = 100.0,\n base: float = np.e**0.5,\n start: float = 0.0,\n end: float = 5.0,\n) -> InvertibleSchedule:\n \"\"\"Exponential noise schedule.\n\n This schedule is obtained by taking the section of the base^t (where base > 1)\n function inside domain [`start`, `end`], and applying linear rescaling such\n that the input domain is [0, 1] and output range is [0, `clip_max`]. This\n schedule is always a convex function.\n\n Args:\n clip_max: The maximum noise level in the schedule.\n base: The base of the exponential. Defaults to sqrt(e) so that σ^2 follows\n schedule exp(t).\n start: The left endpoint of the exponential function domain used.\n end: The right endpoint of the exponential function domain used.\n\n Returns:\n An exponential noise schedule.\n \"\"\"\n if not (start < end and base > 1.0):\n raise ValueError(\"Must have `base` > 1 and `start` < `end`.\")\n\n in_rescale = _linear_rescale(\n in_min=MIN_DIFFUION_TIME,\n in_max=MAX_DIFFUION_TIME,\n out_min=start,\n out_max=end,\n )\n out_rescale = _linear_rescale(\n in_min=base**start, in_max=base**end, out_min=0.0, out_max=clip_max\n )\n sigma = lambda t: out_rescale(jnp.power(base, in_rescale(t)))\n inverse = lambda y: in_rescale.inverse( # pylint:disable=g-long-lambda\n jnp.log(out_rescale.inverse(y)) / jnp.log(base)\n )\n return InvertibleSchedule(sigma, inverse)\n\n\n# ********************\n# Noise sampling\n# ********************\n\n\nclass NoiseLevelSampling(Protocol):\n\n def __call__(self, rng: jax.Array, shape: tuple[int, ...]) -> Array:\n \"\"\"Samples noise levels for training.\"\"\"\n ...\n\n\ndef _uniform_samples(\n rng: jax.Array,\n shape: tuple[int, ...],\n uniform_grid: bool,\n) -> Array:\n \"\"\"Generates samples from uniform distribution on [0, 1].\"\"\"\n if uniform_grid:\n s0 = jax.random.uniform(rng, dtype=jnp.float32)\n grid = jnp.linspace(0, 1, np.prod(shape), endpoint=False, dtype=jnp.float32)\n samples = jnp.reshape(jnp.remainder(grid + s0, 1), shape)\n else:\n samples = jax.random.uniform(rng, shape, dtype=jnp.float32)\n return samples\n\n\ndef log_uniform_sampling(\n scheme: Diffusion, clip_min: float = 1e-4, uniform_grid: bool = False\n) -> NoiseLevelSampling:\n \"\"\"Samples noise whose natural log follows a uniform distribution.\"\"\"\n\n def _noise_sampling(\n rng: jax.Array, shape: tuple[int, ...]\n ) -> Array:\n samples = _uniform_samples(rng, shape, uniform_grid)\n log_min, log_max = jnp.log(clip_min), jnp.log(scheme.sigma_max)\n samples = (log_max - log_min) * samples + log_min\n return jnp.exp(samples)\n\n return _noise_sampling\n\n\ndef time_uniform_sampling(\n scheme: Diffusion, clip_min: float = 1e-4, uniform_grid: bool = False\n) -> NoiseLevelSampling:\n \"\"\"Samples noise from a uniform distribution in t.\"\"\"\n\n def _noise_sampling(\n rng: jax.Array, shape: tuple[int, ...]\n ) -> Array:\n samples = _uniform_samples(rng, shape, uniform_grid)\n min_t = scheme.sigma.inverse(clip_min)\n samples = (MAX_DIFFUION_TIME - min_t) * samples + min_t\n return jnp.asarray(scheme.sigma(samples))\n\n return _noise_sampling\n\n\ndef normal_sampling(\n scheme: Diffusion,\n clip_min: float = 1e-4,\n p_mean: float = -1.2,\n p_std: float = 1.2,\n) -> NoiseLevelSampling:\n \"\"\"Samples noise from a normal distribution.\n\n This noise sampling is first used in Karras et al.\n (https://arxiv.org/abs/2206.00364). The default mean and standard deviation\n settings are designed for diffusion scheme with sigma_max = 80.\n\n Args:\n scheme: The diffusion scheme.\n clip_min: The minimum noise cutoff.\n p_mean: The mean of the sampling normal distribution.\n p_std: The standard deviation of the sampling normal distribution.\n\n Returns:\n A normal sampling function.\n \"\"\"\n\n def _noise_sampler(rng: jax.Array, shape: tuple[int, ...]) -> Array:\n log_sigma = jax.random.normal(rng, shape, dtype=jnp.float32)\n log_sigma = p_mean + p_std * log_sigma\n return jnp.clip(jnp.exp(log_sigma), clip_min, scheme.sigma_max)\n\n return _noise_sampler\n\n\n# ********************\n# Noise weighting\n# ********************\n\n\nclass NoiseLossWeighting(Protocol):\n\n def __call__(self, sigma: chex.Numeric) -> Array:\n \"\"\"Returns weights of the input noise levels in the loss function.\"\"\"\n ...\n\n\ndef inverse_squared_weighting(sigma: Array) -> Array:\n return 1 / jnp.square(sigma)\n\n\ndef edm_weighting(data_std: float = 1.0) -> NoiseLossWeighting:\n \"\"\"Weighting proposed in Karras et al. (https://arxiv.org/abs/2206.00364).\n\n This weighting ensures the effective weights are uniform across noise levels\n (see appendix B.6, eqns 139 to 144).\n\n Args:\n data_std: the standard deviation of the data.\n\n Returns:\n The weighting function.\n \"\"\"\n\n def _weight_fn(sigma: Array) -> Array:\n return (jnp.square(data_std) + jnp.square(sigma)) / jnp.square(\n data_std * sigma\n )\n\n return _weight_fn\n","repo_name":"google-research/swirl-dynamics","sub_path":"swirl_dynamics/lib/diffusion/diffusion.py","file_name":"diffusion.py","file_ext":"py","file_size_in_byte":12687,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"83"} +{"seq_id":"36575367221","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('duck_inscription', '0006_auto_20150723_1117'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='settinganneeuni',\n name='debut_pause',\n field=models.DateTimeField(null=True, blank=True),\n ),\n migrations.AddField(\n model_name='settinganneeuni',\n name='fin_pause',\n field=models.DateTimeField(null=True, blank=True),\n ),\n migrations.AlterField(\n model_name='piecesmanquantesdossierwishmodel',\n name='wish',\n field=models.OneToOneField(related_name='dossier_pieces_manquantes', to='duck_inscription.Wish'),\n ),\n ]\n","repo_name":"iedparis8/duck_inscription","sub_path":"migrations/0007_auto_20150724_1223.py","file_name":"0007_auto_20150724_1223.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"40198509555","text":"\"\"\"\n\n1.\n\nAfter completing the exercises on lists and tuples, Jimmy noticed that, according to his estimate_average_slot_payout function, the slot machines at the Learn Python Casino are actually rigged against the house, and are profitable to play in the long run.\n\nStarting with $200 in his pocket, Jimmy has played the slots 500 times, recording his new balance in a list after each spin. He used Python's matplotlib library to make a graph of his balance over time:\n\"\"\"\n\n# Import the jimmy_slots submodule\nfrom learntools.python import jimmy_slots\n# Call the get_graph() function to get Jimmy's graph\ngraph = jimmy_slots.get_graph()\ngraph.set_title(\"Results of 500 slot machine pulls\")\ngraph.set_ylim(0)\ngraph\n\n\ndef prettify_graph(graph):\n \"\"\"Modify the given graph according to Jimmy's requests: add a title, make the y-axis\n start at 0, label the y-axis. (And, if you're feeling ambitious, format the tick marks\n as dollar amounts using the \"$\" symbol.)\n \"\"\"\n graph.set_title(\"Results of 500 slot machine pulls\")\n graph.set_ylim(bottom = 0)\n graph.set_ylabel(\"Balance\")\n# graph.set_yticks(\"$\")\n\ngraph = jimmy_slots.get_graph()\nprettify_graph(graph)\nhelp(graph.set_yticklabels)\n\n\n\n\"\"\"\n2. 🌶️🌶️\n\nThis is a very hard problem. Feel free to skip it if you are short on time:\n\nLuigi is trying to perform an analysis to determine the best items for winning races on the Mario Kart circuit. He has some data in the form of lists of dictionaries that look like...\n\n[\n {'name': 'Peach', 'items': ['green shell', 'banana', 'green shell',], 'finish': 3},\n {'name': 'Bowser', 'items': ['green shell',], 'finish': 1},\n # Sometimes the racer's name wasn't recorded\n {'name': None, 'items': ['mushroom',], 'finish': 2},\n {'name': 'Toad', 'items': ['green shell', 'mushroom'], 'finish': 1},\n]\n'items' is a list of all the power-up items the racer picked up in that race, and 'finish' was their placement in the race (1 for first place, 3 for third, etc.).\n\nHe wrote the function below to take a list like this and return a dictionary mapping each item to how many times it was picked up by first-place finishers.\n\"\"\"\n\ndef best_items(racers):\n \"\"\"Given a list of racer dictionaries, return a dictionary mapping items to the number\n of times those items were picked up by racers who finished in first place.\n \"\"\"\n winner_item_counts = {}\n for i in range(len(racers)):\n # The i'th racer dictionary\n racer = racers[i]\n # We're only interested in racers who finished in first\n if racer['finish'] == 1:\n for j in racer['items']:\n # Add one to the count for this item (adding it to the dict if necessary)\n if j not in winner_item_counts:\n winner_item_counts[i] = 0\n winner_item_counts[i] += 1\n\n # Data quality issues :/ Print a warning about racers with no name set. We'll take care of it later.\n if racer['name'] is None:\n print(\"WARNING: Encountered racer with unknown name on iteration {}/{} (racer = {})\".format(\n i+1, len(racers), racer['name'])\n )\n return winner_item_counts\n\n\n\"\"\"\n3. 🌶️\n\nSuppose we wanted to create a new type to represent hands in blackjack. One thing we might want to do with this type is overload the comparison operators like > and <= so that we could use them to check whether one hand beats another. e.g. it'd be cool if we could do this:\n\n>>> hand1 = BlackjackHand(['K', 'A'])\n>>> hand2 = BlackjackHand(['7', '10', 'A'])\n>>> hand1 > hand2\nTrue\nWell, we're not going to do all that in this question (defining custom classes is a bit beyond the scope of these lessons), but the code we're asking you to write in the function below is very similar to what we'd have to write if we were defining our own BlackjackHand class. (We'd put it in the __gt__ magic method to define our custom behaviour for >.)\n\nFill in the body of the blackjack_hand_greater_than function according to the docstring.\n\"\"\"\n\n\ndef blackjack_hand_greater_than(hand_1, hand_2):\n \"\"\"\n Return True if hand_1 beats hand_2, and False otherwise.\n\n In order for hand_1 to beat hand_2 the following must be true:\n - The total of hand_1 must not exceed 21\n - The total of hand_1 must exceed the total of hand_2 OR hand_2's total must exceed 21\n\n Hands are represented as a list of cards. Each card is represented by a string.\n\n When adding up a hand's total, cards with numbers count for that many points. Face\n cards ('J', 'Q', and 'K') are worth 10 points. 'A' can count for 1 or 11.\n\n When determining a hand's total, you should try to count aces in the way that\n maximizes the hand's total without going over 21. e.g. the total of ['A', 'A', '9'] is 21,\n the total of ['A', 'A', '9', '3'] is 14.\n\n Examples:\n >>> blackjack_hand_greater_than(['K'], ['3', '4'])\n True\n >>> blackjack_hand_greater_than(['K'], ['10'])\n False\n >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3'])\n False\n \"\"\"\n sum_hand_1 = 0\n a_hand_1 = 0\n sum_hand_2 = 0\n a_hand_2 = 0\n for num in hand_1:\n if num == 'J' or num == 'Q' or num == 'K':\n num = 10\n elif num == 'A':\n a_hand_1 += 1\n num = 0\n else:\n num = int(num)\n sum_hand_1 += num\n if a_hand_1:\n if sum_hand_1 + a_hand_1 + 10 <= 21:\n sum_hand_1 += a_hand_1 + 10\n a_hand_1 = 0\n else:\n sum_hand_1 += a_hand_1\n if sum_hand_1 > 21:\n return (False)\n for num in hand_2:\n if num == 'J' or num == 'Q' or num == 'K':\n num = 10\n elif num == 'A':\n a_hand_2 += 1\n num = 0\n else:\n num = int(num)\n sum_hand_2 += num\n if a_hand_2:\n if sum_hand_2 + a_hand_2 + 10 <= 21:\n sum_hand_2 += a_hand_2 + 10\n a_hand_2 = 0\n else:\n sum_hand_2 += a_hand_2\n if sum_hand_1 > sum_hand_2 or sum_hand_2 > 21:\n return (True)\n else:\n return False","repo_name":"cozytk/kaggle","sub_path":"courses/python/external_libraries.py","file_name":"external_libraries.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"32286528141","text":"import datetime\nimport os\n\nFILENAME = \"calendar.txt\"\n'''\n\nIMPORTANT NOTE: Do NOT change any of the function names or their signatures\n(the parameters they take).\nYour functions must behave exactly as described. Please check correctness by\nrunning DocTests included in function headers. You may not use any print or\ninput statements in your code.\n\nManage a calendar database.\n\nA calendar is a dictionary keyed by date (\"YYYY-MM-DD\") with value being a list\nof strings, the events on the specified date.\n\n'''\n\n\n# -----------------------------------------------------------------------------\n# Please implement the following calendar commands\n# -----------------------------------------------------------------------------\n\ndef command_help():\n \"\"\"\n () -> str\n This function is already implemented. Please do not change it.\n Returns a help message for the system. That is...\n \"\"\"\n\n help_me = \"\"\"\n Help for Calendar. The calendar commands are\n\n add DATE START END DETAILS add the event DETAILS at the specified DATE with specific START and END time\n show show all events in the calendar\n delete DATE NUMBER delete the specified event (by NUMBER) from\n the calendar\n quit quit this program\n help display this help message\n\n Examples: user data follows command:\n\n command: add 2018-10-12 18 19 dinner with jane\n success\n\n command: show\n 2018-10-12 : \n start : 08:00, \n\t\t\tend : 09:00,\n\t\t\ttitle : Eye doctor\n\t\t\t\n start : 12:30,\n\t\t\tend : 13:00,\n\t\t\ttitle : lunch with sid\n \n\t\t\tstart : 18:00,\n\t\t\tend : 19:00, \n\t\t\ttitle : dinner with jane\n 2018-10-29 : \n start : 10:00,\n\t\t\tend : 11:00,\n\t\t\ttitle : Change oil in blue car\n\t\t\t\n start : 12:00,\n\t\t\tend : 14:00,\n\t\t\ttitle : Fix tree near front walkway\n\t\t\t\n start : 18:00,\n\t\t\tend : 19:00,\n\t\t\ttitle : Get salad stuff, leuttice, red peppers, green peppers\n 2018-11-06 : \n start : 18:00,\n\t\t\tend : 22:00,\n\t\t\ttitle : Sid's birthday\n\n command: delete 2018-10-29 10\n deleted\n\n A DATE has the form YYYY-MM-DD, for example\n 2018-12-21\n 2016-01-02\n\n START and END has a format HH where HH is an hour in 24h format, for example\n 09\n 21\n\n Event DETAILS consist of alphabetic characters,\n no tabs or newlines allowed.\n \"\"\"\n return help_me\n\n\ndef command_add(date, start_time, end_time, title, calendar):\n \"\"\"\n (str, int, int, str, dict) -> boolean\n Add title to the list at calendar[date]\n Create date if it was not there\n Adds the date if start_time is less or equal to the end_time\n\n date: A string date formatted as \"YYYY-MM-DD\"\n start_time: An integer from 0-23 representing the start time\n end_time: An integer from 0-23 representing the start time\n title: A string describing the event\n calendar: The calendar database\n return: boolean of whether the even was successfully added\n\n >>> calendar = {}\n >>> command_add(\" \", 11, 12, \"Python class\", calendar)\n True\n\n >>> command_add(\" \", 13, 14, \"CCNA class\", calendar)\n True\n\n >>> calendar.clear()\n >>> command_add(\"2018-02-28\", 11, 12, \"Python class\", calendar)\n True\n\n >>> calendar == {\"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}]}\n True\n\n >>> command_add(\"2018-03-11\", 14, 16, \"CSCA08 test 2\", calendar)\n True\n >>> calendar == {\"2018-03-11\": [{\"start\": 14, \"end\": 16, \"title\": \"CSCA08 test 2\"}], \\\n \"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}]}\n True\n\n >>> command_add(\"2018-03-11\", 10, 9, \"go out with friends after test\", calendar)\n False\n >>> calendar == {\"2018-03-11\": [{\"start\": 14, \"end\": 16, \"title\": \"CSCA08 test 2\"}], \\\n \"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}]}\n True\n\n >>> command_add(\"2018-03-13\", 13, 13, \"Have fun\", calendar)\n True\n >>> calendar == {\"2018-03-13\": [{\"start\": 13, \"end\": 13, \"title\": \"Have fun\"}], \\\n \"2018-03-11\": [{\"start\": 14, \"end\": 16, \"title\": \"CSCA08 test 2\"}], \\\n \"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}]}\n True\n\n\n \"\"\"\n\n # YOUR CODE GOES HERE\n if start_time > end_time:\n return False\n if start_time not in range(0, 25) or end_time not in range(0, 25):\n return False\n if calendar:\n # if not empty\n if len(date.strip()) == 0:\n date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n if date not in calendar:\n # new date\n calendar[date] = [{\"start\": start_time, \"end\": end_time, \"title\": title}]\n else:\n # exist date\n for dates in sorted(list(calendar.keys()), reverse=True):\n if date == dates:\n tasks = list(calendar[date])\n tasks.append({\"start\": start_time, \"end\": end_time, \"title\": title})\n tasks = sorted(tasks, key=lambda k: k['start'], reverse=False)\n calendar[date] = tasks\n save_calendar(calendar)\n return True\n\n else:\n # if empty\n calendar[date] = [{\"start\": start_time, \"end\": end_time, \"title\": title}]\n save_calendar(calendar)\n return True\n\n\ndef command_show(calendar):\n \"\"\"\n (dict) -> str\n Returns the list of events for calendar sorted in decreasing date order\n and increasing time order within the date\n as a string, see examples below for a sample formatting\n calendar: the database of events\n\n Example:\n >>> calendar = {}\n >>> command_add(\"2018-01-15\", 11, 13, \"Eye doctor\", calendar)\n True\n >>> command_add(\"2018-01-15\", 8, 9, \"lunch with sid\", calendar)\n True\n >>> command_add(\"2018-02-10\", 12, 23, \"Change oil in blue car\", calendar)\n True\n >>> command_add(\"2018-02-10\", 20, 22, \"dinner with Jane\", calendar)\n True\n >>> command_add(\"2017-12-22\", 5, 8, \"Fix tree near front walkway\", calendar)\n True\n >>> command_add(\"2017-12-22\", 13, 15, \"Get salad stuff\", calendar)\n True\n >>> command_add(\"2018-05-06\", 19, 23, \"Sid's birthday\", calendar)\n True\n >>> command_show(calendar)\n \"\\\\n2018-05-06 : \\\\n start : 19:00,\\\\n end : 23:00,\\\\n title : Sid's birthday\\\\n2018-02-10 : \\\\n start : 12:00,\\\\n end : 23:00,\\\\n title : Change oil in blue car\\\\n\\\\n start : 20:00,\\\\n end : 22:00,\\\\n title : dinner with Jane\\\\n2018-01-15 : \\\\n start : 08:00,\\\\n end : 09:00,\\\\n title : lunch with sid\\\\n\\\\n start : 11:00,\\\\n end : 13:00,\\\\n title : Eye doctor\\\\n2017-12-22 : \\\\n start : 05:00,\\\\n end : 08:00,\\\\n title : Fix tree near front walkway\\\\n\\\\n start : 13:00,\\\\n end : 15:00,\\\\n title : Get salad stuff\"\n \"\"\"\n if calendar:\n str_return = \"\"\n for dict_day in sorted(list(calendar.keys()), reverse=True):\n list_tasks = calendar[dict_day]\n str_return += \"\\n\" + dict_day + \" : \"\n if len(list_tasks) > 1:\n def my_func(e):\n return e['start']\n list_tasks.sort(reverse=False, key=my_func)\n for dict_task in list_tasks:\n start = dict_task[\"start\"]\n end = dict_task[\"end\"]\n title = dict_task[\"title\"]\n str_return += \"\\n start : \" +\\\n datetime.datetime(2018, 6, 1, start).strftime(\"%H:%M\") + \\\n \",\\n end : \" +\\\n datetime.datetime(2018, 6, 1, end).strftime(\"%H:%M\") + \",\\n\" + \\\n \" title : \" + title\n if len(list_tasks) > 1 and dict_task != list_tasks[-1]: # only middle change line appended\n str_return += \"\\n\"\n return str_return\n else:\n return \"\"\n\n\ndef command_delete(date, start_time, calendar):\n \"\"\"\n (str, int, dict) -> str\n Delete the entry at calendar[date][start_time]\n If calendar[date] is empty, remove this date from the calendar.\n If the entry does not exist, do nothing\n date: A string date formatted as \"YYYY-MM-DD\"\n start_time: An integer indicating the start of the event in calendar[date] to delete\n calendar: The calendar database\n return: a string indicating any errors, True for no errors\n\n Example:\n\n\n >>> calendar = {}\n >>> command_add(\"2018-02-28\", 11, 12, \"Python class\", calendar)\n True\n >>> calendar == {\"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}]}\n True\n >>> command_add(\"2018-03-11\", 14, 16, \"CSCA08 test 2\", calendar)\n True\n >>> calendar == {\"2018-03-11\": [{\"start\": 14, \"end\": 16, \"title\": \"CSCA08 test 2\"}], \\\n \"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}]}\n True\n >>> command_add(\"2018-03-13\", 13, 13, \"Have fun\", calendar)\n True\n >>> calendar == {\"2018-03-13\": [{\"start\": 13, \"end\": 13, \"title\": \"Have fun\"}], \"2018-03-11\": \\\n [{\"start\": 14, \"end\": 16, \"title\": \"CSCA08 test 2\"}], \"2018-02-28\": [{\"start\": 11, \"end\": 12, \\\n \"title\": \"Python class\"}]}\n True\n >>> command_delete(\"2015-01-01\", 1, calendar)\n '2015-01-01 is not a date in the calendar'\n >>> command_delete(\"2018-03-11\", 3, calendar)\n 'There is no event with start time of 3 on date 2018-03-11 in the calendar'\n >>> command_delete(\"2018-02-28\", 11, calendar)\n True\n >>> calendar == {\"2018-03-13\": [{\"start\": 13, \"end\": 13, \"title\": \"Have fun\"}], \"2018-03-11\": [{\"start\": 14, \"end\": 16, \"title\": \"CSCA08 test 2\"}]}\n True\n >>> command_delete(\"2018-03-11\", 14, calendar)\n True\n >>> calendar == {\"2018-03-13\": [{\"start\": 13, \"end\": 13, \"title\": \"Have fun\"}]}\n True\n >>> command_delete(\"2018-03-13\", 13, calendar)\n True\n >>> calendar == {}\n True\n \"\"\"\n\n # YOUR CODE GOES HERE\n if date in calendar:\n list_task = calendar.get(date)\n found = False\n for dict_task in list_task:\n if start_time == dict_task[\"start\"]:\n found = True\n list_task.remove(dict_task)\n if len(list_task) == 0:\n calendar.pop(date)\n save_calendar(calendar)\n return True\n if not found:\n return \"There is no event with start time of {} on date {} in the calendar\".format(start_time, date)\n else:\n return date + \" is not a date in the calendar\"\n\n# -----------------------------------------------------------------------------\n# Functions dealing with calendar persistence\n# -----------------------------------------------------------------------------\n\n\"\"\"\nThe calendar is read and written to disk.\n\n...\n\ndate_i is \"YYYY-MM-DD\"'\ndescription can not have tab or new line characters in them.\n\n\"\"\"\n\n\ndef save_calendar(calendar):\n \"\"\"\n (dict) -> bool\n Save calendar to 'calendar.txt', overwriting it if it already exists. The calendar events do not have\n to be saved in any particular order\n\n The format of calendar.txt is the following:\n\n date_1:start_time_1-end_time_1 description_1\\tstart_time_2-end_time_2 description_2\\t...\\tstart_time_n-end_time_n description_n\\\\n\n date_2:start_time_1-end_time_1 description_1\\tstart_time_2-end_time_2 description_2\\t...\\tstart_time_n-end_time_n description_n\\\\n\n date_n:start_time_1-end_time_1 description_1\\tstart_time_2-end_time_2 description_2\\t...\\tstart_time_n-end_time_n description_n\\\\n\n\n Example: The following calendar...\n\n\n 2018-03-13 : \n start : 13:00,\n end : 13:00,\n title : Have fun\n 2018-03-11 : \n start : 10:00,\n end : 12:00,\n title : Another event on this date\n\n start : 14:00,\n end : 16:00,\n title : CSCA08 test 2\n 2018-02-28 : \n start : 11:00,\n end : 12:00,\n title : Python class\n\n appears in calendar.txt as ...\n\n 2018-03-13:13-13 Have fun\n 2018-03-11:10-12 Another event on this date 14-16 CSCA08 test 2\n 2018-02-28:11-12 Python class\n\n calendar: dictionary containing a calendar\n return: True if the calendar was saved.\n\n\n >>> calendar = {\"2019-01-11\": \\\n [\\\n {\"start\": 3, \"end\": 4, \"title\": \"Have fun3\"}, \\\n {\"start\": 5, \"end\": 6, \"title\": \"Have fun4\"}, \\\n {\"start\": 7, \"end\": 8, \"title\": \"Have fun5\"}\\\n ],\\\n \"2018-03-11\": \\\n [\\\n {\"start\": 10, \"end\": 11, \"title\": \"test 2\"},\\\n {\"start\": 12, \"end\": 13, \"title\": \"test 3\"}\\\n ],\\\n \"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}],\\\n }\n >>> save_calendar(calendar)\n True\n \"\"\"\n my_output = \"\"\n\n for date in sorted(list(calendar.keys()), reverse=True):\n tasks = list(calendar[date])\n my_string = \"\"\n for task in tasks:\n my_string += str(datetime.datetime(2018, 6, 1, task['start']).strftime(\"%H\")) \\\n + \"-\" + str(datetime.datetime(2018, 6, 1, task['end']).strftime(\"%H\")) \\\n + \" \" + task['title']\n my_string += '\\t'\n my_day = date + \":\" + my_string.rstrip(\"\\t.\") + \"\\n\"\n my_output += my_day\n filename = \"calendar.txt\"\n if os.path.exists(filename):\n f = open(filename, \"w\")\n f.write(my_output)\n f.close()\n return True\n else:\n return False\n\n\n\n\ndef load_calendar():\n '''\n () -> dict\n Load calendar from 'calendar.txt'. If calendar.txt does not exist,\n create and return an empty calendar. For the format of calendar.txt\n see save_calendar() above.\n\n return: calendar.\n >>> load_calendar()\n True\n\n calendar = {\n \"2019-01-11\": \\\n [ \\\n {\"start\": 3, \"end\": 4, \"title\": \"Have fun3\"}, \\\n {\"start\": 5, \"end\": 6, \"title\": \"Have fun4\"} \\\n ], \\\n \"2018-03-11\": \\\n [ \\\n {\"start\": 14, \"end\": 16, \"title\": \"CSCA08 test 2\"} \\\n ], \\\n \"2018-02-28\": [{\"start\": 11, \"end\": 12, \"title\": \"Python class\"}] \\\n }\n\n '''\n if not os.path.exists(FILENAME):\n open(FILENAME, \"a\").close\n f = open(FILENAME, \"r\")\n calendar = {}\n if not f.read(1):\n # empty txt\n f.seek(0)\n f.close\n return calendar\n else:\n f.seek(0)\n days = f.read().strip().split(\"\\n\")\n for day in days:\n date = day.split(\":\")[0]\n str_tasks = day.split(\":\")[1]\n list_task = str_tasks.split(\"\\t\")\n calendar[date] = []\n list_tasks_for_dict = []\n for str_task in list_task:\n list_time_title = str_task.split()\n str_time = list_time_title.pop(0)\n int_start = int(str_time.split(\"-\")[0])\n int_end = int(str_time.split(\"-\")[1])\n str_title = \"\"\n for x in list_time_title:\n str_title += x + \" \"\n list_tasks_for_dict.append({\"start\": int_start, \"end\": int_end, \"title\": str_title.rstrip()})\n calendar[date] = list_tasks_for_dict\n f.close\n\n return calendar\n\n\n# -----------------------------------------------------------------------------\n# Functions dealing with parsing commands\n# -----------------------------------------------------------------------------\n\n\ndef is_command(command):\n '''\n (str) -> bool\n Return whether command is a valid command\n Valid commands are any of the options below\n \"add\", \"delete\", \"quit\", \"help\", \"show\"\n You are not allowed to use regular expressions in your implementation.\n command: string\n return: True if command is one of [\"add\", \"delete\", \"quit\", \"help\", \"show\"]\n false otherwise\n Example:\n >>> is_command(\"add\")\n True\n >>> is_command(\" add \")\n False\n >>> is_command(\"List\")\n False\n\n '''\n\n # YOUR CODE GOES HERE\n # pass\n command_dict = (\"add\", \"delete\", \"quit\", \"help\", \"show\")\n if command in command_dict:\n return True\n else:\n return False\n\ndef is_calendar_date(date):\n '''\n (str) -> bool\n Return whether date looks like a calendar date\n date: a string\n return: True, if date has the form \"YYYY-MM-DD\" and False otherwise\n You are not allowed to use regular expressions in your implementation.\n Also you are not allowed to use isdigit() or the datetime module functions.\n\n Example:\n\n >>> is_calendar_date(\"215-110-10\") # invalid year\n False\n >>> is_calendar_date(\"15-10-10\") # invalid year\n False\n >>> is_calendar_date(\"2015-10-15\")\n True\n >>> is_calendar_date(\"2015-5-10\") # invalid month\n False\n >>> is_calendar_date(\"2015-15-10\") # invalid month\n False\n >>> is_calendar_date(\"2015-05-10\")\n True\n >>> is_calendar_date(\"2015-10-55\") # invalid day\n False\n >>> is_calendar_date(\"2015-55\") # invalid format\n False\n >>> is_calendar_date(\"jane-is-gg\") # YYYY, MM, DD should all be digits\n False\n\n Note: This does not validate days of the month, or leap year dates.\n\n >>> is_calendar_date(\"2015-04-31\") # True even though April has only 30 days.\n True\n\n '''\n # Algorithm: Check length, then pull pieces apart and check them. Use only\n # basic string\n # manipulation, comparisons, and type conversion. Please do not use any\n # powerful date functions\n # you may find in python libraries.\n # 2015-10-12\n # 0123456789\n\n # YOUR CODE GOES HERE\n # pass\n if len(date) < 10 or date[4] != \"-\" or date[7] != \"-\":\n return False\n\n year = date[0:4]\n month = date[5:7]\n day = date[8:10]\n\n if not is_natural_number(year) \\\n or not is_natural_number(month) \\\n or not is_natural_number(day) or int(month) not in range(1, 13)\\\n or int(day) not in range(1, 32):\n return False\n else:\n return True\n\n\ndef is_natural_number(str):\n '''\n (str) -> bool\n Return whether str is a string representation of a natural number,\n that is, 0,1,2,3,...,23,24,...1023, 1024, ...\n In CS, 0 is a natural number\n param str: string\n Do not use string functions\n return: True if num is a string consisting of only digits. False otherwise.\n Example:\n\n >>> is_natural_number(\"0\")\n True\n >>> is_natural_number(\"05\")\n True\n >>> is_natural_number(\"2015\")\n True\n >>> is_natural_number(\"9 3\")\n False\n >>> is_natural_number(\"sid\")\n False\n >>> is_natural_number(\"2,192,134\")\n False\n\n '''\n # Algorithm:\n # Check that the string has length > 0\n # Check that all characters are in [\"0123456789\"]\n\n # YOUR CODE GOES HERE\n # pass\n natural_number = \"0123456789\"\n if len(str) == 0:\n return False\n for x in str:\n if x not in natural_number:\n return False\n\n return True\n\n\ndef parse_command(line):\n '''\n (str) -> list\n Parse command and arguments from the line. Return a list\n [command, arg1, arg2, ...]\n Return [\"error\", ERROR_DETAILS] if the command is not valid.\n Return [\"help\"] otherwise.\n The valid commands are\n\n 1) add DATE START_TIME END_TIME DETAILS\n 2) show\n 3) delete DATE START_TIME\n 4) quit\n 5) help\n\n line: a string command\n return: A list consiting of [command, arg1, arg2, ...].\n Return [\"error\", ERROR_DETAILS], if line can not be parsed.\n ERROR_DETAILS displays how to use the\n\n Example:\n >>> parse_command(\"add 2015-10-21 10 11 budget meeting\")\n ['add', '2015-10-21', 10, 11, 'budget meeting']\n >>> parse_command(\"\")\n ['help']\n >>> parse_command(\"not a command\")\n ['help']\n >>> parse_command(\"help\")\n ['help']\n >>> parse_command(\"add\")\n ['error', 'add DATE START_TIME END_TIME DETAILS']\n >>> parse_command(\"add 2015-10-22\")\n ['error', 'add DATE START_TIME END_TIME DETAILS']\n >>> parse_command(\"add 2015-10-22 7 7 Tims with Sally.\")\n ['add', '2015-10-22', 7, 7, 'Tims with Sally.']\n >>> parse_command(\"add 2015-10-35 7 7 Tims with Sally.\")\n ['error', 'not a valid calendar date']\n >>> parse_command(\"show\")\n ['show']\n >>> parse_command(\"show calendar\")\n ['error', 'show']\n >>> parse_command(\"delete\")\n ['error', 'delete DATE START_TIME']\n >>> parse_command(\"delete 15-10-22\")\n ['error', 'delete DATE START_TIME']\n >>> parse_command(\"delete 15-10-22 11\")\n ['error', 'not a valid calendar date']\n >>> parse_command(\"delete 2015-10-22 3,14\")\n ['error', 'not a valid event start time']\n >>> parse_command(\"delete 2015-10-22 14\")\n ['delete', '2015-10-22', 14]\n >>> parse_command(\"quit\")\n ['quit']\n\n '''\n # HINT: You can first split, then join back the parts of\n # the final argument.\n # YOUR CODE GOES HERE\n # pass\n result = []\n if len(line) == 0 or line == \"help\":\n result.append(\"help\")\n else:\n result = line.split(\" \")\n if result[0].lower() == \"add\":\n if len(result) in range(1, 3):\n result.clear()\n result.append(\"error\")\n result.append(\"add DATE START_TIME END_TIME DETAILS\")\n if len(result) == 3:\n result.clear()\n result.append(\"error\")\n result.append(\"add DATE START_TIME END_TIME DETAILS\")\n if len(result) == 4 :\n if not is_natural_number(result[2]):\n result.clear()\n result.append(\"help\")\n return result\n else:\n result.clear()\n result.append(\"error\")\n result.append(\"add DATE START_TIME END_TIME DETAILS\")\n return result\n if len(result) > 4:\n base = []\n temp_str = \"\"\n base.append(result[0])\n if is_calendar_date(result[1]):\n base.append(result[1])\n for x in range(0, len(result)):\n if 1 < x < 4:\n base.append(int(result[x]))\n if x > 3:\n if len(result) <= 4:\n temp_str += result[x]\n if len(result) > 4:\n temp_str += result[x]\n temp_str += \" \"\n temp_str = temp_str.strip()\n result.clear()\n result = base.copy()\n result.append(temp_str)\n else:\n result.clear()\n result.append(\"error\")\n result.append(\"not a valid calendar date\")\n\n if len(result) == 2 and result[0].lower() == \"show\":\n result.clear()\n result.append(\"error\")\n result.append(\"show\")\n\n if len(result) == 3 and result[0].lower() == \"not\":\n result.clear()\n result.append(\"help\")\n\n if result[0] == \"delete\" or result[0].lower() == \"del\":\n if len(result) == 1:\n result.clear()\n result.append(\"error\")\n result.append(\"delete DATE START_TIME\")\n if len(result) == 2:\n result.clear()\n result.append(\"error\")\n result.append(\"delete DATE START_TIME\")\n if len(result) == 3:\n if not is_calendar_date(result[1]):\n result.clear()\n result.append(\"error\")\n result.append(\"not a valid calendar date\")\n if len(result) == 3:\n if not is_natural_number(result[2]):\n result.clear()\n result.append(\"error\")\n result.append(\"not a valid event start time\")\n else:\n result[2] = int(result[2])\n\n return result\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"hnzzyagami/Calendar","sub_path":"Calendar.py","file_name":"Calendar.py","file_ext":"py","file_size_in_byte":24328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"12324148355","text":"import mysql.connector\nfrom method1 import *\nfrom method2 import *\nfrom method3 import *\nfrom method4 import *\nfrom method5 import *\n\ndb_connection = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"rd43327893mysql\",\n database=\"sdc\",\n auth_plugin=\"mysql_native_password\"\n)\n\ndb_cursor = db_connection.cursor()\n\nrun = True\n\nwhile run:\n\n print(\"This is a python programme which is used to manage a SDC database.\")\n print(\"Methods:\")\n print(\"1 -> add a new note;\")\n print(\"2 -> edit a note;\")\n print(\"3 -> delete a note\")\n print(\"4 -> information about SDC\")\n print(\"5 -> show a statistics\")\n print(\"0 -> exit the programme\")\n print()\n\n print()\n\n method = input(\"Choose a method:\")\n\n print(\"You choose method\", method)\n\n if method == \"0\":\n run = False\n\n elif method == \"1\":\n method_1(db_cursor, db_connection)\n\n elif method == \"2\":\n method_2(db_cursor, db_connection)\n\n elif method == \"3\":\n method_3(db_cursor, db_connection)\n\n elif method == \"4\":\n method_4(db_cursor, db_connection)\n\n elif method == \"5\":\n method_5(db_cursor, db_connection)\n\n\n\n elif method:\n print()\n print(\"A incorrect method! Please, try again\")\n print()\n print()\n","repo_name":"bliack-swan/SDC_DATABASE","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"22500851445","text":"# 2022-03-08\n# connection pool 제작\n\nimport pandas as pd\nimport psycopg2 as pg2\nimport psycopg2\nimport numpy as np\nfrom datetime import date, timedelta\nimport itertools\nimport cx_Oracle as cxo\n\npd.set_option(\"display.max_columns\", 50)\n\n# tb_m00s22_am_pred table 기반 생사 여부 판단 도출\n# --> 해당 테이블의 sub_model_id, aggr_dt 를 group by 하여 count 가 1 이상인 경우 생으로 판단.\n# --> ** 향후 고려 필요 사항: 예측 결과가 NaN으로 나오는 경우는 어떤 case 인지?\n# 해당 case 를 판단하여 생,사 여부를 판단해야함.\n\n# 1. mk connection pool obj\ndatabase_name = \"pphmn\"\nuser = \"posrwlb\"\nhost = \"172.18.47.51\"\nport = \"5630\"\npassword = \"hmnopen\"\npool_min_conn = 1\npool_max_conn = 100\n\n# query text\nam_pred_query = \"\"\"\n SELECT am_model_id, sub_model_id, TO_CHAR(pred_date, 'YYYY-MM-DD') AS date_format, COUNT(pred_value)\n FROM poswork.tb_m00s22_am_pred\n GROUP BY am_model_id, sub_model_id, date_format\n WHERE date_format BETWEEN TO_CHAR(SYS_DATE, 'YYYY-MM-DD') AND \n\"\"\"\n\n# query_tp = 1 인 애들이 예측. 2가 실적\nam_exec_hist_sql_query = \"\"\"\n SELECT A.am_model_id, A.sub_model_id, A.query_tp, A.query_text\n A.source_db_type, A.source_db_id, A.source_db1, A.source_db2\n B.ip, B.port, B.database_name\n FROM poswork.tb_m00s22_am_exec_hist_sql as A \n LEFT OUTER JOIN poswork.tb_m00s22_cm_server as B ON\n A.source_db_id = B.serv_id\n WHERE query = 1;\n\"\"\"\n\npg_pool = pg2.pool.SimpleConnectionPool(pool_min_conn, pool_max_conn,\n host=host,\n database=database_name,\n user=user,\n password=password,\n port=port)\n\npg_connection = pg_pool.getconn()\n\n# 2. execute query and select data to dataFrame.\ntry:\n with pg_connection.cursor() as cursor:\n cursor.execute(am_pred_query)\n column_names = [desc[0] for desc in cursor.description] # cursor.description 으로 column 명 가져옴\n\n # fetchall : 모든 데이터를 한꺼번에 클라이언트로 가져올 때 사용\n # fetchone : 한번 호출에 하나의 Row 만 가져옴\n records = cursor.fetchall()\n am_pred_df = pd.DataFrame(records, columns=column_names)\n\n cursor.execute(am_exec_hist_sql_query)\n column_names = [desc[0] for desc in cursor.description]\n\n records = cursor.fetchall()\n am_exec_hist_sql_df = pd.DataFrame(records, columns=column_names)\n\n cursor.close()\n pg_pool.putconn(pg_connection)\n\nexcept (Exception, psycopg2.DatabaseError) as error:\n print(\"Error while connecting to PostgreSQL\", error)\n\nfinally:\n if pg_connection:\n print(pg_pool.closeall)\n\n# 3. submd_stat 에 저장하기 위한 전처리 작업 수행\nam_submd_stat_df = pd.DataFrame()\nam_pred_df[\"date_format\"] = pd.to_datetime(am_pred_df[\"date_format\"], format=\"%Y-%m-%d\")\n\n# 최근 한달만 filtering.\ntoday = date.today()\ntoday_before_month = today - timedelta(days=30)\n\ncurrent_day = today.strftime(\"%Y-%m-%d\")\ncurrent_day_before_month = today_before_month.strftime(\"%Y-%m-%d\")\n\n# 최근 30일치 filter\nam_pred_df_cur_months = am_pred_df[am_pred_df[\"date_format\"] > current_day_before_month]\nam_pred_df_cur_months.sort_values([\"sub_model_id\", \"date_format\"], inplace=True)\nprint(am_pred_df_cur_months)\n\n# submd_stat table 에 insert 하기 위한 result_submd_stat 계산\nam_pred_df_cur_months_distinct_by_model_id = am_pred_df_cur_months[['am_model_id', 'sub_model_id', 'date_format']] \\\n .drop_duplicates()\n\nuniq_sub_model_id = pd.unique(am_pred_df_cur_months_distinct_by_model_id.sub_model_id)\ndate_range = np.array(pd.date_range(start=current_day_before_month, end=current_day))\n\nresult_submd_stat = pd.DataFrame(list(itertools.product(uniq_sub_model_id, date_range)),\n columns=[\"sub_model_id\", \"date_format\"])\n\nresult_submd_stat = pd.merge(result_submd_stat,\n am_pred_df_cur_months_distinct_by_model_id[['am_model_id', \"sub_model_id\"]],\n how=\"left\")\n\nresult_submd_stat = pd.merge(result_submd_stat, am_pred_df_cur_months, how='left')\nresult_submd_stat['op_live'] = np.where(np.isnan(result_submd_stat['count'], 0, 1))\n\nresult_submd_stat.rename(columns={\"date_format\": \"aggr_dt\"}, inplace=True)\nresult_submd_stat[\"works_code\"] = \"P\"\n\n# save result_submd_stat.csv\nresult_submd_stat.to_csv(\"result_submd_stat.csv\", sep=\",\")\n\n\n\n","repo_name":"koni114/TIL","sub_path":"Python/daily_Python/2022-03-08.py","file_name":"2022-03-08.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"83"} +{"seq_id":"9753334257","text":"import json\n\n\ndef read_json(path: str):\n with open(path) as jsonFile:\n data = json.load(jsonFile)\n jsonFile.close()\n return data\n\n\ndef write_file(path: str, data):\n with open(path, \"w\") as outfile:\n outfile.write(data)\n outfile.close()\n","repo_name":"Readrid/aug-text-to-sql","sub_path":"paraphrase_generation/data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"11274776736","text":"import numpy as np\nfrom itertools import product\n\n\ndef sgn(n,ref=0):\n\t\treturn 1 if n>=ref else -1\n\ndef add_noise(s,proportion):\n n = int(proportion*len(s))\n for i in np.random.permutation(len(s))[:n]:\n s[i] *= -1\n \n return s\n\ndef gen_random_pattern(N):\n U = np.random.uniform(0,1,N)\n arr = np.zeros(N)\n for i in range(N):\n if U[i] > 0.5:\n arr[i] = 1\n else:\n arr[i] = -1\n return arr\n\ndef gen_list_of_patterns(N_neurons, M_patterns):\n patterns_list = []\n for i in range(M_patterns):\n patterns_list.append(gen_random_pattern(N_neurons))\n return patterns_list\n\ndef sum_patterns(pattern_1, pattern_2):\n if len(pattern_1) != len(pattern_2):\n raise Exception(\"Sum of patterns: Length mismatch\");\n else:\n result = pattern_1 + pattern_2\n result = np.vectorize(sgn)(result)\n return result\n\ndef invert_pattern(pattern):\n return np.array([x*(-1) for x in pattern])\n\ndef array_is_in(array, list_arrays):\n for arr in list_arrays:\n if np.array_equal(array,arr):\n return True\n return False\n\ndef get_all_combinations(patterns_list):\n combinations = []\n L = len(patterns_list)\n\n permutations_tuples = list(product([1,-1],repeat=L))\n sign_permutations = []\n for pr in permutations_tuples:\n sign_permutations.append(np.array(pr))\n\n if len(sign_permutations) != np.power(2,L):\n log.error(\"Permutations not doing right. Bye.\")\n sys.exit(1)\n\n patterns_arr = np.array(patterns_list)\n for signs in sign_permutations:\n res = patterns_arr*signs[:,None]\n res = np.sum(res,axis=0)\n res = np.vectorize(sgn)(res)\n combinations.append(res)\n\n return combinations\n\ndef find_inverted_spurious(hopfieldNet,patterns_list):\n spurious_count = 0\n for pattern in patterns_list:\n refreshed = hopfieldNet.evaluate_net(invert_pattern(pattern),'async')\n if not array_is_in(refreshed,patterns_list):\n spurious_count += 1\n return spurious_count\n\ndef find_combinations_spurious(hopfieldNet,patterns_list):\n spurious_count = 0\n combinations = get_all_combinations(patterns_list) \n \n for comb in combinations:\n refreshed = hopfieldNet.evaluate_net(comb,'async')\n if not array_is_in(refreshed,patterns_list):\n spurious_count += 1\n return spurious_count ","repo_name":"cristinakuo/redes-neuronales-tp1","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"4847842190","text":"from nltk import PCFG, Tree\n\nfrom nltk import nonterminals, Nonterminal, Production\n\nimport itertools\n\nimport sys\n\nimport random\n\nimport csv\n\nfrom typing import *\n\nimport json\n\nimport gzip\n\nfrom tqdm import tqdm\n\n\n\n\ndef generate(grammar, start=None, depth=None):\n\n \"\"\"\n\n Generates an iterator of all sentences from a CFG.\n\n\n\n :param grammar: The Grammar used to generate sentences.\n\n :param start: The Nonterminal from which to start generate sentences.\n\n :param depth: The maximal depth of the generated tree.\n\n :param n: The maximum number of sentences to return.\n\n :return: An iterator of lists of terminal tokens.\n\n \"\"\"\n\n if not start:\n\n start = grammar.start()\n\n if depth is None:\n\n depth = sys.maxsize\n\n\n\n items = [start]\n\n tree = _generate(grammar,items, depth)\n\n return tree[0]\n\n\n\ndef _generate(grammar,items,depth=None):\n\n if depth > 0:\n\n result = []\n\n for i in items:\n\n p = random.random()\n\n total_rule_prob = 0.\n\n if isinstance(i, Nonterminal):\n\n for prod in grammar.productions(lhs=i):\n\n total_rule_prob += prod.prob()\n\n if p < total_rule_prob:\n\n expansion = _generate(grammar, prod.rhs(), depth - 1)\n\n result += [Tree(i, expansion)]\n\n break\n\n else:\n\n result += [i] \n\n break \n\n return result\n\n\n\ndef create_file (filename, grammar, ex_generator, n=10):\n\n with open(\"test_file.csv\", mode='w') as output_file:\n\n output_writer = csv.writer(output_file, delimiter=',', quotechar=' ')\n\n# output_writer.writerow({'SRC', 'TRANSFORM', 'TRG'})\n\n output_writer.writerow(['SRC', 'TRG'])\n\n for _ in range(n):\n\n # src, trans, targ = ex_generator(grammar)\n\n (pos), src, (neg), targ = ex_generator(grammar)\n\n # output_writer.writerow([src + ' ' + trans, targ])\n\n output_writer.writerow([(pos) + src + ' ' + (neg) + targ])\n\n\ndef create_dataset_json(grammar: PCFG, ex_generator: Callable, \n file_prefix: str = '', **splits: Dict[str,int]) -> None:\n \"\"\"\n Create a dataset json file that can be read using the datasets module's dataset loader.\n params: grammar: PCFG: a PCFG object\n ex_generator: function: a function that creates a pair of sentences and associated tags\n from the grammar\n file_prefix: str: an identifier to add to the beginning of the output file names\n splits: a kwargs/dictionary mapping a string identifying a set label to the number of examples to generate\n for the file with that label\n ex: train = 10000, dev = 1000, test = 10000\n output: a file for each argument in splits that contains the specified number of example pairs\n \"\"\"\n file_prefix = file_prefix + '_' if file_prefix and not (file_prefix[-1] in ['-', '_']) else ''\n \n for name, n_examples in splits.items():\n prefixes = {}\n l = []\n print('Generating examples')\n for n in tqdm(range(n_examples)):\n source, pfx, target = ex_generator(grammar)\n prefixes[pfx] = 1 if not pfx in prefixes else prefixes[pfx] + 1\n l += [{'translation': {'src': source, 'prefix': pfx, 'tgt': target}}]\n \n for pfx in prefixes:\n print(f'{name} prop {pfx} examples: {prefixes[pfx]/n_examples}')\n \n if l:\n print('Saving examples to data/' + file_prefix + name + '.json.gz')\n with gzip.open('data/' + file_prefix + name + '.json.gz', 'wt') as f:\n for ex in tqdm(l):\n json.dump(ex, f, ensure_ascii=False)\n f.write('\\n')\n \n# def demo(N=5):\n\n# for _ in range(N):\n\n# sent = generate(grammars)\n\n# print(\" \".join(sent.leaves()))\n\n\n\n# if __name__ == \"__main__\":\n\n# demo()","repo_name":"clay-lab/negation","sub_path":"experiments/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"4760828678","text":"import torch.utils.data.distributed\r\nimport torchvision.transforms as transforms\r\nfrom PIL import Image\r\nfrom torch.autograd import Variable\r\nimport os\r\nfrom models.repvgg import create_RepVGG_A0\r\nimport torch.nn as nn\r\nclasses = ('angry','disgust','fear','happy','neutral','sad','surprise')\r\ntransform_test = transforms.Compose([\r\n transforms.Resize((224, 224)),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.51819474, 0.5250407, 0.4945761], std=[0.24228974, 0.24347611, 0.2530049])\r\n])\r\n\r\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\nmodel = create_RepVGG_A0(deploy=True)\r\nnum_ftrs = model.linear.in_features\r\nmodel.linear = nn.Linear(num_ftrs, 7)\r\nmodel.load_state_dict(torch.load('repvgg_deploy_emo.pth'))\r\n\r\nmodel.eval()\r\nmodel.to(DEVICE)\r\n\r\npath = 'test/'\r\ntestList = os.listdir(path)\r\nfor file in testList:\r\n img = Image.open(path + file)\r\n img = transform_test(img)\r\n img.unsqueeze_(0)\r\n img = Variable(img).to(DEVICE)\r\n out = model(img)\r\n # Predict\r\n _, pred = torch.max(out.data, 1)\r\n print('Image Name:{},predict:{}'.format(file, classes[pred.data.item()]))\r\n","repo_name":"Guodashen222/RepVGg","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"9286570759","text":"# 通过批处理来优化FP在MNIST Data Set中的速度\nimport sys, os\nimport numpy as np\nimport pickle\nimport time\nsys.path.append(os.pardir) # 导入父目录的文件\nfrom dataset.mnist import load_mnist # 加载MINIST数据集\n\ndef get_data():\n '''\n Returns\n -------\n (训练图像, 训练标签), (测试图像, 测试标签)\n\n flattern:设置是否将输入展开(将图像展开为一维数组, 不展开为1x28x28三维图像) True:展开, False不展开\n normalize:是否将图像正规化为0.0~1.0的值。False:图像按原来的像素保持0~255, True:正规化\n '''\n\n (x_trian, t_trian), (x_test, t_test) = load_mnist(flatten=True, normalize=True)\n return x_test, t_test\n\ndef init_network():\n with open(\"sample_weight.pkl\", 'rb') as f:\n network = pickle.load(f)\n # print(network)\n return network\n\ndef sigmoid_function(x):\n return 1 / (1 + np.exp(-x))\n\ndef softmax_function(a):\n c = np.max(a)\n exp_a = np.exp(a - c)\n sum_exp_a = np.sum(exp_a)\n y = exp_a / sum_exp_a\n return y\n\ndef work(network, x):\n W1, W2, W3 = network['W1'], network['W2'], network['W3']\n B1, B2, B3 = network['b1'], network['b2'], network['b3']\n A1 = np.dot(x, W1) + B1\n Z1 = sigmoid_function(A1)\n\n A2 = np.dot(Z1, W2) + B2\n Z2 = sigmoid_function(A2)\n\n A3 = np.dot(Z2, W3) + B3\n y = softmax_function(A3)\n\n return y\n\nstart_time = time.time()\nx, t = get_data()\nnetwork = init_network()\nbatch_size = 100 # 批处理的数量\naccuracy_cnt = 0\nfor i in range(0, len(x), batch_size):\n x_batch = x[i: i + batch_size] # 每次提取batchsize个数据出来进行FP处理\n y_batch = work(network, x_batch)\n p = np.argmax(y_batch, axis = 1) # 对应矩阵的第一维,矩阵的第一维代表行,第零维代表列\n accuracy_cnt += np.sum(p == t[i: i + batch_size])\n\nprint(\"Accuracy: \" + str(float(accuracy_cnt) / len(x)))\nend_time = time.time()\nprint(\"消耗时间: \", (end_time - start_time))\n\n\n\n\n\n","repo_name":"Lilyan-code/Book_Introduce_Deep-Learning","sub_path":"ch03/Batch_MNIST_Data_Handle.py","file_name":"Batch_MNIST_Data_Handle.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"11666021017","text":"import numpy as np\nimport tensorflow as tf\nimport cv2 as cv\nfrom tensorflow.tools.graph_transforms import TransformGraph\nfrom datetime import datetime\n\n# Read the graph.\nwith tf.gfile.FastGFile('frozen_inference_graph.pb', 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\nwith tf.Session() as sess:\n # Restore session\n sess.graph.as_default()\n tf.import_graph_def(graph_def, name='')\n \n # Read and preprocess an image.\n img = cv.imread('timg.jpg')\n print(img.shape, type(img), img.dtype, img.flags['C_CONTIGUOUS'])\n rows = img.shape[0]\n cols = img.shape[1]\n inp = cv.resize(img, (300, 300))\n inp = inp[:, :, [2, 1, 0]] # BGR2RGB\n # Run the model\n a=datetime.now()\n out = sess.run([sess.graph.get_tensor_by_name('concat:0'),\n sess.graph.get_tensor_by_name('concat_1:0')], \n feed_dict={'image_tensor:0': inp.reshape(1, inp.shape[0], inp.shape[1], 3)})\n b=datetime.now()\n print (\"===== Tensorflow RESULTS =======\")\n print(\"%d.%ds\" %((b-a).seconds, (b-a).microseconds))\n \n# print(type(out[0]))\n# print(out[0].shape)\n# print(out[0])\n \n# print(type(out[1]))\n# print(out[1].shape)\n# print(out[1])\n\nimport ctypes\nfrom ctypes import *\n\nlib = ctypes.cdll.LoadLibrary(\"./libpostprocess.so\")\n\n#######################################################################\n\nimg = img.transpose((2, 0, 1)) #HWC2CHW\n# img = img[:, :, [2, 1, 0]] # BGR2RGB\nimg = (img/255.0-0.5)*2.0\nif not img.flags['C_CONTIGUOUS']:\n img = np.ascontiguousarray(img, dtype=np.float32)\nimg_ctypes_ptr = cast(img.ctypes.data, POINTER(c_float))\n\nif not out[0].flags['C_CONTIGUOUS']:\n out[0] = np.ascontiguousarray(out[0], dtype=out[0].dtype)\nloc_ctypes_ptr = cast(out[0].ctypes.data, POINTER(c_float))\n\nif not out[1].flags['C_CONTIGUOUS']:\n out[1] = np.ascontiguousarray(out[1], dtype=out[1].dtype)\ncls_ctypes_ptr = cast(out[1].ctypes.data, POINTER(c_float))\n\n#print(img.shape, type(img), img.dtype, img.flags['C_CONTIGUOUS'])\n#print(out[0].shape, type(out[0]), out[0].dtype, out[0].flags['C_CONTIGUOUS'])\n#print(out[1].shape, type(out[1]), out[1].dtype, out[1].flags['C_CONTIGUOUS'])\n\nlib.post_process.argtypes = [POINTER(c_float), ctypes.c_int, ctypes.c_int, \n POINTER(c_float), POINTER(c_float)]\nlib.post_process(img_ctypes_ptr, c_int(cols), c_int(rows), loc_ctypes_ptr, cls_ctypes_ptr)\n\n#print(img.shape, type(img), img.dtype, img.flags['C_CONTIGUOUS'])\n# img = img[:, :, [2, 1, 0]] #RGB2BGR\nimg = img.transpose((1, 2, 0)) #CHW2HWC\nimg = (img + 1.0)*255.0/2.0\nimg = img.astype(np.uint8)\n#print(img.shape, type(img), img.dtype, img.flags['C_CONTIGUOUS'])\nif not img.flags['C_CONTIGUOUS']:\n img = np.ascontiguousarray(img, dtype=img.dtype)\n\n#print(img.shape, type(img), img.dtype, img.flags['C_CONTIGUOUS'])\ncv.imshow('TensorFlow MobileNet-SSD', img)\ncv.waitKey(5000)\n\n","repo_name":"sjtu-tcloud/AIoT-DOC","sub_path":"eas/TVM/ssd_mobilenet_v1/ssd_mnv1_tf_inf.py","file_name":"ssd_mnv1_tf_inf.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"35104706726","text":"import sys\nfrom typing import Optional, Union\n\nimport ray\nfrom ray.data._internal.compute import ActorPoolStrategy, ComputeStrategy\nfrom ray.data.dataset import Dataset\n\nfrom benchmark import Benchmark\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\n\ndef map_batches(\n input_ds: Dataset,\n batch_size: int,\n batch_format: Literal[\"default\", \"pandas\", \"pyarrow\", \"numpy\"],\n compute: Optional[Union[str, ComputeStrategy]] = None,\n num_calls: Optional[int] = 1,\n is_eager_executed: Optional[bool] = False,\n) -> Dataset:\n\n ds = input_ds\n if is_eager_executed:\n ds.fully_executed()\n\n for _ in range(num_calls):\n ds = ds.map_batches(\n lambda x: x,\n batch_format=batch_format,\n batch_size=batch_size,\n compute=compute,\n )\n if is_eager_executed:\n ds.fully_executed()\n return ds\n\n\ndef run_map_batches_benchmark(benchmark: Benchmark):\n input_ds = ray.data.read_parquet(\n \"s3://air-example-data/ursa-labs-taxi-data/by_year/2018/01\"\n )\n lazy_input_ds = input_ds.lazy()\n input_ds.fully_executed()\n\n batch_formats = [\"pandas\", \"numpy\"]\n batch_sizes = [1024, 2048, 4096, None]\n num_calls_list = [1, 2, 4]\n\n # Test different batch_size of map_batches.\n for batch_format in batch_formats:\n for batch_size in batch_sizes:\n # TODO(chengsu): https://github.com/ray-project/ray/issues/31108\n # Investigate why NumPy with batch_size being 1024, took much longer\n # to finish.\n if (\n batch_format == \"numpy\"\n and batch_size is not None\n and batch_size == 1024\n ):\n continue\n\n num_calls = 2\n test_name = f\"map-batches-{batch_format}-{batch_size}-{num_calls}-eager\"\n benchmark.run(\n test_name,\n map_batches,\n input_ds=input_ds,\n batch_format=batch_format,\n batch_size=batch_size,\n num_calls=num_calls,\n is_eager_executed=True,\n )\n test_name = f\"map-batches-{batch_format}-{batch_size}-{num_calls}-lazy\"\n benchmark.run(\n test_name,\n map_batches,\n input_ds=lazy_input_ds,\n batch_format=batch_format,\n batch_size=batch_size,\n num_calls=num_calls,\n )\n\n # Test multiple calls of map_batches.\n for num_calls in num_calls_list:\n for compute in [\"tasks\", ActorPoolStrategy(1, 1)]:\n batch_size = 4096\n if compute == \"tasks\":\n compute_strategy = \"tasks\"\n else:\n compute_strategy = \"actors\"\n\n test_name = (\n f\"map-batches-{batch_format}-{batch_size}-{num_calls}-\"\n f\"{compute_strategy}-eager\"\n )\n benchmark.run(\n test_name,\n map_batches,\n input_ds=input_ds,\n batch_format=batch_format,\n batch_size=batch_size,\n compute=compute,\n num_calls=num_calls,\n is_eager_executed=True,\n )\n test_name = (\n f\"map-batches-{batch_format}-{batch_size}-{num_calls}-\"\n f\"{compute_strategy}-lazy\"\n )\n benchmark.run(\n test_name,\n map_batches,\n input_ds=lazy_input_ds,\n batch_format=batch_format,\n batch_size=batch_size,\n compute=compute,\n num_calls=num_calls,\n )\n\n # Test different batch formats of map_batches.\n for current_format in [\"pyarrow\", \"pandas\"]:\n new_input_ds = input_ds.map_batches(\n lambda ds: ds, batch_format=current_format, batch_size=None\n ).fully_executed()\n for new_format in [\"pyarrow\", \"pandas\", \"numpy\"]:\n for batch_size in batch_sizes:\n test_name = f\"map-batches-{current_format}-to-{new_format}-{batch_size}\"\n benchmark.run(\n test_name,\n map_batches,\n input_ds=new_input_ds,\n batch_format=new_format,\n batch_size=batch_size,\n num_calls=1,\n )\n\n # Test reading multiple files.\n input_ds = ray.data.read_parquet(\n \"s3://air-example-data/ursa-labs-taxi-data/by_year/2018\"\n ).fully_executed()\n\n for batch_format in batch_formats:\n for compute in [\"tasks\", \"actors\"]:\n test_name = f\"map-batches-{batch_format}-{compute}-multi-files\"\n benchmark.run(\n test_name,\n map_batches,\n input_ds=input_ds,\n batch_format=batch_format,\n batch_size=4096,\n compute=compute,\n num_calls=1,\n )\n\n\nif __name__ == \"__main__\":\n ray.init()\n\n benchmark = Benchmark(\"map-batches\")\n\n run_map_batches_benchmark(benchmark)\n\n benchmark.write_result()\n","repo_name":"llv22/ray-macOS-cuda","sub_path":"release/nightly_tests/dataset/map_batches_benchmark.py","file_name":"map_batches_benchmark.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"27124036154","text":"import Random\nimport ScrambledString\nimport Variable\nimport Operators\n\nimport struct\n\ndef _strto4(s):\n return [_ for _ in struct.unpack('')\n\n\ndef get_flask_app(config: dict = None) -> Flask:\n\n # init flask\n flask_app = Flask(__name__)\n\n # configure app\n config = default_config\n flask_app.config.update(config)\n\n # init api and routes\n api = Api(app=flask_app)\n create_routes(api=api)\n\n # init mongoengine\n db = MongoEngine(app=flask_app)\n\n return flask_app\n\n\nif __name__ == '__main__':\n\n # main entry point when run in stand-alone mode\n app = get_flask_app()\n app.run(debug=True)","repo_name":"brc-dd/storyzen-py","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"70828320593","text":"import webapp2\n\nfrom handler.auth0handlers import Auth0CallbackHandler, IndexHandler,\\\n LogoutHandler\n\n_routes = [\n ('/', IndexHandler),\n ('/logout', LogoutHandler),\n ('/auth0callback', Auth0CallbackHandler)\n]\n\ndef AddRoute(aApiHandler):\n\t_routes.append((aApiHandler.GetAPIPath(), aApiHandler))\n\t\n#AddRoute(SelfApiHandler)\n\nconfig = {}\nconfig['webapp2_extras.sessions'] = {\n 'secret_key': 'dsfzsdfsfwaefszefzsefezsf',\n}\n\napp = webapp2.WSGIApplication(_routes, config=config, debug=True)\n\n","repo_name":"emlynoregan/auth0spike","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"4825022915","text":"#!/usr/bin/python\n# python3\n\nimport socket\nimport sys\n\nif len(sys.argv) != 4:\n\tprint(\"Usage: smtp-vrfy.py \")\n\tsys.exit(0)\n\n#Create socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect to server\nip = sys.argv[2]\nport = int(sys.argv[3]) # Convert the port to an integer\nconnect = s.connect((ip,port))\n\n# Banner grab\nbanner = s.recv(1024)\n\nprint(banner)\n\n#VRFY a user\nuser = (sys.argv[1]).encode()\ns.send(b'VRFY ' + user + b'\\r\\n')\nresult = s.recv(1024)\n\nprint(result)\n\n# Close socket\ns.close()\n","repo_name":"l3clelVl/HomeGrown","sub_path":"Python/OldVersions/SMTP_Enum-v1.py","file_name":"SMTP_Enum-v1.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"73574951312","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom io import open\nimport sys\nimport os\nimport collections\nimport fontforge\n\n# ignore warning\n# import warnings\n# warnings.filterwarnings(\"ignore\")\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (QFileDialog, QDialog, QPushButton,\n QLineEdit, QLabel,\n QApplication, QVBoxLayout)\n\n\nclass askSetting(QDialog):\n\n def __init__(self,\n app=None,\n parent=None,\n items=None):\n\n super(askSetting, self).__init__(parent)\n\n self.app = app\n self.items = items\n\n layout = QVBoxLayout()\n\n self.lineedits = {}\n\n for key in items.keys():\n layout.addWidget(QLabel(key))\n self.lineedits[key] = QLineEdit()\n self.lineedits[key].setText(items[key])\n # enable ime input\n self.lineedits[key].inputMethodQuery(Qt.ImEnabled)\n layout.addWidget(self.lineedits[key])\n\n self.btn = QPushButton('TTF File to Read', self)\n self.btn.clicked.connect(lambda: (self.bye(items)))\n self.btn.setFocusPolicy(Qt.StrongFocus)\n\n layout.addWidget(self.btn)\n\n self.setLayout(layout)\n self.setWindowTitle(' Setting ')\n\n def bye(self, items):\n fileName = QFileDialog.getOpenFileName(\n self, 'Dialog Title', '~/', initialFilter='*.ttf')\n if fileName == (u'', u'*.ttf'):\n print(\"Must Provide an input TTF file.\")\n sys.exit()\n\n for key in self.lineedits.keys():\n self.items[key] = self.lineedits[key].text()\n\n self.items['getOpenFileName'] = fileName[0]\n self.close()\n self.app.exit(1)\n\n\ninFilePrompt = \"File to read\"\ndefaultInFile = \"copyReferenceAtoB\"\n\n# outFilePrompt = \"TTF File to write\"\n# defaultOutFile = \"out.ttf\"\n\nitems = collections.OrderedDict()\nitems[inFilePrompt] = defaultInFile\n# items[outFilePrompt] = defaultOutFile\n\napp = QApplication(sys.argv)\nask = askSetting(app=app, items=items)\nask.show()\nrtnCode = app.exec_()\n# If press OK button rtnCode should be 1\nif rtnCode != 1:\n print('User abort by closing Setting dialog')\n sys.exit\n\n# print(items)\nttfFile = fontforge.open(items['getOpenFileName'])\n\nf = open(items[inFilePrompt], 'r', encoding=\"utf-8\")\n\nttfFile.selection.none()\n###\n# file contents\n# ## start with \"##\" line will be ignore to read\n# 問\n# 问\n# ie. \\w\n# ie. word\n###\ncount = 0\nfor line in f:\n if line.startswith(\"##\"):\n continue\n words = line.encode(\"raw_unicode_escape\").split()\n # words = line.split()\n # print(len(words))\n if len(words) == 2:\n sys.stdout.write(words[0].decode('unicode_escape'))\n count += 1\n if count % 25 == 0:\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n if words[0] == words[1]:\n pass\n elif words[0].startswith(b'\\u') and words[1].startswith(b'\\u'):\n ttfFile.selection.select(words[0][1:])\n ttfFile.copyReference()\n if words[1].startswith(b'\\u'):\n ttfFile.selection.select(words[1][1:])\n else:\n ttfFile.selection.select(words[1])\n\n ttfFile.paste()\n else:\n ttfFile.selection.select(words[0])\n ttfFile.copyReference()\n if words[1].startswith(b'\\u'):\n ttfFile.selection.select(words[1][1:])\n else:\n ttfFile.selection.select(words[1])\n ttfFile.paste()\n\nttfFile.fontname = \"Z-\"+ttfFile.fontname\nttfFile.familyname = \"Z-\"+ttfFile.familyname\n\nif not os.path.exists(\"out\"):\n os.makedirs(\"out\")\n\nttfFile.generate(\"out/\"+ttfFile.fontname+\".ttf\")\n\nprint(u'\\nGenerated '+ttfFile.fontname+u\" as out/\"+ttfFile.fontname+u\"\\n\")\n","repo_name":"Kennyl/python-fontforge-script","sub_path":"copyReferenceAtoB.py","file_name":"copyReferenceAtoB.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"83"} +{"seq_id":"10976875379","text":"from channels.db import database_sync_to_async\nfrom channels.testing import WebsocketCommunicator\nfrom django.test import TestCase\nfrom .consumers import ChatConsumer\nfrom .models import Room\n\n\nclass WebSocketTests(TestCase):\n @database_sync_to_async\n def create_room(self, room_name):\n return Room.objects.create(name=room_name, slug=room_name)\n\n async def test_connect(self):\n room_name = \"test_room\"\n room = await self.create_room(room_name)\n\n path = f\"/ws/{room_name}/\"\n communicator = WebsocketCommunicator(ChatConsumer.as_asgi(), path)\n connected, _ = await communicator.connect()\n\n self.assertTrue(connected)\n\n async def test_disconnect(self):\n room_name = \"test_room\"\n room = await self.create_room(room_name)\n\n communicator = WebsocketCommunicator(ChatConsumer.as_asgi(), f\"/ws/{room_name}/\")\n connected, _ = await communicator.connect()\n\n self.assertTrue(connected)\n\n await communicator.disconnect()\n\n","repo_name":"Rayzler/game_chat","sub_path":"roomApp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"22875646523","text":"# -*- coding:utf-8 -*-\n\nimport os\nimport json\nimport time\nimport random\nimport traceback\nimport subprocess\nfrom functools import wraps\nfrom retry import retry\nfrom datetime import datetime\n\nfrom .utils.email import send_email\nfrom .utils.file_util import new_file\nfrom .models import ScriptMission, EmailMission\nfrom . import db, redis, glogger\n\n\n\n\n# 定义需要重试的Exception\nclass NoFileException(Exception):\n pass\n\n# 定义捕获最大重试次数失败的装饰器\ndef max_retries_catch(func):\n @wraps(func)\n def decorater(comment):\n try:\n return func(comment)\n except NoFileException:\n mission = EmailMission.query.filter(EmailMission.comment == comment).first()\n mission.log(u\"Can't find new file which prefix is %s, have try %d times!\" \\\n % (mission.filename_prefix, db.app.config['RETRY_TIMES']), if_send_email=True)\n return decorater\n\n# 任务锁装饰器, 防止重复执行同一任务\ndef task_lock(func):\n @wraps(func)\n def decorater(comment):\n locking = False # 只有上锁的进程有资格去解锁, 使用这个变量作为标记\n try:\n if (redis.get('task_%s' % comment) or '0') == '0':\n redis.set('task_%s' % comment, '1', ex=3600) # 上锁, 这个锁默认只会存在3600秒\n locking = True\n glogger.info('task_%s get lock' % comment)\n return func(comment)\n else:\n glogger.info('task_%s locking' % comment)\n except:\n glogger.error(traceback.format_exc())\n finally:\n if locking:\n redis.set('task_%s' % comment, '0')\n glogger.info('task_%s release lock' % comment)\n return decorater\n\n# 毫秒级随机延时避让装饰器(由于这个避让本身也可能导致任务重复执行,必须确保值较小)\ndef random_delay(min=150., max=300.):\n '''\n :param min: float, 随机避让最小时长,单位:毫秒 \n :param max: float, 随机避让最大时长,单位:毫秒\n '''\n def decorater_1(func):\n @wraps(func)\n def decorater_2(*args, **kwargs):\n time.sleep(random.uniform(min/1000., max/1000.))\n return func(*args, **kwargs)\n return decorater_2\n return decorater_1\n\n\n\n# 执行脚本并且发送邮件\n@random_delay(min=0., max=3000.)\n@task_lock\ndef script_task(comment):\n app = db.app\n with app.app_context():\n start_time = datetime.now()\n mission = ScriptMission.query.filter(ScriptMission.comment==comment).first()\n if not mission:\n return\n filename = os.path.join(app.config['UPLOADED_SCRIPTS_DEST'], mission.filename)\n statement_direction = os.path.join(app.config['SCRIPT_MISSION_DIRECTION'], mission.comment)\n popen_instance = subprocess.Popen('python %s %s' % (filename, statement_direction),\n shell=True,\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE)\n out, err = popen_instance.communicate()\n retcode = popen_instance.poll()\n if not retcode:\n # 仅执行脚本不发送邮件\n if mission.content.strip().startswith('<%no_email%>'):\n mission.update() # 顺利完成后\n mission.log(u'Successful(without send email)!', start_time)\n return\n\n # 执行脚本且发送邮件\n file = new_file(statement_direction, mission)\n if not file:\n mission.log(u\"can't find new statement\", start_time, if_send_email=True)\n return\n if redis.get('task_%s' % comment) == '1': # 如果任务还是不慎多次执行只能在发送邮件时尽量减少重复发送的可能\n send_email(app, mission, mission.caption, mission.content, json.loads(mission.recipient), json.loads(mission.cc), file)\n mission.update() # 顺利完成后\n mission.log(u'Successful!', start_time)\n else:\n mission.log(u'It seems the mission has executed ever!', start_time)\n return\n elif retcode > 0:\n # error\n mission.log(err, start_time, if_send_email=True)\n elif retcode < 0:\n # killed\n mission.log(u'mission was killed by other process(kill signal %s)' % -retcode, start_time, if_send_email=True)\n\n# 从特定路径获取\n@random_delay(min=0., max=3000.)\n@task_lock\n@max_retries_catch\n@retry(NoFileException, tries=db.app.config['RETRY_TIMES'], delay=db.app.config['RETRY_INTERVAL'])\ndef email_task(comment):\n app = db.app\n with app.app_context():\n mission = EmailMission.query.filter(EmailMission.comment == comment).first()\n if not mission:\n return\n file = new_file(app.config['EMAIL_MISSION_DIRECTION'], mission)\n if not file:\n raise NoFileException(\"Can't find new file which prefix is '%s'\" % mission.filename_prefix)\n if redis.get('task_%s' % comment) == '1': # 如果任务还是不慎多次执行只能在发送邮件时尽量减少重复发送的可能\n send_email(app, mission, mission.caption, mission.content, json.loads(mission.recipient), json.loads(mission.cc), file)\n mission.update()\n mission.log(u'Successful!')\n else:\n mission.log(u'It seems the mission has executed ever!')\n return\n\n\n\n\n\n\n","repo_name":"xxxx-hhhh/my_email_center","sub_path":"app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"3742405607","text":"from viber.utils.database import ViberDB\n\n\nclass MajilisCollection:\n @staticmethod\n async def majilis_updates_from_scheduler(collection, name, link, status, summary):\n collection = getattr(ViberDB(), collection)\n if not collection.search(ViberDB().query.link == link):\n collection.insert(\n {\n 'name': name,\n 'link': link,\n 'status': f\"މިހާރު އޮތް ހިސާބް: {status}\",\n 'summary': summary\n }\n )\n\n @staticmethod\n async def majilis_return_collection(collection):\n collection = getattr(ViberDB(), collection)\n documents = collection.all()\n data = []\n for document in documents:\n _data = {\n 'name': document['name'],\n 'link': document['link'],\n 'status': document['status'],\n 'summary': document['summary']\n }\n data.append(_data)\n\n return data\n","repo_name":"baivaru/aiohttp_viber","sub_path":"viber/utils/database/majilis_collection.py","file_name":"majilis_collection.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"83"} +{"seq_id":"38419860031","text":"import nltk\nimport nltk.book as book\nimport string\n\n# Let's do frequency analysis for book 1 (Moby Dicke)\ntext1 = book.text1\nconcatenated_text = ''.join(text1)\ndis = nltk.FreqDist(concatenated_text)\n# dis.plot()\n\n# Now we can get the bigrams\naux = nltk.bigrams(text1)\nbigram_frequency = nltk.FreqDist(aux)\nprint('Most common bigrams')\nprint(bigram_frequency.most_common(20)) # Now we print the most common bigrams\n\n","repo_name":"h-mayorquin/nlp_testing","sub_path":"1_chapter.py","file_name":"1_chapter.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"7599036917","text":"import keyword\nfrom pathlib import Path\nimport sys\n\nimport pytest\n\nfrom hopic.template.utils import (\n command,\n module_command,\n)\n\n\ndef test_args_only():\n assert command(\"cmd\") == (\"cmd\",)\n assert command(\"cmd\", 1) == (\"cmd\", \"1\")\n assert command(\"cmd\", \"a\") == (\"cmd\", \"a\")\n assert command(\"cmd\", 1, 2, 3, \"a\", \"b\", \"c\") == (\"cmd\", \"1\", \"2\", \"3\", \"a\", \"b\", \"c\")\n\n\ndef test_bool_kwargs_only():\n assert command(\"cmd\", first=True, second=True) == (\"cmd\", \"--first\", \"--second\")\n assert command(\"cmd\", second=True, first=True) == (\"cmd\", \"--second\", \"--first\")\n assert command(\"cmd\", first=False, second=True) == (\"cmd\", \"--second\")\n assert command(\"cmd\", first=True, second=False) == (\"cmd\", \"--first\")\n\n\ndef test_list_kwargs():\n assert command(\"cmd\", puppet=(\"Woody\", \"Buzz\")) == (\"cmd\", \"--puppet\", \"Woody\", \"--puppet\", \"Buzz\")\n assert command(\"cmd\", puppet=[\"Buzz\", \"Woody\"]) == (\"cmd\", \"--puppet\", \"Buzz\", \"--puppet\", \"Woody\")\n\n\ndef test_short_kwargs():\n assert command(\"cmd\", x=True, v=True, f=Path(\"some/archive.tar\")) == (\"cmd\", \"-x\", \"-v\", \"-f\", \"some/archive.tar\")\n assert command(\"cmd\", f=(True, True), v=True) == (\"cmd\", \"-f\", \"-f\", \"-v\")\n\n\ndef test_str_coercion():\n assert command(\"cmd\", Path(\"over/here.txt\"), include=(Path(\"somewhere/else.txt\"), Path(\"some/other/place.txt\"))) == (\n \"cmd\",\n *(\"--include\", \"somewhere/else.txt\"),\n *(\"--include\", \"some/other/place.txt\"),\n \"over/here.txt\",\n )\n\n assert command(\"cmd\", 0, arg=1, args=(2, True)) == (\"cmd\", \"--arg\", \"1\", \"--args\", \"2\", \"--args\", \"0\")\n\n\n@pytest.mark.parametrize(\"keyword\", keyword.kwlist)\ndef test_keyword_opts(keyword):\n if keyword.startswith(\"_\"):\n pytest.skip(\"Ignoring keywords starting with underscores as we don't support those currently.\")\n\n try:\n call = compile(f\"command('cmd', {keyword}=True)\", filename=\"\", mode=\"eval\")\n except SyntaxError:\n call = compile(f\"command('cmd', _{keyword}=True)\", filename=\"\", mode=\"eval\")\n\n assert eval(call) == (\"cmd\", f\"--{keyword}\")\n\n\ndef test_opt_like_args():\n assert command(\"cmd\", Path(\"-cons.txt\"), Path(\"+pros.txt\"), evaluate=True) == (\"cmd\", \"--evaluate\", \"--\", \"-cons.txt\", \"+pros.txt\")\n\n\ndef test_list_command():\n assert command((\"git\", \"add\"), Path(\"a.txt\"), Path(\"b.txt\"), u=True) == (\"git\", \"add\", \"-u\", \"a.txt\", \"b.txt\")\n\n\ndef test_module_command():\n assert module_command(__name__, 1, 2, verbose=True) == (sys.executable, \"-m\", \"hopic.test.test_template_utils\", \"--verbose\", \"1\", \"2\")\n assert module_command((__name__, \"sub\"), 1, verbose=True) == (sys.executable, \"-m\", \"hopic.test.test_template_utils\", \"sub\", \"--verbose\", \"1\")\n","repo_name":"tomtom-international/hopic","sub_path":"hopic/test/test_template_utils.py","file_name":"test_template_utils.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"83"} +{"seq_id":"8389689956","text":"import json\nimport falcon\nfrom familienmitglied.familienmitgliedService import FamilienmitgliedService\n\n#Beschreibung der CRUD-Operationen für die folgenden Endpunkte in einem Netzwerk:\nclass FamilienmitgliedRessource:\n\n #Gibt alle Familienmitglieder zurück:\n def on_get_familienmitglieder(self, req, resp):\n familienmitgliedlist = FamilienmitgliedService.get_familienmitglieder()\n resp.text = json.dumps([f.to_dict() for f in familienmitgliedlist], ensure_ascii=False, indent=2)\n resp.status = falcon.HTTP_200\n\n #Gibt ein Familienmitglied basiert auf der ID zurück:\n def on_get_familienmitglied(self, req, resp, id_familienmitglied):\n resp.text=None\n f = FamilienmitgliedService.get_familienmitglied(int(id_familienmitglied))\n resp.text = json.dumps(f.to_dict(), ensure_ascii=False, indent=2)\n resp.status = falcon.HTTP_200\n\n #Hinzufügen eines Familienmitglieds:\n def on_post_familienmitglied(self, req, resp):\n familienmitglied_json = json.load(req.bounded_stream)\n FamilienmitgliedService.create_familienmitglied(familienmitglied_json)\n resp.text = \"Familienmitglied erfolgreich hinzugefügt.\"\n resp.status = falcon.HTTP_201\n resp.content_type = falcon.MEDIA_TEXT\n\n #Familienmitglied aktualisieren:\n def on_put_familienmitglied(self, req, resp, id_familienmitglied):\n familienmitglied_json = json.load(req.bounded_stream)\n FamilienmitgliedService.update_familienmitglied(id_familienmitglied, familienmitglied_json)\n resp.text = \"Familienmitglied erfolgreich aktualisiert.\"\n resp.status = falcon.HTTP_OK\n resp.content_type = falcon.MEDIA_TEXT\n\n #Löschen eines Familienmitglieds:\n def on_delete_familienmitglied(self, req, resp, id_familienmitglied):\n FamilienmitgliedService.delete_familienmitglied(id_familienmitglied)\n resp.text = \"Familienmitglied erfolgreich gelöscht.\"\n resp.status = falcon.HTTP_OK\n resp.content_type = falcon.MEDIA_TEXT\n\n #Priorität hinzufügen(d.h.Familienmitglied kann wählen):\n def on_post_priorisiert(self,req,resp):\n priorisiert_json = json.load(req.bounded_stream)\n FamilienmitgliedService.create_priorisiert(priorisiert_json)\n resp.text = \"Priorität erfolgreich hinzugefügt.\"\n resp.status = falcon.HTTP_201\n resp.content_type = falcon.MEDIA_TEXT\n\n\n","repo_name":"AlexandraBiju/HolidayPlannerProject","sub_path":"MyHolidayFamiliyPlaner/familienmitglied/familienmitgliedRessource.py","file_name":"familienmitgliedRessource.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"11959330629","text":"# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = 'dav-tools'\ncopyright = '2023, Davide Ponzini'\nauthor = 'Davide Ponzini'\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'autoapi.extension',\n # 'sphinx.ext.inheritance_diagram',\n # 'autoapi.sphinx',\n]\n\ntemplates_path = ['_templates']\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'alabaster'\nhtml_static_path = ['_static']\n\n\n# -- Autoapi -----------------------------------------------------------------\nautoapi_dirs = ['../src']\nautodoc_typehints = 'description'\nautoapi_options = [ 'members', 'private-members', 'show-inheritance', 'show-module-summary', 'special-members', 'imported-members', ]\n","repo_name":"DavidePonzini/dav-tools","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"14344362564","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# :license LASR_UC3M v1.0, ver LICENCIA.txt\n\n# Este programa es software libre: puede redistribuirlo y/o modificarlo\n# bajo los terminos de la Licencia Academica Social Robotics Lab - UC3M\n# publicada por la Universidad Carlos III de Madrid, tanto en su version 1.0\n# como en una version posterior.\n\n# Este programa se distribuye con la intencion de que sea util,\n# pero SIN NINGUNA GARANTIA. Para mas detalles, consulte la\n# Licencia Academica Social Robotics Lab - UC3M version 1.0 o posterior.\n\n# Usted ha recibido una copia de la Licencia Academica Social\n# Robotics Lab - UC3M en el fichero LICENCIA.txt, que tambien se encuentra\n# disponible en .\n\"\"\"\nAverages ouput from ocular's learner_recognizer_node.\n\n:author: Victor Gonzalez-Pacheco\n\"\"\"\n# from itertools import chain, islice\n# from toolz import frequencies\n# import pandas as pd\n\nimport roslib\nroslib.load_manifest('ocular_active_learning')\nimport rospy\nfrom rospy import (Publisher, Subscriber)\nfrom rospy import loginfo\n\nfrom ocular_active_learning import al_utils as alu\n\nfrom ocular.msg import SystemOutput\nfrom ocular_msgs.msg import AccumulatedPredictions as Predictions\n\n\nclass Estimator(object):\n\n \"\"\"\n Estimator Node: publishes object_id estimations once a second.\n\n It subscribes to the accumulated predictions topic and produces estimations\n of the object_id each second from these accumulated predictions.\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n rospy.init_node('ocular_object_id_averager', anonymous=True)\n self.node_name = rospy.get_name()\n rospy.on_shutdown(self.shutdown)\n loginfo(\"Initializing \" + self.node_name + \" node...\")\n\n # Publishers and Subscribers\n Subscriber(\"predictions\", Predictions, self.callback)\n self.pub = Publisher('final_object_id', SystemOutput)\n\n def callback(self, predictions):\n \"\"\"Callback that publishes updated predictions when new msg is recv.\"\"\"\n y, y_rgb, y_pcloud = alu.estimate(predictions.rgb, predictions.pcloud)\n output_msg = SystemOutput(id_2d_plus_3d=y, id_2d=y_rgb, id_3d=y_pcloud)\n try:\n self.pub.publish(output_msg)\n except ValueError as ve:\n rospy.logwarn(str(ve))\n\n def run(self):\n \"\"\"Run (wrapper of ``rospy.spin()``.\"\"\"\n rospy.spin()\n\n def shutdown(self):\n \"\"\"Shudown hook to close the node.\"\"\"\n loginfo('Shutting down ' + rospy.get_name() + ' node.')\n\n\nif __name__ == '__main__':\n try:\n node = Estimator()\n node.run()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"UC3MSocialRobots/ocular_project","sub_path":"ocular_active_learning/nodes/ocular_estimator.py","file_name":"ocular_estimator.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"30879507582","text":"\"\"\"\r\nDescription: auxiliary scripts\r\n document = Document('Задание.docx')\r\n all_paragraphs = document.paragraphs\r\n desc_task = document.paragraphs\r\n for p in desc_task:\r\n print(p.text.encode('utf-8'))\r\n with open(\"Пример ответа.json\", \"r\") as read_file:\r\n data_example_answer = json.load(read_file)\r\n print('EXAMPLE ANSWER:', data_example_answer)\r\n print('MY RESULT END :', my_result_end)\r\n\r\nEXAMPLE_CLASS\r\nclass AnswerToQuestion(Dict):\r\n\t''' AnswerOnQuestion '''\r\n\tdef __init__(self, data):\r\n\t\tDict.__init__().super()\r\n\t\tname = 'name_model'\r\n\t\tmodel = data\r\n\t\t\r\n\tdef __str__(self):\r\n\t\treturn self.name\r\n\r\nprint(\r\n f'count years: {count_years}',\r\n f\"of leap years are: {response_leap}\",\r\n sep='\\n',\r\n )\r\n\"\"\"\r\nimport json\r\nimport os\r\nfrom addict import Dict\r\nfrom docx import Document\r\nimport pandas as pd\r\nimport datetime\r\nimport calendar\r\nfrom data_to import data_to_resp\r\n\r\npath = os.getcwd()\r\npath_files = os.walk(__file__)\r\n\r\n\r\ndef find_leap_year(age):\r\n \"\"\"\"\"\"\r\n answer_by_y = 0\r\n years = range((int(current_year) - int(age)), int(current_year))\r\n count_years = len(years)\r\n for year in years:\r\n if calendar.isleap(int(year)):\r\n answer_by_y = answer_by_y + 1\r\n return answer_by_y, count_years\r\n\r\n\r\nwith open(\"DataSet.json\", \"r\") as read_file:\r\n data = json.load(read_file)\r\n\r\naddi_data = Dict(data_to_resp)\r\n# answer = dict()\r\n\r\nanswer_keys = [\r\n\t'result', \r\n\t'client', \r\n\t'rules', \r\n\t'arrayLiability',\r\n\t]\r\n\r\nall_clients_id = list(addi_data.client.keys())\r\n\r\nmy_result = dict()\r\n\r\nname_credit_history = ['В', 'G', 'N', 'E']\r\n\r\nname_rules = [\r\n\t'rule_1', \r\n\t'rule_2', \r\n\t'rule_3', \r\n\t'rule_4', \r\n\t'rule_5',\r\n\t]\r\n\r\nmin_age = 18\r\nmax_age = 55\r\ncheck_status = 'RU'\r\ncheck_days_reg = 180\r\n\r\ncurrent_year = datetime.datetime.now().strftime('%Y')\r\ntoday = datetime.date.today()\r\n\r\nfor i, iclient in enumerate(all_clients_id, 1):\r\n countOpenLiability = 0\r\n countCloseLiability = 0\r\n rules_by_client = [] # to fill in the list of rules that worked for the client\r\n array_liability = [] # to fill in the list of the client's unique liability\r\n \r\n surname = (addi_data.client[iclient].name).split(' ')\r\n surname_birthday = '|'.join([surname[0], addi_data.client[iclient].birthday])\r\n \r\n app_no = addi_data.dataLiability.appNO[iclient] # list liability\r\n \r\n date_start = addi_data.dataLiability.dateStart[iclient] # список дат начала обязательств\r\n date_end = addi_data.dataLiability.dateEnd[iclient] # список дат окончания обязательств\r\n sum_delay = 0 # sum(addi_data.dataLiability.sumDelay[iclient]) # сумма просрочки\r\n \r\n for ia, app in enumerate(app_no):\r\n \tif surname_birthday == addi_data.dataLiability.appOwner[iclient][ia]:\r\n \t\tarray_liability.append(app)\r\n \t\t\r\n \t\tif date_end[ia] == '' :\r\n \t\t\tcountOpenLiability += 1\r\n \t\t\tsum_delay += addi_data.dataLiability.sumDelay[iclient][ia]\r\n \t\telif date_end[ia] != '':\r\n\t \t\tsy = int(date_start[ia][-4:])\r\n\t \t\tsm = int(date_start[ia][3:5])\r\n\t \t\tsd = int(date_start[ia][:2])\r\n\t \t\t\r\n\t \t\tey = int(date_start[ia][-4:])\r\n\t \t\tem = int(date_end[ia][3:5])\r\n\t \t\ted = int(date_end[ia][:2])\r\n \t\t\t\r\n \t\t\tif datetime.datetime(sy, sm, sd) < datetime.datetime(ey, em, ed) or date_end[ia] != '':\r\n \t\t\t\tcountCloseLiability += 1 \r\n\r\n # DEFINITION / DETERMINATION OF THE RESIDENT STATUS\r\n statusCHIP = addi_data.client[iclient]['citizenship']\r\n if statusCHIP != check_status:\r\n rules_by_client.append(name_rules[0]) \r\n \r\n # DEFINITION / DETERMINING THE CLIENT'S AGE\r\n birthday_ = addi_data.client[iclient].birthday[-4:]\r\n bdm = addi_data.client[iclient].birthday[3:5]\r\n bdd = addi_data.client[iclient].birthday[:2]\r\n \r\n age = int(current_year) - int(birthday_)\r\n convert_birthday = datetime.date(int(birthday_), int(bdm), int(bdd))\r\n age_full_days = (today - convert_birthday).days\r\n \r\n response_leap = find_leap_year(age)[0]\r\n age_full_year = (age_full_days - response_leap*366)/365 + response_leap\r\n \r\n if age_full_year < min_age:\r\n rules_by_client.append(name_rules[1])\r\n if age_full_year > max_age:\r\n rules_by_client.append(name_rules[2]) \r\n\r\n # DEFINITION / ASSESSMENT OF CREDIT HISTORY\r\n if sum_delay > 1000:\r\n credit_history = name_credit_history[0] # BAD\r\n elif sum_delay == 0 and countOpenLiability != 0 or countCloseLiability != 0:\r\n credit_history = name_credit_history[1] # GOOD\r\n elif 0 < sum_delay <= 1000 and countCloseLiability != 0:\r\n credit_history = name_credit_history[2] # MIDDLE\r\n else: # elif app_no == []:\r\n credit_history = name_credit_history[3] # EMPTY\r\n\r\n # DEFINITION / DETERMINIG THE REGISTRATION STATUS\r\n statusERGIP = addi_data.source.egripStatus[iclient] # definition of status ERGIP\r\n if int(statusERGIP) == 0:\r\n rules_by_client.append(name_rules[3]) \r\n \r\n # DEFINITION / TERM OF BUSINESS ACTIVITY\r\n dateREGIST = addi_data.source.dateRegistration[iclient]\r\n current_date = datetime.datetime.now().strftime('%d.%m.%Y')\r\n try:\r\n date_reg = datetime.datetime(int(dateREGIST[-4:]), int(dateREGIST[3:5]), int(dateREGIST[:2]))\r\n dateDELTA = (datetime.datetime.now() - date_reg).days\r\n if int(dateDELTA) < check_days_reg:\r\n rules_by_client.append(name_rules[4]) \r\n except TypeError:\r\n pass\r\n\r\n # FILLING IN THE RESULTS\r\n my_result.update(\r\n {f'client_{i}': {\r\n # 'surname_birthday': surname_birthday,\r\n # 'response_leap': response_leap,\r\n # 'age_full': age_full_year,\r\n # 'response_count_leap': response_count_leap,\r\n 'rules': rules_by_client,\r\n 'countOpenLiability': countOpenLiability,\r\n 'countCloseLiability': countCloseLiability,\r\n 'sumDelays': sum_delay,\r\n 'statusCH': credit_history,\r\n 'arrayLiability': array_liability, # list(set(app_no)),\r\n }}\r\n ) \r\n\r\nmy_result_end = dict({'result': {'client': my_result}})\r\nprint('MY RESULT END:\\n', my_result_end)\r\n","repo_name":"mikon666/public_answer_task_new_job","sub_path":"tasknewjob210119-2339.py","file_name":"tasknewjob210119-2339.py","file_ext":"py","file_size_in_byte":6267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"24789027309","text":"import tensorflow as tf\n# from tensorflow.keras.callbacks import CSVLogger, EarlyStopping\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport seaborn as sns\nimport time\nimport gc\nimport sys\n\nmpl.rcParams['figure.figsize'] = (17, 5)\nmpl.rcParams['axes.grid'] = False\nsns.set_style(\"whitegrid\")\n\nnotebookstart= time.time()\n\n\n# Data Loader Parameters\nBATCH_SIZE = 256\nBUFFER_SIZE = 10000\nTRAIN_SPLIT = 300000\n\n# LSTM Parameters\nEVALUATION_INTERVAL = 200\nEPOCHS = 4\nPATIENCE = 5\n\n# Reproducibility\nSEED = 13\ntf.random.set_seed(SEED)\n\nzip_path = tf.keras.utils.get_file(\n origin='https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip',\n fname='jena_climate_2009_2016.csv.zip',\n extract=True)\ncsv_path, _ = os.path.splitext(zip_path)\n\ndf = pd.read_csv(csv_path)\nprint(\"DataFrame Shape: {} rows, {} columns\".format(*df.shape))\n# print(df.head())\n\ndef univariate_data(dataset, start_index, end_index, history_size, target_size):\n # history size of past window information in 10 min increments\n # target size how far in the future model predict\n # target size is the label that needs to be predicted\n\n data = []\n labels = []\n\n start_index = start_index + history_size\n if end_index is None:\n end_index = len(dataset) - target_size\n\n for i in range(start_index, end_index):\n indices = range(i - history_size, i)\n # Reshape data from (history_size,) to (history_size, 1)\n data.append(np.reshape(dataset[indices], (history_size, 1)))\n labels.append(dataset[i + target_size])\n\n return np.array(data), np.array(labels)\n\n\n# Part 1: forecast using only a single feature\n\nuni_data = df['T (degC)']\nuni_data.index = df['Date Time']\n# print(uni_data.head())\n#\n# uni_data.plot(subplots=True)\n# plt.show()\nuni_data = uni_data.values\n\n# scaling features\nuni_train_mean = uni_data[:TRAIN_SPLIT].mean()\nuni_train_std = uni_data[:TRAIN_SPLIT].std()\nuni_data = (uni_data-uni_train_mean)/uni_train_std\n\nunivariate_past_history = 20\nunivariate_future_target = 0\n\nx_train_uni, y_train_uni = univariate_data(dataset=uni_data,\n start_index=0,\n end_index=TRAIN_SPLIT,\n history_size=univariate_past_history,\n target_size=univariate_future_target)\n\nx_val_uni, y_val_uni = univariate_data(dataset=uni_data,\n start_index=TRAIN_SPLIT,\n end_index=None,\n history_size=univariate_past_history,\n target_size=univariate_future_target)\n\n# # This is what uni-variate data returns\n# print(\"In:\")\n# print(uni_data.shape)\n# print(uni_data[:5])\n#\n# print(\"\\nOut\")\n# print(x_train_uni.shape)\n#\n#\n# print(x_train_uni.shape[0] / uni_data.shape[0])\n#\n# print ('Single window of past history. Shape: {}'.format(x_train_uni[0].shape))\n# print (x_train_uni[0])\n# print ('\\n Target temperature to predict. Shape: {}'.format(y_train_uni[0].shape))\n# print (y_train_uni[0])\n#\n# print('type', type(x_train_uni))\n\ndef create_time_steps(length):\n return list(range(-length, 0))\n\n\ndef show_plot(plot_data, delta, title):\n labels = ['History', 'True Future', 'Model Prediction']\n marker = ['.-', 'rx', 'go']\n time_steps = create_time_steps(plot_data[0].shape[0])\n if delta:\n future = delta\n else:\n future = 0\n\n plt.title(title)\n for i, x in enumerate(plot_data):\n if i:\n plt.plot(future, plot_data[i], marker[i], markersize=10,\n label=labels[i])\n else:\n plt.plot(time_steps, plot_data[i].flatten(), marker[i], label=labels[i])\n plt.legend()\n plt.xlim([time_steps[0], (future + 5) * 2])\n plt.xlabel('Time-Step')\n\n return plt.show()\n\n# show_plot([x_train_uni[0], y_train_uni[0]], 0, 'Sample Example')\n\n# Baseline is the mean of the past window\n\ndef baseline(history):\n return np.mean(history)\n\n# show_plot([x_train_uni[0], y_train_uni[0], baseline(x_train_uni[0])], 0,\n# 'Baseline Prediction Example')\n\n\ntrain_univariate = tf.data.Dataset.from_tensor_slices((x_train_uni, y_train_uni))\ntrain_univariate = train_univariate.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()\n\nval_univariate = tf.data.Dataset.from_tensor_slices((x_val_uni, y_val_uni))\nval_univariate = val_univariate.batch(BATCH_SIZE).repeat()\n\n# print(x_train_uni.shape)\n# print(type(x_train_uni))\n# print(type(train_univariate))\n\nsimple_lstm_model = tf.keras.models.Sequential([\n tf.keras.layers.LSTM(8, input_shape=x_val_uni.shape[-2:]),\n tf.keras.layers.Dense(1)\n])\n\nsimple_lstm_model.compile(optimizer='adam', loss='mae')\n# print(simple_lstm_model.summary())\n\n# sample prediction\nfor x, y in val_univariate.take(1):\n print(simple_lstm_model.predict(x).shape)\n\nearly_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)\n\nsimple_lstm_model.fit(train_univariate,\n epochs=EPOCHS,\n steps_per_epoch=EVALUATION_INTERVAL,\n validation_data=val_univariate,\n callbacks=[early_stopping],\n validation_steps=50)\n\n\nfor x, y in val_univariate.take(3):\n plot = show_plot([x[0].numpy(), y[0].numpy(),\n simple_lstm_model.predict(x)[0]], 0, 'Simple LSTM model')\n plt.show()","repo_name":"ToastyBunz/TensorFlowStudy","sub_path":"Handling_Data/Timeseries_MD1_1in1out.py","file_name":"Timeseries_MD1_1in1out.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"6876876905","text":"# ## @author: Eduarda Centeno\n#### @modified: Remya Sankar\n# # Documentation for this module.\n# #\n# # Created on Wed Feb 6 15:06:12 2019; -*- coding: utf-8 -*-; \n\n\n# #################################################################################################################################\n# #################################################################################################################################\n# # This code was built with the aim of allowing the user to work with Spike2 .smr files and further perfom correlation analyses ##\n# # between specific acoustic features and neuronal activity. ##\n# # In our group we work with Zebra finches, recording their neuronal activity while they sing, so the parameters here might ##\n# # have to be ajusted to your specific data. ## ##\n# #################################################################################################################################\n# #################################################################################################################################\n\n# ### Necessary packages\nimport neo\nimport numpy as np\nimport os\n\n\n\n# ##############################################################################################################################\n# # From now on there will be the core functions of this code, which will be individually documented: #\n# #\n\n\ndef read(file):\n \"\"\"# # This function will allow you to read the .smr files from Spike2.\"\"\"\n\n block_neo = neo.io.CedIO(file)\n\n seg_neo = block_neo.read_segment(lazy=True, signal_group_mode=\"split-all\")\n\n return block_neo, seg_neo\n # return data, data_seg\n\n\ndef getsong(file, songChannelName):\n \"\"\"\n Extracts song from smr/smrx file and saves in npy format.\n Compatible with neo v0.10\n \"\"\"\n\n block_neo, seg_neo = read(file) # Reads smr file\n\n n_analogs = seg_neo.size[\"analogsignals\"]\n\n for index in range(n_analogs):\n if seg_neo.analogsignals[index].name == songChannelName:\n\n analog_index = index\n songData = seg_neo.analogsignals[analog_index].load().as_array()\n np.save(os.path.dirname(file) + \"/\" + songChannelName + \"_Songfile.npy\", songData)\n print(\"Songfile saved in \", os.path.dirname(file) + \"/\" + songChannelName + \"_Songfile.npy\")\n\n break\n","repo_name":"rsankar9/HVCHackathon","sub_path":"Scripts/songbird_data_analysis/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"21401865551","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom .models import userProfile, User\n\n\n\"\"\"\n we want the profile to be created when the user is created this process is done by using signals\n signals are functions that are executed when a certain event occurs like saving some record in the database\n this means that when a new instance of user is saved in the database then the signal functions will be executed\n every signal function has a sender and a receiver\n the sender is the model that sends the signal\n the receiver is the function that will be executed when the signal is sent\n ....................................................................................................\n we have two ways for connecting the sender and receiver first is:\n post_save.connect(post_save_create_profile_receiver, sender=User)\n and second is to use a decorator receiver as following:\n\"\"\"\n\n\n@receiver(post_save, sender=User)\ndef post_save_create_profile_receiver(sender: User, instance: User, created: bool, **kwargs) -> None:\n \"\"\"\n this function will check if the user is created or not if created was True\n the function will create a new profile with that user so the instance is actually the user\n but if we just wanted to update a user info we dont want to create a new profile\n then we just update the changes to the user profile in the else block\n .....................................................................................\n there is one more scenario where we dont have a profile but we update the user instance\n in this case we first try to update the user profile as we did before but if the profile\n doesn't exist then we just create a new profile using that instance we get from the User model\n \"\"\"\n\n if created:\n userProfile.objects.create(user=instance)\n else:\n try:\n profile = userProfile.objects.get(user=instance)\n profile.save()\n\n except userProfile.DoesNotExist:\n userProfile.objects.create(user=instance)\n","repo_name":"mbijanpour/Store-X","sub_path":"accounts/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"31017765349","text":"import os\n\n#This import is needed for VIP\nfrom oauth2client.client import OAuth2WebServerFlow\n\n#These are generally useful\nCSRF_ENABLED = True\nSECRET_KEY = os.getenv('SECRET_KEY')\n\n#These variables configure the DECC scripts\ndeccinputdir = os.getenv('DECCINPUT')\ndeccoutputdir = os.getenv('DECCOUTPUT')\nHOST = os.getenv('PGHOST')\nUSER = os.getenv('PGUSER')\nDB = os.getenv('PGDB')\nPASSWORD = os.getenv('PGPASSWORD')\n\n#These are all VIP Variables\napi_id = os.getenv('GOOGLE_NATIVE_APP_CLIENT_ID')\napi_secret = os.getenv('GOOGLE_NATIVE_APP_CLIENT_SECRET')\napi_key = os.getenv('GOOGLE_PUBLIC_API_KEY')\ngeokey = os.getenv('GOOGLE_GEOCODE_API_KEY')\nvip_qa_data = os.getenv('VIPQADATA')\nev_qa_data = os.getenv('EVIPQADATA')\nstates = {'AL': 'Alabama', 'AR': 'Arkansas', 'AZ': 'Arizona', 'ME': 'Maine',\n 'NH': 'New Hampshire', 'TN': 'Tennessee', 'LA': 'Louisiana',\n 'IL': 'Illinois', 'IN': 'Indiana', 'ID': 'Idaho', 'GA': 'Georgia',\n 'MA': 'Massachusetts', 'SD': 'South Dakota', 'VT': 'Vermont',\n 'FL': 'Florida', 'MS': 'Mississippi', 'KY': 'Kentucky',\n 'TX': 'Texas', 'SC': 'South Carolina', 'WV': 'West Virginia',\n 'NM': 'New Mexico'}\nscope1 = 'https://spreadsheets.google.com/feeds'\nscope2 = 'https://www.googleapis.com/auth/drive'\nscope = '{0} {1}'.format(scope1, scope2)\nredirect = os.getenv('AUTH_REDIRECT')\nflow = OAuth2WebServerFlow(client_id=api_id,\n client_secret=api_secret,\n scope=scope,\n redirect_uri=redirect)\nvipTemplateKey = '1qcqHBizQeFJwXsORMS_QS59gywuT9TRifwQe4BM_G3E'\nevTemplateKey = '1_uEKMFrFxfu69Ws-2QbmUPm1kFNMY5txGJzG8bfzK4s'\n","repo_name":"mlambright/EA-Tools","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"11282257623","text":"import numpy as np\n\nfrom .aggregations import AggregationMostRecent\nfrom .models import MissionContext, MessageSet, Message, InformationType\nfrom .utilities import UtilityBattery, UtilityPosition\nfrom .message_forecast import FullKnowledgeTypeForecast, PeriodicTypeForecast # NOQA\n\nBATTERY_DATA_TYPE = 'batt'\nPOSITION_DATA_TYPE = 'position'\n\npresets = [\n {\n 'ident': 0,\n 'max_depl_rate_mi': lambda: np.random.normal(0.2, 0.2),\n 'max_depl_rate': lambda mi: max(0.003, np.random.normal(mi, 0.001)),\n 't_gen': lambda t: abs(np.random.normal(t, 0.1)),\n 'topic_weight': lambda i: 3**(i+1),\n # 'message_size': lambda i: 2048 - i*25,\n 'message_size': lambda i: 2048,\n },\n {\n 'ident': 1,\n 'max_depl_rate_mi': lambda: np.random.normal(0.3, 0.01),\n 'max_depl_rate': lambda mi: max(0.003, np.random.normal(mi, 0.001)),\n 't_gen': lambda t: abs(np.random.normal(t, 0.001)),\n 'topic_weight': lambda i: i*1000+1,\n 'message_size': lambda i: 2048,\n },\n {\n 'ident': 2,\n 'max_depl_rate_mi': lambda: 0.7,\n 'max_depl_rate': lambda mi: mi,\n 't_gen': lambda t: t,\n 'topic_weight': lambda i: i**(0.1)+1,\n 'message_size': lambda i: 2048,\n },\n {\n 'ident': 3,\n 'max_depl_rate_mi': lambda: np.random.normal(0.2, 0.2),\n 'max_depl_rate': lambda mi: max(0.003, np.random.normal(mi, 0.001)),\n 't_gen': lambda t: abs(np.random.normal(t, 0.1)),\n 'topic_weight': lambda i: 5,\n 'message_size': lambda i: 2048,\n },\n {\n 'ident': 4,\n 'max_depl_rate_mi': lambda: 0.3,\n 'max_depl_rate': lambda mi: mi,\n 't_gen': lambda t: abs(np.random.normal(t, 0.01)),\n 'topic_weight': lambda i: 5,\n 'message_size': lambda i: 2048,\n 't_start': lambda sender: sender/(8*6) + 1/(8*6)*0.2,\n 'f': lambda sender: 6,\n },\n {\n 'ident': 5,\n 'max_depl_rate_mi': lambda: 0.3,\n 'max_depl_rate': lambda mi: mi,\n 't_gen': lambda t: abs(np.random.normal(t, 0.01)),\n 'topic_weight': lambda i: 5,\n 'message_size': lambda i: 2048,\n 't_start': lambda sender: sender/(8*6) + 1/(8*6)*0.2,\n 'f': lambda sender: 1,\n },\n {\n 'ident': 6,\n 'max_depl_rate_mi': lambda: 0.3,\n 'max_depl_rate': lambda mi: mi,\n 't_gen': lambda t: abs(np.random.normal(t, 0.01)),\n 'topic_weight': lambda i: 5,\n 'message_size': lambda i: 1900, # 2048,\n 't_start': lambda sender: (sender%4)/(4*10) + (\n sender // 4 * 25 + sender % 4 * 0\n ),\n 't_end': lambda t_end, sender: (\n sender // 4 * 25 + 25 - sender % 4 * 5\n # sender*20 + 45\n ),\n 'f': lambda sender: 10,\n 'seed': 0,\n },\n {\n 'ident': 7,\n 'max_depl_rate_mi': lambda: 0.3,\n 'max_depl_rate': lambda mi: mi,\n 't_gen': lambda t: abs(np.random.normal(t, 0.01)),\n 'topic_weight': lambda i: 5,\n 'message_size': lambda i: 2048,\n 't_start': lambda sender: (\n (sender % 4)/(4*10)\n # (sender % 2 * 4 + sender // 2)/(8*10)\n ) + (\n sender // 4 * 100 + sender % 4 * 5\n ),\n 't_end': lambda t_end, sender: (\n sender // 4 * 100 + 100 - sender % 4 * 5\n # sender*20 + 45\n ),\n 'f': lambda sender: 10\n },\n]\n\n\ndef generate_periodic_messages(\n t_end, sender, receivers, data_type_name,\n t_start=0, f=1, data_f=lambda t: {},\n msgset=0,\n append_sender_to_data_type_name=False,\n):\n def gen_data_type_name(sender):\n if append_sender_to_data_type_name:\n return data_type_name + str(sender)\n else:\n return data_type_name\n\n return MessageSet(t_end, [\n Message(\n sender,\n set(receivers) - set([sender]),\n msgset['t_gen'](t),\n gen_data_type_name(sender),\n msgset['message_size'](sender),\n data_f(t)\n )\n for t in np.arange(t_start, t_end, 1/f)\n ], t_start)\n\n\ndef generate_batt_messages(t_end, sender, receivers, t_start=0, f=1,\n level_start=1, level_end=0,\n msgset=0,\n ):\n\n mi = msgset['max_depl_rate_mi']()\n\n def batt_level(t):\n a = (level_start - level_end) / (t_start - t_end)\n b = level_end - a * t_end\n level = a*t+b\n return {\n 'battery_level': level,\n 'max_depl_rate': msgset['max_depl_rate'](mi),\n }\n\n messages = generate_periodic_messages(\n t_end, sender, receivers,\n BATTERY_DATA_TYPE, t_start, f, batt_level,\n msgset=msgset,\n append_sender_to_data_type_name=True,\n )\n\n full_knowledge = False\n if full_knowledge:\n forecast_cls = FullKnowledgeTypeForecast\n\n def forecast_kwargs(data_type_name):\n return {\n 'data_type_name': data_type_name,\n 'messages': messages,\n }\n else:\n forecast_cls = PeriodicTypeForecast\n\n def forecast_kwargs(data_type_name):\n return {\n 'data_type_name': data_type_name,\n 't_end': t_end,\n 'max_depl_rate': mi,\n 'battery_level': level_start,\n 'receivers': receivers,\n 'sender': sender,\n 'initial_t_start': t_start,\n 'T': 1/f,\n 'size': msgset['message_size'](sender),\n }\n\n return (\n messages,\n MissionContext(\n set([\n InformationType(\n data_type_name,\n utility_cls=UtilityBattery,\n aggregation_cls=AggregationMostRecent,\n message_forecast_cls=forecast_cls,\n message_forecast_kwargs=forecast_kwargs(data_type_name),\n weight=msgset['topic_weight'](sender),\n )\n for data_type_name in set(\n m.data_type_name\n for m in messages.all()\n )\n ])\n )\n )\n\n\ndef generate_pos_messages(t_end, sender, receivers, t_start=0, f=5):\n messages = generate_periodic_messages(\n t_end, sender, receivers, POSITION_DATA_TYPE, t_start, f,\n append_sender_to_data_type_name=True,\n )\n return (\n messages,\n MissionContext(set([\n InformationType(\n m.data_type_name,\n utility=UtilityPosition,\n aggregation=AggregationMostRecent,\n )\n for m in messages.all()\n ]))\n )\n\n\ndef generate_simple_3D_reconstruction(\n t_end, msgset=0, senders={0, 1}, receivers=None, seed=0,\n):\n if receivers is None:\n receivers = senders\n\n np.random.seed(seed)\n\n all_messages = MessageSet(t_end, [])\n all_contexts = MissionContext(set())\n\n for sender in senders:\n level_start = 1\n level_end = level_start\n # level_end = level_start * np.random.random()\n messages, context = generate_batt_messages(\n msgset.get(\n 't_end',\n lambda t_end, sender: t_end\n )(t_end, sender),\n sender, receivers,\n f=msgset.get(\n 'f',\n lambda _: np.random.normal(1, 0.1),\n )(sender),\n t_start=msgset.get(\n 't_start',\n lambda _: int(np.random.random())\n )(sender),\n level_start=level_start,\n level_end=level_end,\n msgset=msgset,\n )\n all_messages += messages\n all_contexts += context\n\n return all_messages, all_contexts\n\n\nif __name__ == \"__main__\":\n msgs, context = generate_simple_3D_reconstruction(22)\n print(msgs.messages.__str__(\n ['sender', 'receivers', 't_gen', 't_sent', 'data',\n 'data_type_name']))\n","repo_name":"zeroos/infdist","sub_path":"infdist/optimization/missions.py","file_name":"missions.py","file_ext":"py","file_size_in_byte":8008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"74455300112","text":"from pandas import Index,Series,DataFrame\nimport numpy as n\nx = Series(range(3), index=['a','b','c'])\n(x.index[:2])\n#result Index(['a', 'b'], dtype='object') 获取Index对象并进行切片处理\n\nindex = Index(n.arange(3))\nobj = Series([1.5,-2.5,0],index=index) # 构造Index(索引)对象\n# result\n# 0 1.5\n# 1 -2.5\n# 2 0.0\n# dtype: float64\n\nobj.index is index is True # obj.index ==> index <> Index\n\ndata = {'pop':{2.4, 2.9},\n 'year':{2001, 2002} }\nx = DataFrame(data) # 索引默认0和1\nprint('pop' in x.columns) # 判断列是否存在\nprint(1 in x.index) # 判断行索引是否存在\n# result\n# True\n# True","repo_name":"111ZhuXueke/django","sub_path":"pandasssss/Indexss.py","file_name":"Indexss.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"74957294352","text":"from graphblas import binary\n\n__all__ = [\"s_metric\"]\n\n\ndef s_metric(G):\n if G.is_directed():\n degrees = G.get_property(\"total_degrees+\")\n else:\n degrees = G.get_property(\"degrees+\")\n return (binary.first(degrees & G._A) @ degrees).reduce().get(0) / 2\n # Alternatives\n # return (degrees @ binary.second(G._A & degrees)).reduce().get(0) / 2\n # return degrees.outer(degrees).new(mask=G._A.S).reduce_scalar().get(0) / 2\n","repo_name":"python-graphblas/graphblas-algorithms","sub_path":"graphblas_algorithms/algorithms/smetric.py","file_name":"smetric.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"83"} +{"seq_id":"7559994423","text":"# -*- coding: utf-8 -*-\n# Created by restran on 2016/8/12\n\"\"\"\n验证码识别\n\"\"\"\n\nfrom __future__ import unicode_literals, absolute_import\nfrom io import BytesIO\nfrom PIL import Image\nimport re\nimport os\nimport pytesseract\n\n# 二值化,采用阈值分割法,threshold为分割点\nthreshold = 140\nbinary_table = []\nfor i in range(256):\n if i < threshold:\n binary_table.append(0)\n else:\n binary_table.append(1)\n\n# 由于都是数字\n# 对于识别成字母的 采用该表进行修正\nreplace_table = {\n 'O': '0',\n 'I': '1',\n 'L': '1',\n 'Z': '2',\n 'S': '8'\n}\n\n\ndef image_data_to_tiff(img, is_png=False):\n if is_png:\n img.load()\n # Make your background RGB, not RGBA\n # 将PNG转成JPG,PNG背景透明通道会干扰识别\n background = Image.new(\"RGB\", img.size, (255, 255, 255))\n background.paste(img, mask=img.split()[3]) # 3 is the alpha channel\n cf = BytesIO()\n background.save(cf, 'JPEG', quality=80)\n img = Image.open(cf)\n # 转换为灰度图\n img = img.convert('L')\n # img = binary_image(img)\n\n # 二值化\n img = img.point(binary_table, '1')\n # img.save('1.jpg')\n\n return img\n\n\ndef image_to_text(img, only_digits=False):\n text = pytesseract.image_to_string(img)\n text = re.sub('[\\W]', '', text)\n text = text.strip()\n if only_digits:\n text = text.upper()\n for r in replace_table:\n text = text.replace(r, replace_table[r])\n return text\n\n\ndef recognize(file_name=None, img=None, is_png=False, only_digits=False):\n if img is None:\n img = Image.open(file_name)\n return image_to_text(image_data_to_tiff(img, is_png), only_digits=only_digits)\n\n\ndef get_file_list(path):\n if path == \"\":\n return []\n return [x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]\n\n\ndef test_im(base_path):\n file_list = get_file_list(base_path)\n data_list = []\n result = 0\n for f in file_list:\n p = os.path.join(base_path, f)\n r = recognize(p, is_png=True, only_digits=True)\n print('%s:%s' % (p, r))\n data_list.append(r)\n a = int(f.replace('.png', ''))\n b = int(r)\n result += a * b\n print(result)\n print(result)\n return data_list\n\n\nif __name__ == '__main__':\n data = test_im('d://im')\n # result = recognize('d://im//10042.png')\n # print(result)\n","repo_name":"restran/hacker-scripts","sub_path":"captcha/pycaptcha.py","file_name":"pycaptcha.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"83"} +{"seq_id":"38430447871","text":"# SOCKETS RÉSEAU : SERVEUR\n#\n# socket\n# bind (ip, port) 127.0.0.1 -> localhost\n# listen\n# accept -> socket / (ip, port)\n# close\n\n# already used\n\nimport socket\n\nHOST_IP = \"127.0.0.1\"\nHOST_PORT = 32000\n\ns = socket.socket()\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((HOST_IP, HOST_PORT))\ns.listen()\n\nprint(f\"Attente de connexion sur {HOST_IP}, port {HOST_PORT}...\")\nconnection_socket, client_address = s.accept()\nprint(f\"Connexion établie avec {client_address}\")\n\n\ntexte_envoye = \"Bonjour\"\nconnection_socket.sendall(texte_envoye.encode())\n\n\ns.close()\nconnection_socket.close()","repo_name":"issemou/Chat_interpose_Python","sub_path":"5/sockets_serveur.py","file_name":"sockets_serveur.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"31723040388","text":"import json\nimport time\nimport sys, os\n\n#current = os.path.dirname(os.path.realpath(__file__))\n#parent = os.path.dirname(current)\n#sys.path.append(parent)\n#import sender.player as player\n#from utils import json_modify\nimport utils\n\nclass Lobby:\n ps1 = 0\n ps2 = 0\n\n def __init__(self, filename:str):\n self.filename = filename # file where the status will be saved\n\n def read_status(self, data:str) -> None:\n \"\"\"Read status of json string if both\n of them are ready (1) then update the file\"\"\"\n data = json.loads(data)['status']\n player_id = str(data[0]) \n status = data[1]\n if player_id == '1':\n self.ps1 = status\n elif player_id == '2':\n self.ps2 = status\n utils.json_modify(self.filename, player_id, status)\n\n def _return_dict(self) -> dict:\n \"\"\"Debugging purpose only\"\"\"\n return {\"1\":self.ps1, \"2\":self.ps2}\n\n def reset_dict(self) -> None:\n \"\"\"Reset back the file after the game end\"\"\"\n utils.json_modify(self.filename, \"1\", 0)\n utils.json_modify(self.filename, \"2\", 0)\n \n\nif __name__ == \"__main__\":\n lb = Lobby(\"../status.json\")\n data1 = '{\"status\": [1,1]}'\n lb.read_status(data1)\n time.sleep(1)\n print(lb._return_dict())\n data2 = '{\"status\": [2,0]}'\n lb.read_status(data2)\n time.sleep(1)\n print(lb._return_dict())\n data2 = '{\"status\": [2,1]}'\n lb.read_status(data2)\n time.sleep(1)\n print(lb._return_dict())\n lb.reset_dict()\n","repo_name":"entangle2giraffe/rainyword","sub_path":"reciever/lobby.py","file_name":"lobby.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"41040576395","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import special as esp\n\n#Ec is the Coulomb energy\n#L is the Lambda\n#g is the attraction\n# every energy is normalized to E_R = \\kappa*p0^2\n# every length is nomalized to 1/p0 \nc = 2 - 4*np.sqrt(2)/np.pi #is the constant in the coulomb aprox\nA = np.exp(1)*np.pi**(3/2)/(np.sqrt(2)*esp.gamma(5/4)**2)\nA = A.real #is the constant we need for L = 0\n\n\n'''DEFINING COULOMB FOR SPECIAL CASE OF NO SCREENING'''\n\ndef Coul(a):\n\tI = 4/(a*np.sqrt(1+a))*(esp.ellipk(2*a/(1+a+1e-15))\n\t\t\t\t-(1+a)*esp.ellipe(2*a/(1+a+1e-15)))\n\treturn I/(2*np.pi)\n\n\n''' BUILDING THE SOLVER '''\n\ndef solver(g, Ec, L):\n\n\t# this is critcal L in absence of Coulomb. here I'm using it as energy scale.\n\tLc0 = g**2/16 \n\tN = 2000 #determines fineness\n\n\t#forming the grid\n\n\tif L >= 0:\n\t\tlogx = np.linspace(-10, 0, N)\n\t\txl = 1 - 10**logx\n\t\txl = np.flip(xl,0)\n\t\txr = 1 + 10**logx\n\t\tx = np.r_[xl, [1], xr]\n\t\tx = x[1:]\n\telse:\n\t\tlogx = np.linspace(-10, 0, int(N/2))\n\t\txl = 1 -np.sqrt(-L) - 10**logx*(1 -np.sqrt(-L))\n\t\txl = np.flip(xl, 0)\n\t\txcl = 1 -np.sqrt(-L) + 10**logx*(np.sqrt(-L))\n\t\txcr = 1 +np.sqrt(-L) - 10**logx*(np.sqrt(-L))\n\t\txcr = np.flip(xcr, 0)\n\t\txr = 1 +np.sqrt(-L) + 10**logx*(1 -np.sqrt(-L))\n\t\tx = np.r_[xl, [1 - np.sqrt(-L)], xcl, xcr, [1 + np.sqrt(-L)], xr]\n\t\tx = x[1:]\n\n\t#forming dx\n\tdx = np.diff(x)\n\tdx = np.r_[dx, dx[len(x)-2]]\n\n\t#the band\n\txi = (x-1)**2 + L \n\n\t#forming Coulomb term\n\tX, Y = np.meshgrid(x, x)\n\tcolmb = Coul(2*X*Y/(X**2 + Y**2))/np.sqrt(X**2 + Y**2)\n\n\t#setting initial values\n\n\tdelta0 = Lc0*np.ones(len(x)) #flat initial value of delta\n\tphi0 = np.zeros(len(x)) #flat zero for initial phi\n\terr = 1 #error\n\tj = 0 #counter\n\n\n\twhile err > 1e-5 and j < 50:\n\t\t#new delta\n\t\tdelta = np.zeros(len(x))\n\t\n\t\tfor i in range(len(x)):\n\t\t\tinteg1 = x*delta0/np.sqrt((xi + phi)**2 + delta0**2)\n\t\t\tinteg2 = (g - Ec*colmb[:, i])/(4*np.pi)\n\t\t\tdelta[i] = sum(dx*integ1*integ2)\n\t\n\t\t#this is the error that's supposed to converge if there is a solution\n\t\terr = sum(np.abs(delta - delta0))/sum(np.abs(delta))\n\t\tdelta0 = delta\n\t\n\t\tj += 1\n\t\tprint('#',j)\n\t\tprint(np.log(err))\n\t\t\n\n\t\tplt.figure(0)#this is keeping track of error\n\t\tplt.plot([j], [np.log(err)] , 'ro')\n\t\n\t#plt.show()\n\n\treturn x, delta\n\n\n'''PLOTTING TWO EXAMPLES FOR g = 0.1 '''\n\ng = 0.1 #setting g\n\n# plot for L = 0 and Ec = 0.05 \n\nx, delta = solver(g, 0.05, 0)\nx, d = solver(g, 0, 0)#this is without Coulomb to be used as normalization scale\nd0 = min(d)\n\nplt.figure(1)\n\nplt.subplot(2,1,1)\nplt.title('$\\Lambda = 0$, $E_c = 0.05 E_R$', fontsize = 14)\nplt.plot(x, delta/d0, 'k', lw = 2)\nplt.xlim((x[0],2))\nplt.xlabel('$p/p_0$', fontsize = 14)\nplt.ylabel('$\\Delta / \\Delta_{0}$', fontsize = 14)\n\n\n# plot for L = -0.01 and Ec = 0.02\n\nx, delta = solver(g, 0.02, -0.01)\nx, d = solver(g, 0, -0.01)#this is without Coulomb to be used as normalization scale\nd0 = min(d)\n\nplt.figure(1)\n\nplt.subplot(2,1,2)\nplt.title('$\\Lambda = -0.01 E_R$, $E_c = 0.02 E_R$ ', fontsize = 14)\nplt.plot(x, delta/d0, 'k', lw = 2)\nplt.xlim((x[0],2))\nplt.xlabel('$p/p_0$', fontsize = 14)\nplt.ylabel('$\\Delta / \\Delta_{0}$', fontsize = 14)\n\nplt.show()\n'''\n\n\n\ng = 0.1\nLc0 = g**2/16\nx, delta = solver(g, .0634, 0)\n\nprint('min delta =', min(delta)/Lc0)\n'''\n","repo_name":"hassan-allami/SC-in-Moat","sub_path":"BCS_Coulomb_1d_no_Screen.py","file_name":"BCS_Coulomb_1d_no_Screen.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"41639171331","text":"import pickle\nimport openpyxl\nfrom selenium import webdriver\nimport time\nimport re\nimport traceback\nfrom datetime import datetime\nimport os\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport json\nimport random\nfrom proxymaker import *\ndef createexcelifnotexists():\n filepath=\"database.xlsx\"\n if not os.path.isfile(filepath):\n #if not exists file\n wb = openpyxl.Workbook()\n wb.save(filepath)\ndef readfromexcel(sheet_name,row,col):\n createexcelifnotexists()\n wb_obj = openpyxl.load_workbook(\"database.xlsx\")\n try: \n sheet_obj = wb_obj[sheet_name]\n except KeyError:\n wb_obj.create_sheet(sheet_name)\n sheet_obj = wb_obj[sheet_name]\n return sheet_obj.cell(row = row, column = col).value\n\ndef writetoexcel(sheet_name,row,col,value):\n createexcelifnotexists()\n wb_obj = openpyxl.load_workbook(\"database.xlsx\")\n try: \n sheet_obj = wb_obj[sheet_name]\n except KeyError:\n wb_obj.create_sheet(sheet_name)\n sheet_obj = wb_obj[sheet_name]\n sheet_obj.cell(row = row, column = col).value= value\n wb_obj.save(\"database.xlsx\")\ndef getmaxrow(sheet_name):\n createexcelifnotexists()\n wb_obj = openpyxl.load_workbook(\"database.xlsx\")\n try: \n sheet_obj = wb_obj[sheet_name]\n except KeyError:\n wb_obj.create_sheet(sheet_name)\n sheet_obj = wb_obj[sheet_name]\n return sheet_obj.max_row\n\nclass Browser:\n def __init__(self,username,password):\n chrome_options = Options()\n prefs = {\n \"download_restrictions\": 3,\n \"download.open_pdf_in_system_reader\": False,\n \"download.prompt_for_download\": True,\n \"download.default_directory\": \"/dev/null\",\n \"plugins.always_open_pdf_externally\": False,\n \"profile.managed_default_content_settings.images\": 2\n }\n chrome_options.add_experimental_option(\n \"prefs\", prefs\n )\n chrome_options.add_argument(\"--disable-logging\")\n chrome_options.add_argument('log-level=3')\n prefs = {\n \"download_restrictions\": 3,\n }\n chrome_options.add_experimental_option(\n \"prefs\", prefs\n )\n PROXY = get_random_proxy()\n #chrome_options.add_argument('--proxy-server=%s' % PROXY)\n driver = webdriver.Chrome('chromedriver',options=chrome_options)\n self.driver=driver \n self.setmobileview()\n self.username=username\n self.password=password\n self.login()\n def setmobileview(self):\n # Apple iPhone X: 375, 812\n # Apple iPhone XS Max: 414, 896\n try:\n self.driver.set_window_size(414, 896)\n except :\n print(\"Unexpected alert on resizing web driver!\\n\\t\")\n \n def login(self):\n self.driver.get(\"https://www.linkedin.com\")\n try:\n print(\"trying to load cookie if available\")\n self.loadcookie()\n self.driver.get(\"https://www.linkedin.com\")\n return\n except:\n print(\"some problem with cookie or its not available\")\n traceback.print_exc()\n time.sleep(10)\n self.driver.get(\"https://www.linkedin.com/login\")\n self.driver.find_element_by_id('username').send_keys(self.username)\n self.driver.find_element_by_id('password').send_keys(self.password)\n self.driver.find_element_by_id('password').send_keys(\"\\n\")\n try:\n self.driver.find_elements_by_xpath(\"//*[contains(text(),'Skip']\").click()\n except:\n pass\n self.savecookies()\n def loadcookie(self):\n print(\"loading cookie\")\n cookies = pickle.load(open(\"cookies.pkl\", \"rb\"))\n print(cookies)\n self.driver.add_cookie(cookies)\n print('loaded cookie')\n def savecookies(self):\n print(\"saving cookie\")\n time.sleep(10)\n cookies=self.driver.get_cookies()\n for cookie in cookies:\n if(cookie['name']=='li_at'):\n cookie['domain']='.linkedin.com'\n x={\n 'name': 'li_at',\n 'value': cookie['value'],\n 'domain': '.linkedin.com'\n }\n break\n pickle.dump(x , open(\"cookies.pkl\",\"wb\"))\n\n print('cookies saved')\n def leave(self):\n print(\" killing the browser \")\n self.driver.quit()","repo_name":"codewithnick/linkedpy","sub_path":"Browser.py","file_name":"Browser.py","file_ext":"py","file_size_in_byte":4586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"19953531811","text":"filehandle = open(\"Sales2.txt\",\"w\")\ndef convert(filename):\n items = []\n menuitems = {}\n filehandle = open(filename,\"r\")\n for line in filehandle.readlines():\n items= line.split(\" - \")\n menuitems[items[0]]=items[1].replace(\"\\n\",\"\")\n return menuitems\n \ndef getorder(filename):\n items = []\n filehandle = open(filename,\"r\")\n for line in filehandle.readlines():\n line = line.replace(\"\\n\",\"\")\n items.append(line)\n \n return items\n\ndef total():\n order = getorder(\"Orders.txt\")\n menu = convert(\"Menu.txt\")\n subtotal = 0.00\n for items in order:\n subtotal = subtotal + float(menu[items])\n return subtotal \n \n \n \n \n \n \nprint(total())","repo_name":"TarunNarahari/PythonPrograms","sub_path":"Sales2.py","file_name":"Sales2.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"26283696381","text":"m, n = list(map(int, input().split()))\r\n\r\ndef enumerate(old, new, i, translate, seen):\r\n if \"\".join(old) == \"\".join(new):\r\n return True\r\n if len(old) == i:\r\n return False\r\n\r\n if old[i] == new[i]:\r\n return enumerate(old, new, i+1, translate, seen)\r\n\r\n if old[i] not in translate:\r\n return False\r\n\r\n for change in translate[old[i]]:\r\n original = old[i]\r\n old[i] = change\r\n if \"\".join(old) in seen:\r\n continue\r\n\r\n seen.add(\"\".join(old))\r\n v = enumerate(old, new, i, translate, seen)\r\n old[i] = original\r\n if v:\r\n return v\r\n return False\r\n\r\ntranslate = {}\r\nfor _ in range(0, m):\r\n old, new = input().split()\r\n if old in translate:\r\n translate[old].append(new)\r\n else:\r\n translate[old] = [new]\r\nfor _ in range(0, n):\r\n old, new = input().split()\r\n a = False\r\n if len(old) == len(new):\r\n a = enumerate(list(old), list(new), 0, translate, set())\r\n if a:\r\n print(\"yes\")\r\n else:\r\n print(\"no\")\r\n","repo_name":"jonathantsang/CompetitiveProgramming","sub_path":"kattis/secretchamber/secretchamber.py","file_name":"secretchamber.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"83"} +{"seq_id":"3367691132","text":"import sqlite3\n\n\n\n# db = sqlite3.connect('allsave.db')\n# sql = db.cursor()\n# # Раскоментировать и запустить файл чтобы создать таблицы в базе, не забыть прописать commit\n# sql.execute(\"create table anydd_user (user_id)\")\n# db.commit()\n\nclass User:\n\tdef __init__(self, user_id):\n\t\tself.user_id = user_id\n\n\tdef add_or_check_user(self):\n\t\tdb = sqlite3.connect('allsave.db')\n\t\tsql = db.cursor()\n\t\tsql.execute('select user_id from anydd_user where user_id = ?', (self.user_id,))\n\t\t\n\n\t\tif sql.fetchone() is None:\n\t\t\tsql.execute('insert into anydd_user values(?)', (self.user_id,))\n\t\t\tdb.commit()\n\n\tdef get_users(self, user_id):\n\t\tdb = sqlite3.connect('allsave.db')\n\t\tsql = db.cursor()\n\t\tif user_id in [583411442, 295612129]:\n\t\t\tsql.execute('select user_id from anydd_user')\n\t\t\tLusers = sql.fetchall()\n\t\t\tusers = []\n\t\t\tfor i in Lusers:\n\t\t\t\tusers.append(i)\n\n\t\t\treturn users\n\t\tpass\n\n# sql.close()\n# db.close()\n\n","repo_name":"Ruzakiiii/Boot-loader","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"2820413318","text":"di = [-1,1,0,0]\ndj = [0,0,-1,1] # 상하좌우\n\ndef snake(now_pos,path,cnt):\n if cnt == 6:\n if not(path in path_list):\n path_list.append(path[:])\n return\n\n for k in range(4):\n dx = now_pos[0] + di[k]\n dy = now_pos[1] + dj[k]\n if 0 <= dx < 5 and 0 <= dy < 5:\n path += maps[dx][dy]\n snake([dx,dy],path,cnt+1)\n path.pop()\n\nmaps = [list(input().split()) for _ in range(5)]\npath_list = []\nfor i in range(5):\n for j in range(5):\n snake([i,j],[],0)\n\nprint(len(path_list))","repo_name":"kimjinho-dev/baekjoon","sub_path":"백준/Silver/2210. 숫자판 점프/숫자판 점프.py","file_name":"숫자판 점프.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"9115397991","text":"\"\"\"\r\nform.errors 表单错误消息的提取\r\n将form表单提交的结果,转换成json格式输出,从而得到error_message\r\n定义一个表单父类,然后定义一个get_error,\r\n定义的其他表单继承此类,从而有此属性,从而获取表单的错误信息\r\n\"\"\"\r\nclass FormMixin(object):\r\n def get_error(self):\r\n if hasattr(self,'errors'):\r\n errors = self.errors.get_json_data()\r\n error_tuple = errors.popitem()\r\n error_list = error_tuple[1]\r\n error_dict = error_list[0]\r\n message = error_dict['message']\r\n return message\r\n else:\r\n return None\r\n\r\n","repo_name":"Chales-xys/dj_xtproj","sub_path":"apps/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"70273021391","text":"import string\nimport sys\n\nwith open(sys.argv[1]) as f:\n rows = [line.rstrip('\\n') for line in f]\n\n\nfor row in rows:\n if (int(row.split()[6].replace(\"%\", \"\")) > int(sys.argv[2])):\n print(row.split()[0].replace(\":\", \"\"))\t\n\n\n","repo_name":"xhnilic3/python","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"9526830878","text":"import json\nfrom django.core import serializers\nfrom django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render, redirect\nfrom textApp.getToken import Token\nfrom django.core.cache import cache\nfrom django.utils.decorators import method_decorator\nfrom textApp.form import MyForm\nfrom textApp.models import *\n# Create your views here.\nfrom textApp import getCode\nfrom textApp.models import User, UserInfo\n\n\n# # 用户认证装饰器\ndef checklogin(func):\n def wrapper(request, *args, **kwargs):\n try:\n req_obj = json.loads(request.body)\n a = req_obj['token']\n if a:\n payload = Token.check_token(a)\n a = cache.get(payload['username'])\n if payload == 'token已失效' or payload == '非法的token' or payload == '非法的token':\n return JsonResponse(payload, safe=False)\n else:\n res = func(request, *args, **kwargs)\n return res\n else:\n return JsonResponse('请登录', safe=False)\n except ValueError as e:\n print(e)\n return wrapper\n\n\n# 用户登录的实现\ndef login(request):\n req_obj = json.loads(request.body)\n username = req_obj['username']\n password = req_obj['password']\n font_code = req_obj['code']\n back_code = request.session['value_code']\n try:\n user_obj = User.objects.filter(username=username)\n if user_obj:\n if User.objects.filter(username=username, password=password):\n if font_code.lower() == back_code.lower():\n # 将用户登录成功的信息设置成token储存在redis里\n redis_obj = Token.create_token(username, user_obj.first().is_vip)\n # conn = get_redis_connection('default')\n # conn.set(redis_obj, username, 15)\n cache.set(username, redis_obj, 12*60*60)\n obj = JsonResponse('suc', safe=False)\n obj.set_cookie('token', redis_obj, 12*60*60)\n return obj\n else:\n return JsonResponse('验证码不正确', safe=False)\n else:\n return JsonResponse('密码不正确', safe=False)\n else:\n return JsonResponse('用户名不存在', safe=False)\n except Exception as e:\n print(e)\n return JsonResponse('fail', safe=False)\n\n\n# 注册实现\ndef register(request):\n req_obj = json.loads(request.body)\n username = req_obj['username']\n password = req_obj['password']\n font_code = req_obj['code']\n\n back_code = request.session['value_code']\n if User.objects.filter(username=username):\n register_message = '用户名已存在'\n return JsonResponse(register_message, safe=False)\n else:\n if back_code.lower() == font_code.lower():\n user_obj = User.objects.create(username=username, password=password)\n user_obj.save()\n user = UserInfo.objects.create(\n user_id=user_obj.id,\n name=username,\n gender='3',\n address='1',\n phone='none',\n )\n user.save()\n return JsonResponse('suc', safe=False)\n else:\n return JsonResponse('验证码���误', safe=False)\n\n\n# 注销实现\ndef logout(request):\n obj = JsonResponse('suc', safe=False)\n obj.delete_cookie('token')\n return obj\n\n\n# 判断是否是vip\ndef vip(request):\n if request.method == 'POST':\n pass\n else:\n return render(request, 'vip_user.html')\n\n\n# 验证码图片的实现\ndef img(request):\n # 用 pillow 来制作验证码 并将验证码内容设置到cookie里\n data, code = getCode.get()\n request.session['value_code'] = code\n return HttpResponse(data, code)\n\n\n# 首页显示所有图书\ndef index(request):\n books_objs = Books.objects.all()\n books_obj = serializers.serialize('json', books_objs)\n books = json.loads(books_obj)\n return JsonResponse(books, safe=False)\n\n\n# def ajax_search(request):\n# if\n# info = request.POST.get('search_input')\n# print(info)\n# book = Books.objects.filter(book_name__contains=info)\n# b = serializers.serialize('json', book)\n# b = json.loads(b)\n# return HttpResponse(json.dumps(b))\n\n\n# 搜索功能\ndef search(request):\n info = request.GET.get('bookinfo')\n # 检查输入框是否有值\n if info:\n # 按书名搜索\n books_name_obj = Books.objects.filter(book_name__contains=info)\n # 按作者搜索\n books_author_obj = Books.objects.filter(book_author__contains=info)\n book1 = serializers.serialize('json', books_name_obj)\n book2 = serializers.serialize('json', books_author_obj)\n book_name = json.loads(book1)\n book_author = json.loads(book2)\n data = {'book_name': book_name, 'book_author': book_author}\n return JsonResponse(data, safe=False)\n else:\n return JsonResponse('请输入书名或作者', safe=False)\n\n\n# 个人中心的实现\ndef my_zone(request):\n if request.method == 'POST':\n info = json.loads(request.body)['info']\n cookie = info['cookie']\n user = Token.check_token(cookie)['username']\n if user:\n name = info['username']\n phone = info['phone']\n gender = info['gender']\n address = info['address']\n # name = request.POST.get('name')\n # phone = request.POST.get('phone')\n # gender = request.POST.get('gender')\n # address = request.POST.get('address')\n # user = request.COOKIES.get('username')\n user_obj = User.objects.filter(username=user).first()\n user_upd = UserInfo.objects.filter(user_id=user_obj.id).update(\n name=name,\n phone=phone,\n address=address,\n gender=gender\n )\n return JsonResponse('suc', safe=False)\n else:\n return JsonResponse('fail', safe=False)\n else:\n cookie = request.GET.get('cookie')\n payload = Token.check_token(cookie)\n username = payload['username']\n # 一对一表单反向查询\n user_obj = User.objects.filter(username=username).first()\n name = user_obj.userinfo.name\n phone = user_obj.userinfo.phone\n # # 一对一表单正向查询\n # user_obj2 = UserInfo.objects.filter(name='那个男人').first()\n # print(user_obj2.user.username)\n # name = user_obj.userinfo.name\n gender = user_obj.userinfo.get_gender_display()\n address = user_obj.userinfo.get_address_display()\n # phone = user_obj.userinfo.phone\n data = {'name': name, 'phone': phone, 'address': address, 'gender': gender}\n return JsonResponse(data, safe=False)\n\n\n# 我的书架功能实现\ndef my_books(request):\n token = request.GET.get('cookie')\n # 判断用户是否登陆\n if token:\n user = Token.check_token(token)\n username = user['username']\n my_books_obj = MyBooks.objects.filter(book_master=username)\n my_books_list = serializers.serialize('json', my_books_obj)\n my_books_json = json.loads(my_books_list)\n return JsonResponse(my_books_json, safe=False)\n else:\n return JsonResponse(None, safe=False)\n\n\n# 将小说加入我的书架功能实现\ndef add_book(request):\n # 得到用户信息和小说的id\n cookie = request.GET.get('cookie')\n book_id = request.GET.get('book_id')\n # 如果用户登陆 则判断是否存在书架 若没有登陆则返回登陆\n if cookie:\n username = Token.check_token(cookie)['username']\n if book_id:\n if MyBooks.objects.filter(book_num=book_id, book_master=username):\n data = 'fail'\n return JsonResponse('不可重复添加 ', safe=False)\n else:\n book = Books.objects.filter(book_num=book_id).first()\n myBooks = MyBooks.objects.create(\n book_name=book.book_name,\n book_num=book_id,\n book_master=username,\n book_img=book.book_img,\n book_author=book.book_author,\n book_type=book.book_type\n )\n myBooks.save()\n data = 'suc'\n return JsonResponse('添加成功', safe=False)\n else:\n state_code = 404\n return JsonResponse(state_code, safe=False)\n else:\n return JsonResponse('请登录', safe=False)\n\n\n# 删除我的书架中的图书\ndef delete_mybook(request):\n # 找到用户选定的小说编号 并且循环找出单个书籍进行删除\n book_num_list_str = request.GET.get('book_num')\n book_num_list = json.loads(book_num_list_str)\n # 循环删除\n for book_num in book_num_list:\n print(book_num_list[book_num])\n MyBooks.objects.filter(book_num=book_num_list[book_num]).delete()\n return JsonResponse('suc', safe=False)\n\n\n# 检查小说是否在我的书架 是则在前端显示已加入书架\ndef is_on_book(request):\n # 找到当前用户信息\n token = request.GET.get('cookie')\n username = Token.check_token(token)['username']\n # 找到小说的id 并且检查是否在我的书架中\n book_id = request.GET.get('book_id')\n is_true = MyBooks.objects.filter(book_num=book_id, book_master=username)\n if is_true:\n return JsonResponse('true', safe=False)\n else:\n return JsonResponse('false', safe=False)\n\n\n# @login_type\ndef chapter(request):\n # 得到小说id\n book_id = request.GET.get('book_id')\n # 查询该小说\n book_obj = Books.objects.filter(book_num=book_id)\n # 将查到的小说章节按照id排序\n book_chapters_obj = BookChapter.objects.filter(books_id=book_id).order_by('id')\n # 序列化 并传到前端\n books = serializers.serialize('json', book_obj)\n book = json.loads(books)\n book_chapter = serializers.serialize('json', book_chapters_obj)\n book_chapters = json.loads(book_chapter)\n return JsonResponse({'book_chapter': book_chapters, 'book': book}, safe=False)\n\n\ndef chapter_info(request):\n chapter_id = request.GET.get('chapter_id')\n book_id = request.GET['book_id']\n cookie = request.COOKIES.get('token')\n play = Token.check_token(cookie)\n # 找到书信息 和 章节的信息\n book_type = Books.objects.filter(book_num=book_id).first().book_type\n chapter_infos = BookChapter.objects.filter(books_id=book_id, id=chapter_id).first()\n # 如果书是免费的 返回全部章节信息\n if book_type == '7':\n chapters = chapter_infos.chapters\n text = chapter_infos.text\n message = 'ok'\n book_chapter = {'chapter': chapters, 'text': text, \"message\": message}\n return JsonResponse(book_chapter, safe=False)\n # 如果不是免费的 则判断用户类型\n else:\n if chapter_infos.chapter_types == '1':\n chapters = chapter_infos.chapters\n text = chapter_infos.text\n message = 'ok'\n book_chapter = {'chapter': chapters, 'text': text, \"message\": message}\n return JsonResponse(book_chapter, safe=False)\n else:\n token = request.COOKIES.get('token')\n # 如果用户登录过\n if token:\n play = Token.check_token(token)\n username = play['username']\n is_vip = play['is_vip']\n user = User.objects.filter(username=username)\n # 判断用户类型 如果是会员 返回全部章节信息\n if user and user.first().is_vip == '2' and is_vip == '2':\n chapters = chapter_infos.chapters\n text = chapter_infos.text\n message = 'ok'\n book_chapter = {'chapter': chapters, 'text': text, \"message\": message}\n return JsonResponse(book_chapter, safe=False)\n # 否则返回部分信息\n else:\n\n chapters = chapter_infos.chapters\n text = chapter_infos.contr_text()\n print(chapters)\n message = '亲!您还不是会员哟'\n book_chapter = {'chapter': chapters, 'text': text, \"message\": message}\n return JsonResponse(book_chapter, safe=False)\n # 如果没登陆也返回部分信息\n else:\n chapters = chapter_infos.chapters\n text = chapter_infos.contr_text()\n message = '亲,您还没有登录不能阅读哦'\n book_chapter = {'chapter': chapters, 'text': text, \"message\": message}\n return JsonResponse(book_chapter, safe=False)\n\n\n# from textApp import webCrawler\n#\n# from urllib import request as request_de\n# import pymysql\n#\n# import requests as requests_de\n# from lxml import etree\n# import re\n# import time\n# from bs4 import BeautifulSoup\n#\n# def python_bug(request):\n# src = 'https://www.bqkan.com'\n# name = ''\n# author = ''\n# text = ''\n# headers = {\n# 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'\n# }\n# url = 'https://www.bqkan.com/83641_83641553/'\n# res = requests_de.get(url, headers=headers)\n# res.encoding = res.apparent_encoding\n# soup = BeautifulSoup(res.text, 'html.parser')\n# names = soup.select('body > div.book > div.info > h2')\n# authors = soup.select('body > div.book > div.info > div.small > span:nth-child(1)')\n# texts = soup.select('body > div.book > div.info > div.intro')\n# select = etree.HTML(res.text)\n# imgs = select.xpath('//div[@class=\"cover\"]//img/@src')\n# for m in imgs:\n# src += str(m)\n# for i in names:\n# name += str(i)\n# for l in authors:\n# author += str(l)\n# for x in texts:\n# text += str(x)\n# patter = re.compile('<(.*?)>')\n# name = patter.sub('', name)\n# author = patter.sub('', author)\n# text = patter.sub('', text)\n# print(src)\n# # for i in range(1):\n# request_de.urlretrieve(src, '../static/book_images/{}.jpg'.format(\"2\"))\n# book = Books.objects.create(\n# book_name=name,\n# book_author=author,\n# book_num=5,\n# book_info=text,\n# book_type='1',\n# book_end='1',\n# book_hot=0,\n# book_img='{}.jpg'.format(i))\n# return HttpResponse('ok')\n\n\ndef chapter_normal(request, book_id):\n book = Books.objects.filter(book_num=book_id).first()\n book_chapters = BookChapter.objects.filter(books_id=book_id)\n return render(request, 'chapter_normal.html', locals())\n\n\n","repo_name":"zhengwei03/novel_mianshi","sub_path":"text/textApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"1030248075","text":"class Solution:\n def maxOperations(self, nums: List[int], k: int) -> int:\n nums.sort()\n start=operation=0\n end=len(nums)-1\n while startk:\n #increment end pointer\n end-=1\n else:\n #increment start pointer\n start+=1 \n return operation\n","repo_name":"hannankm/Data-Structures-and-Algorithms","sub_path":"Mx-Number-of-K-Sum-Sub-arrays.py","file_name":"Mx-Number-of-K-Sum-Sub-arrays.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"16899155093","text":"# dawitblog.tistory.com\ndef find(r):\n global count\n if r == n:\n # n줄 까지 도달했다면 1가지 경우 추가\n count += 1\n return\n for c in range(n):\n # 대각선 값\n s = r + c\n b = r - c\n if col[c] and slash[s] and backSlash[b]:\n col[c] = slash[s] = backSlash[b] = False\n find(r+1)\n col[c] = slash[s] = backSlash[b] = True\n\nn = int(input())\ncol = [True] * n\nslash = [True] * (n*2+1)\nbackSlash = [True] * (n*2+1)\ncount = 0\nfind(0)\nprint(count)","repo_name":"david02324/Algorithm","sub_path":"Solved.ac/CLASS 4/baekjoon-9663.py","file_name":"baekjoon-9663.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"42630947432","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Constants\r\nc = 3e8 # Speed of light in m/s\r\nh = 6.62e-34 # Planck's constant in J*s\r\n\r\n# Simulation parameters\r\ncutoff = 1e12 # Reduce frequency cutoff to 1 THz\r\nN = 1000 # Reduce number of samples\r\ndx = 10e-6 # Spatial resolution of 10 micrometers\r\n\r\n# Frequency spacing\r\ndf = cutoff / N\r\n\r\n# Frequency values\r\nfreqs = np.arange(0, cutoff, df)\r\n\r\n# Wavevector magnitudes\r\nks = 2 * np.pi * freqs / c\r\n\r\n# Random phases\r\nphases = 2 * np.pi * np.random.rand(N)\r\n\r\n# Electric field amplitude\r\nE0 = (h * freqs)**0.5\r\n\r\n# Generate random 3D E-field\r\nEx = E0 * np.cos(phases) * np.random.randn(N)\r\nEy = E0 * np.sin(phases) * np.random.randn(N)\r\nEz = E0 * np.cos(0.5 * phases) * np.random.randn(N)\r\n\r\n# Magnetic field amplitude\r\nB0 = E0 / c\r\n\r\n# Generate random 3D B-field\r\nBx = B0 * np.sin(phases) * np.random.randn(N)\r\nBy = B0 * np.cos(phases) * np.random.randn(N)\r\nBz = B0 * np.sin(0.5 * phases) * np.random.randn(N)\r\n\r\n# Position arrays\r\nx = np.arange(0, 0.002, dx) # Simulate 2 mm region\r\ny = np.arange(0, 0.002, dx)\r\nz = np.arange(0, 0.002, dx)\r\n\r\n# Create meshgrid\r\nX, Y, Z = np.meshgrid(x, y, z)\r\n\r\n# Evaluate electric field\r\nExyz = np.zeros_like(X)\r\nfor i in range(N):\r\n Exyz += np.sin(ks[i] * X + phases[i]) * Ex[i]\r\n Exyz += np.sin(ks[i] * Y + 0.5 * phases[i]) * Ey[i]\r\n Exyz += np.sin(ks[i] * Z + 0.25 * phases[i]) * Ez[i]\r\n\r\n# Evaluate magnetic field\r\nBxyz = np.zeros_like(X)\r\nfor i in range(N):\r\n Bxyz += np.sin(ks[i] * X + phases[i]) * Bx[i]\r\n Bxyz += np.sin(ks[i] * Y + 0.5 * phases[i]) * By[i]\r\n Bxyz += np.sin(ks[i] * Z + 0.25 * phases[i]) * Bz[i]\r\n\r\n# Spatial field energy density\r\nenergy_density = Exyz**2 + Bxyz**2 # Adding permeability (assume 1 for simplicity)\r\n\r\n# Visualization\r\nfig = plt.figure()\r\nax = plt.axes(projection='3d')\r\nax.plot_wireframe(X, Y, Z, energy_density)\r\nax.set_title('Spatial Energy Density Distribution')\r\nax.set_xlabel('X (m)')\r\nax.set_ylabel('Y (m)')\r\nax.set_zlabel('Z (m)')\r\n\r\nplt.show()\r\n","repo_name":"koernergb/BloctiMIze","sub_path":"save_the_world.py","file_name":"save_the_world.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"74698863952","text":"from typing import List\n\nimport numpy as np\nfrom brimarl_masked.networks.dqrnet import DQRN\nimport tensorflow as tf\nfrom brimarl_masked.environment.environment import BriscolaGame, BriscolaPlayer, Agent\n\n\nclass RecurrentDeepQAgent(Agent):\n \"\"\"Q-learning agent using a recurrent network\"\"\"\n\n def __init__(self, n_actions: int, epsilon: float, minimum_epsilon: float,\n epsilon_decay: float, hidden_size: int = 256,\n fully_connected_layers: int = 256, training=True,\n name=\"RecurrentDeepQLearningAgent\") -> None:\n \"\"\"\"\"\"\n super().__init__(name)\n self.name = name\n\n # Network parameters\n self.n_actions = n_actions\n\n self.policy_net = DQRN(\n hidden_size,\n n_actions,\n fully_connected_layers,\n )\n self.policy_net.build((None, None, 40))\n\n self.hidden_size = hidden_size\n self.fully_connected_layers = fully_connected_layers\n self.h, self.c = self.policy_net.init_hidden(1)\n\n # Reinforcement learning parameters\n self.epsilon = epsilon\n self.minimum_epsilon = minimum_epsilon\n self.epsilon_decay = epsilon_decay\n self.training = training\n\n def state(self, env: BriscolaGame, player: BriscolaPlayer, current_player: BriscolaPlayer):\n \"\"\"\n Each card is encoded as a vector of length 6:\n first entry: numerical value of the card.\n second entry: boolean value (1 if briscola 0 otherwise).\n last four entries: one hot encoding of the seeds.\n For example \"Asso di bastoni\" is encoded as:\n [0, 1, 1, 0, 0, 0] if the briscola is \"bastoni\".\n State:\n [\n my turn 0/1\n my team turn 0/1\n my points (maybe also other team points?)\n move counter\n first card in my hand | 0\n second card in my hand | 0\n third card in my hand | 0\n first card on the table | 0\n second card on the table | 0\n third card on the table | 0\n ]\n \"\"\"\n state = np.zeros(40)\n value_offset = 4\n seed_offset = 2\n features_per_card = 6\n state[0] = player.id == current_player.id\n state[1] = player.id == current_player.id or env.get_teammate(player.id) == current_player.id\n state[2] = player.points / 60\n state[3] = env.counter / 10\n\n for i, card in enumerate(player.hand):\n number_index = i * features_per_card + value_offset\n seed_index = i * features_per_card + value_offset + seed_offset + card.seed\n state[number_index] = card.number\n state[number_index + 1] = 1 if card.seed == env.briscola.seed else 0\n state[seed_index] = 1\n\n for i, card in enumerate(env.played_cards):\n number_index = (i + 3) * features_per_card + value_offset\n seed_index = (i + 3) * features_per_card + seed_offset + card.seed + value_offset\n state[number_index] = card.number\n state[number_index + 1] = 1 if card.seed == env.briscola.seed else 0\n state[seed_index] = 1\n return state\n\n def action(self, game: BriscolaGame, player: BriscolaPlayer):# , available_actions: List[int]):\n \"\"\"Selects action according to an epsilon-greedy policy\"\"\"\n \"\"\"# Select a random action with probability epsilon\n action = np.random.choice(available_actions)\n if np.random.uniform() > self.epsilon or not self.training:\n # Select a greedy action with probability 1 - epsilon\n output, (self.h, self.c) = self.policy_net(\n tf.reshape(self.state(game, player, player), (1, 1, -1)),\n self.h,\n self.c,\n )\n # consider only the first element (ignore the batch dimension)\n output = output.numpy()[0][0]\n sorted_actions = (-output).argsort()\n for predicted_action in sorted_actions:\n if predicted_action in available_actions:\n action = predicted_action\n break\"\"\"\n assert len(player.hand)\n mask = np.zeros(40)\n for card in player.hand: mask[card.id] = 1\n\n game_action = np.random.choice(list(range(len(player.hand))))\n if np.random.uniform() > self.epsilon or not self.training:\n output, (self.h, self.c) = self.policy_net(\n tf.reshape(self.state(game, player, player), (1, 1, -1)),\n self.h,\n self.c,\n )\n # consider only the first element (ignore the batch dimension)\n output = output.numpy()[0][0]\n masked_output = (1-mask) * np.finfo(np.float32).min + output\n action = np.argmax(masked_output)\n game_action = np.argwhere([c.id == action for c in player.hand]).squeeze()\n assert player.hand[game_action].id == action\n\n action = np.zeros(40)\n action[player.hand[game_action].id] = 1\n return game_action, action, mask\n\n def update_epsilon(self):\n if self.epsilon > self.minimum_epsilon:\n self.epsilon -= self.epsilon_decay\n if self.epsilon < self.minimum_epsilon:\n self.epsilon = self.minimum_epsilon\n\n def reset(self):\n self.h, self.c = self.policy_net.init_hidden(1)\n\n def save_model(self, path: str):\n if not path.endswith(\"/\"):\n path += \"/\"\n self.policy_net.save_weights(path + self.name + \"/q_network\")\n\n def load_model(self, path: str):\n if not path.endswith(\"/\"):\n path += \"/\"\n self.policy_net.load_weights(path + self.name + \"/q_network\")\n\n def clone(self, training=False):\n assert type(self) is RecurrentDeepQAgent\n new_agent = RecurrentDeepQAgent(\n n_actions=self.n_actions,\n epsilon=self.epsilon,\n minimum_epsilon=self.minimum_epsilon,\n epsilon_decay=self.epsilon_decay,\n hidden_size=self.hidden_size,\n fully_connected_layers=self.fully_connected_layers,\n training=training\n )\n new_agent.policy_net.set_weights([np.copy(weight) for weight in self.policy_net.get_weights()])\n return new_agent\n\n","repo_name":"AlbertoSinigaglia/brimarl","sub_path":"agents/recurrent_q_agent.py","file_name":"recurrent_q_agent.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"35339142749","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom tiendaDia.models import Producto, Venta\nfrom django.views.generic import ListView, DetailView \nfrom django.urls import reverse_lazy\nfrom django.views.generic.edit import UpdateView, CreateView, DeleteView\n\n# Create your views here.\ndef first_view(request):\n return render(request, 'base.html')\n\nclass ProductoListView(ListView):\n model = Producto\nclass ProductoDetailView(DetailView):\n model = Producto\n\nclass VentaListView(ListView):\n model = Venta\nclass VentaDetailView(DetailView):\n model = Venta\n\nclass VentaCreate(CreateView):\n model = Venta\n fields='__all__'\nclass ProductoCreate(CreateView):\n model = Producto\n fields='__all__'\n\nclass ProductoDelete(DeleteView):\n model = Producto\n success_url = reverse_lazy('producto-list')\nclass VentaDelete(DeleteView):\n model = Venta\n success_url = reverse_lazy('venta-list')\n\n\nclass ProductoUpdate(UpdateView):\n model = Producto\n fields='__all__'\nclass VentaUpdate(UpdateView):\n model = Venta\n fields='__all__'","repo_name":"Andreso07/tienda","sub_path":"tienda/tiendaDia/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"2629764998","text":"#coding:utf-8\nimport sys\nimport CodeAnalyse as ca\nimport classify\n\n###############################################################################\n\n__author__ = 'Luo Yaoxiang ' \\\n 'Shi Junjie ' \\\n 'Gao Mengru '\n\n__date__, __version__ = '12/26/2017', '0.01' # Creation\n__date__, __version__ = '12/28/2017', '1.00' # First release\n\n__description__ = 'Final goal of this tool is to do code refactoring automatically. ' \\\n 'Now we have finished the part of separate a big class into several small classes.'\n\n__note__ = '12/26/2017 Gao - H file parsing & Visualizing with Pygame and Plotly' \\\n '12/26/2017 Luo - CPP file parsing & Extracing relations between vars and funcs' \\\n '12/26/2017 Shi - Clustering classes using relations & Visualizing with MSTR Workstaiton'\n\n################################################################################ \n\ndef read_argv():\n\tfrom optparse import OptionParser\n\tthis_version = 'v%s (c) %s %s' % (__version__, __date__.split('/')[2], __author__)\n\tthis_description = __description__\n\tthis_usage = '''%prog'''\n\tparser = OptionParser(version=this_version, description=this_description, usage=this_usage)\n\tparser.add_option('-v', '--visualize',\n action='store', dest='visualize', default=None,\n help='visualize the relations. --plotly: Visualize with plotly, need to install required libs \\n' \\\n \t\t'--csv: Import csv file to visualize with MSTR workstation \\n' \\\n \t\t'--pygame: Visualize with pygame, need to install required libs. ' \\\n \t\t'We suggest using plotly to load large scale of data rather than pygame.'\n \t\t)\n\t(options, args) = parser.parse_args()\n\treturn options, args\n\nif __name__ == '__main__':\n\toptions, args = read_argv()\n\t#main()\n\t__VISUSALIZE__=options.visualize\n\tif len(args)!=2 or (args[0][-2:]!='.h' and args[-4:]!='.cpp') or (args[0][:-2]!=args[1][:-4]):\n\t\tprint(\"This program takes two args: .h file and .cpp file with the same name\")\n\t\texit(0)\n\th_path = args[0]\n\tcpp_path = args[1]\n\tanalyzer = ca.CodeAnalyse(h_path,cpp_path)\n\t# get relevance between vars and funcs\n\trelevance = analyzer.get_relevance_between_var_and_func()\n\t# get funcs list and vars list\n\tfuncs_list = analyzer.funcs_list\n\tvars_list = analyzer.vars_list\n\t# classify\n\tn = len(set(vars_list)) + len(set(funcs_list))\n\toutput_dic = classify.classify(relevance, n)\n\t# output result as txt\n\tclassify.output(output_dic, 'output_file.txt')\n\tprint(\"Success classify!\")\n\t#draw_fig(output_dic)\n\t# save relevance for visualize\n\tif __VISUSALIZE__=='csv':\n\t\tclassify.save_csv(relevance)\n\t# visualize\n\tif __VISUSALIZE__=='plotly':\n\t\timport draw\n\t\tprint('Waiting for visualizing with plotly...')\n\t\tdraw.visualize(relevance)\n\tif __VISUSALIZE__=='pygame':\n\t\timport draw_pygame\n\t\tprint('Waiting for visualizing with pygame...')\n\t\tdraw_pygame.visualize(output_dic)\t\n\t#else:\n\t#\tprint(\"Warning: -v takes only csv, plotly and pygame\")\t\n","repo_name":"2453929471/hackathon2017","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"42601594036","text":"\nfrom scrapy.linkextractor import LinkExtractor\nimport scrapy\nfrom scrapy.spiders import Rule, CrawlSpider\n\nfrom mzitu_spider.items import MzituSpiderItem\n\n\nclass mzitu_spider(CrawlSpider):\n name = 'mzitu'\n\n start_urls = {\n 'http://www.mzitu.com/all/'\n }\n\n rules = {\n Rule(LinkExtractor(allow=r'http://www.mzitu.com/\\d{1,6}', deny=r'http://www.mzitu.com/\\d{1,6}/\\d{1,6}'),\n callback='parse_item', follow=True)\n }\n img_urls = []\n\n def parse_item(self, response):\n item = MzituSpiderItem()\n total_pages = response.xpath('/html/body/div[2]/div[1]/div[4]/a[5]/span/text()').extract()[0] # str\n item['name'] = response.xpath('/html/body/div[2]/div[1]/h2/text()').extract()\n item['url'] = response.url # 用来设置中间件里面浏览器请求头的referer参数,\n for i in range(1, int(total_pages)-1):\n page_url = response.url + '/' + str(i) # 每页的图片地址\n yield scrapy.Request(page_url, callback=self.img_url)\n item['img_urls'] = self.img_urls\n yield item\n\n def img_url(self, response):\n img_urls = response.xpath(\"/html/body/div[2]/div[1]/div[3]/p/a/img/@src\").extract()\n for img_url in img_urls:\n self.img_urls.append(img_url)","repo_name":"cscainiao/spider","sub_path":"scrapys/mzitu/mzitu_spider/mzitu_spider/spiders/mzitu.py","file_name":"mzitu.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"32885521073","text":"class Phone():\r\n def __init__(self):\r\n self.is_on=False\r\n self.is_locked=True\r\n self.is_onAriplaneMode=False\r\n \r\n def turn_on(self):\r\n self.is_on=True\r\n print('HELLO')\r\n \r\n def turn_off(self):\r\n self.is_off=False\r\n print('GOODBYE')\r\n \r\n def unlock(self):\r\n print('Insert your PIN to unlock.')\r\n \r\n def insert_pin(self,pin):\r\n self.pin=pin\r\n if self.pin == 1009:\r\n self.is_locked=False\r\n print('Welcome')\r\n else:\r\n print('Incorrect. Try again')\r\n def lock(self):\r\n self.is_locked=True\r\n print('Phone locked')\r\n \r\n def airplane_mode_on(self):\r\n self.is_onAriplaneMode=True\r\n print(\"\\tAirplane mode on. \\nYou'll be unable to make or receive calls, \\nsend or receive messages or browse the internet.\")\r\n def airplane_mode_off(self):\r\n self.is_onAriplaneMode=False\r\n print(\"\\tAirplane mode off. \\nYou're able to make and receive calls, \\nsend and receive messages and browse the internet.\")\r\n\r\nphone1=Phone()\r\nphone1.turn_on()\r\nphone1.unlock()\r\nphone1.insert_pin(2345)\r\nphone1.insert_pin(1009)\r\nphone1.lock()\r\nphone1.turn_off()\r\nprint('\\n----------\\n')\r\nphone2=Phone()\r\nphone2.unlock()\r\nphone2.insert_pin(1009)\r\nphone2.airplane_mode_on()\r\nphone2.airplane_mode_off()\r\nphone2.lock()\r\n\r\n \r\n \r\n \r\n \r\n ","repo_name":"lismalgorzata/PRA-PRO-1","sub_path":"Inheritance/telefon.py","file_name":"telefon.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"30575707030","text":"def insertion(lst):\r\n # Search entries in lst starting with index 1\r\n for element in lst[1::]:\r\n # save index of element\r\n index = lst.index(element)\r\n # While the index is positive and the entry to the left is greater than element\r\n while index > 0 and lst[index-1] > element:\r\n # replace greater with lesser\r\n lst[index] = lst [index-1]\r\n # decrement index\r\n index -= 1\r\n # replace lesser with greater\r\n lst[index] = element\r\n return lst\r\n\r\n\r\n\r\n\r\n#The code below will test your function. If your function\r\n#works, it will print: [1, 2, 3, 4, 5].\r\nprint(insertion([5, 1, 47, 3, 2, 4]))","repo_name":"donttauntpepito/search_sort_python","sub_path":"search_sort_class/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"11274574961","text":"import torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader, Dataset\n\nimport numpy as np\nimport pandas as pd\nimport random\n\nimport GTKutils\n\n\ntorch.manual_seed(0)\n\ng = torch.Generator()\ng.manual_seed(0)\n\nnp.random.seed(0)\n\n\nclass DatasetSplit(Dataset):\n \"\"\"\n An abstract Dataset class wrapped around Pytorch Dataset class.\n \"\"\"\n\n def __init__(self, dataset, idxs):\n self.dataset = dataset\n self.idxs = [int(i) for i in idxs]\n\n def __len__(self):\n return len(self.idxs)\n\n def __getitem__(self, item):\n image, label = self.dataset[self.idxs[item]]\n return torch.tensor(image), torch.tensor(label)\n\n\nclass GKTClientTrainer(object):\n def __init__(self, \n model, \n train_data, \n test_data, \n idxs, \n client_index,\n gpu=1, \n optimizer=\"sgd\",\n local_batch_size=16, \n lr=0.01, \n local_epochs=1, \n temperature=3.0, \n alpha=1.0):\n \n self.model = model\n\n self.gpu = gpu\n self.device = 'cuda' if self.gpu else 'cpu'\n self.optimizer = optimizer\n self.local_batch_size = local_batch_size\n self.lr = lr\n self.local_epochs = local_epochs\n self.client_index = client_index\n\n self.trainloader, self.testloader = self.train_test(\n train_data, test_data, list(idxs)) # get train, valid sets\n\n if self.optimizer == \"sgd\":\n self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.lr, momentum=0.9,\n nesterov=True, weight_decay=5e-04)\n elif self.optimizer == \"adam\":\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr, weight_decay=0.0001,\n amsgrad=True)\n\n self.server_logits_dict = dict()\n\n self.temperature = temperature\n self.alpha = alpha\n\n self.criterion_CE = nn.CrossEntropyLoss()\n self.criterion_KL = GTKutils.KL_Loss(self.temperature) \n\n def update_large_model_logits(self, logits):\n self.server_logits_dict = logits\n\n def seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n \n def train_test(self, train_data, test_data, idxs):\n \n \n trainloader = DataLoader(DatasetSplit(train_data, idxs),\n batch_size=self.local_batch_size, shuffle=True, generator=g,\n worker_init_fn=self.seed_worker)\n testloader = DataLoader(test_data,\n batch_size=self.local_batch_size, shuffle=False, generator=g,\n worker_init_fn=self.seed_worker)\n\n return trainloader, testloader\n \n\n def train(self):\n \n self.model.train()\n\n extracted_feature_dict = dict()\n\n logits_dict = dict()\n\n labels_dict = dict()\n\n extracted_feature_dict_test = dict()\n labels_dict_test = dict()\n\n epoch_loss = []\n\n for epoch in range(1, self.local_epochs + 1):\n batch_loss = []\n\n for batch_idx, (images, labels) in enumerate(self.trainloader):\n images, labels = images.to(self.device), labels.to(self.device)\n\n log_probs, _ = self.model(images)\n loss_true = self.criterion_CE(log_probs, labels)\n\n if len(self.server_logits_dict) != 0:\n large_model_logits = torch.from_numpy(\n self.server_logits_dict[batch_idx]\n ).to(self.device)\n loss_kd = self.criterion_KL(log_probs, large_model_logits) # knowledge distillation\n loss = loss_true + self.alpha * loss_kd\n else:\n loss = loss_true\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n batch_loss.append(loss.item())\n\n print('client {} - Update Epoch: {} - Loss: {:.6f}'.format(\n self.client_index, \n epoch, \n sum(batch_loss) / len(batch_loss)\n )\n )\n\n epoch_loss.append(sum(batch_loss) / len(batch_loss))\n\n self.model.eval()\n\n for batch_idx, (images, labels) in enumerate(self.trainloader):\n\n images, labels = images.to(self.device), labels.to(self.device)\n log_probs, extracted_features = self.model(images)\n\n \"\"\"\n if dataset too large -> OUT OF MEMORY ERROR\n it is better to run the program on CPU\n \"\"\"\n extracted_feature_dict[batch_idx] = extracted_features.cpu().detach().numpy()\n\n log_probs = log_probs.cpu().detach().numpy()\n\n logits_dict[batch_idx] = log_probs\n labels_dict[batch_idx] = labels.cpu().detach().numpy()\n\n for batch_idx, (images, labels) in enumerate(self.testloader):\n \n test_images, test_labels = images.to(self.device), labels.to(self.device)\n _, extracted_features_test = self.model(test_images)\n extracted_feature_dict_test[batch_idx] = extracted_features_test.cpu().detach().numpy()\n\n labels_dict_test[batch_idx] = test_labels.cpu().detach().numpy()\n\n return extracted_feature_dict, logits_dict, labels_dict, extracted_feature_dict_test, labels_dict_test\n","repo_name":"ricevutoriccardo/Federated-Learning-with-ResNet-50-on-CIFAR-10","sub_path":"FedGKT/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"80"} +{"seq_id":"32448546900","text":"import string\nimport random\nfrom rest_framework import serializers\nfrom .models import URL\nfrom .exceptions import InvalidShortcodeException, ShortcodeInUseException\n\nclass UrlStatsSerializer(serializers.ModelSerializer):\n class Meta:\n model = URL\n fields = (\"created\", \"last_redirect\", \"redirect_count\")\n\n\nclass CreateUrlSerializer(serializers.Serializer):\n \"\"\"\n Serializer for creating a shortened URL.\n\n This serializer is used to validate and create a shortened URL. It accepts the following fields:\n - url: The original URL to be shortened (required)\n - shortcode: The custom shortcode for the shortened URL (optional)\n\n The `validate_shortcode` method validates the provided shortcode and generates a random one if not provided.\n It checks if the shortcode is alphanumeric, contains only lowercase letters, digits, and underscores,\n and has a length of 6 characters. If the shortcode is already in use, a `ShortcodeInUseException` is raised.\n\n The `create` method creates a new URL object using the validated data.\n\n Example Usage:\n serializer = CreateUrlSerializer(data={\"url\": \"https://assetcare.nl\", \"shortcode\": \"asc123\"})\n if serializer.is_valid():\n url = serializer.create(serializer.validated_data)\n # Process the created URL object\n\n \"\"\"\n\n url = serializers.URLField(required=True)\n shortcode = serializers.CharField(required=False)\n\n def validate_shortcode(self, value):\n # Validate and generate shortcode if not provided\n if not value:\n value = \"\".join(\n random.choice(string.ascii_lowercase + string.digits + \"_\")\n for _ in range(6)\n )\n else:\n value = value.lower()\n if not value.replace(\"_\", \"\").isalnum() or len(value) != 6:\n raise InvalidShortcodeException\n if URL.objects.filter(shortcode=value).exists():\n raise ShortcodeInUseException\n return value\n\n def create(self, validated_data):\n # Create a new URL object\n return URL.objects.create(\n url=validated_data[\"url\"], shortcode=validated_data[\"shortcode\"]\n )\n","repo_name":"BuckBucket/CaseAssetCare","sub_path":"shortener/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"9718635830","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 16 14:27:28 2016\n\n@author: piotr at nicecircuits.com\n\"\"\"\n\nfrom libraryManager.symbol import symbol\nfrom libraryManager.symbolPrimitive import *\nfrom libraryManager.defaults import defaults\nfrom libraryManager.part import part\nfrom symbols.symbolsIC import *\nfrom footprints.footprintSmdQuad import *\nfrom libraryManager.footprintPrimitive import *\nimport pyexcel_ods3\nimport numpy as np\n\ntest_path=r\"D:\\pcbLibraryManager\\src\\pcbLibraryManager\\libraries\\STM32_LQFP48.ods\"\n \nclass icGenerator():\n \"\"\"\n universal generator for IC symbols from xls files\n \"\"\"\n def generate_advanced(pinout_file_name, symbol_file_name=\"\", footprint_file_name=\"\"):\n \"\"\"\n generate one or many parts from pinout file. Read more data from file.\n pinout_file_name: name of file with pinouts\n symbol_file_name: name of file with symbols\n footprint_file_name: name of file with footprints\n \"\"\"\n ret=[]\n if symbol_file_name==\"\":\n symbol_file_name = pinout_file_name\n if footprint_file_name==\"\":\n footprint_file_name = pinout_file_name\n parts=icGenerator.load_parts_advanced(pinout_file_name)\n for part_descr in parts:\n if part_descr:\n if part_descr[0]:\n new_part=part(part_descr[0], defaults.icRefDes)\n symbols = icGenerator.load_symbol_advanced(symbol_file_name, part_descr[1])\n new_part.symbols.extend(symbols)\n footprints = icGenerator.load_footprints_advanced(footprint_file_name) #, part_descr[2]\n new_part.footprints.extend(footprints)\n ret.append(new_part)\n return ret\n\n # todo: alternate part\n #new_part=part(part_descr[0]+\"_alt\", defaults.icRefDes)\n def load_footprints_advanced(fileName):\n ret=[]\n params = icGenerator.load_ods_section(fileName, \"Footprint\", \\\n stopString=\"Mechanical\", vector=True, dictionary=True)\n mechanical = icGenerator.load_ods_section(fileName, \"Footprint\", \\\n startString=\"Mechanical\", stopString=\"Footprint\", vector=False, dictionary=True)\n footprint = icGenerator.load_ods_section(fileName, \"Footprint\", \\\n startString=\"Footprint\", vector=False, dictionary=True)\n for variant in footprint.keys():\n if params[\"Type\"]==\"QFP\": \n ret.append(footprintQfpParametrized(params, mechanical, footprint, variant))\n if params[\"Type\"]==\"QFN\": \n ret.append(footprintQfnParametrized(params, mechanical, footprint, variant))\n else:\n raise ValueError(\"Footprint type %s found in %s unsupported\" % (params[\"Type\"], fileName))\n return ret\n \n def test_load_footprints_advanced():\n print(icGenerator.load_footprints_advanced(test_path))\n\n def load_parts_advanced(fileName):\n \"\"\"\n Load parts description from pinout file.\n \"\"\"\n ret = icGenerator.load_ods_section(fileName, \"Part\", vector=False)\n return ret[1:]\n \n def load_ods_sheet(fileName, sheetName):\n try:\n data = pyexcel_ods3.get_data(fileName)[sheetName]\n except KeyError:\n raise ValueError(\"No \\\"%s\\\" tab found in %s\" %(sheetName, fileName))\n except:\n raise ValueError(\"Error opening file \" + fileName)\n return data\n\n def load_ods_section(fileName, sheetName, startString=\"\", stopString=\"\", \\\n vector=False, dictionary=False):\n \"\"\"\n data:\n a,1\n b,2\n read as vector and dictionary:\n {\"a\":1' \"b\":2}\n read vector and not dictionary:\n [[\"a\",1], [\"b\",2]]\n \n data:\n ,v1,v2\n a,1,2\n b,3,4,5,6\n read as not vector and not dictionary:\n [[,\"v1\",\"v2\"],\n [\"a\",1,2],\n [\"b\",3,4]]\n read as not vector and dictionary:\n {\"v1\":{\"a\":1,\"b\":3},\n \"v2\":{\"a\":2,\"b\":4}}\n \"\"\"\n if dictionary:\n output={}\n elif vector:\n output=[]\n else:\n output=[[]]\n data=icGenerator.load_ods_sheet(fileName, sheetName)\n header = True\n variants=[]\n if startString:\n save_data=False\n else:\n save_data=True\n for line in data:\n if line and save_data:\n if stopString and line[0]==stopString:\n break\n if vector and line[0] and len(line)>=2:\n if dictionary:\n output[str(line[0]).strip()]=line[1]\n else:\n output.append([str(line[0]).strip(), line[1]])\n elif not vector:\n if header:\n header=False\n start=1 if dictionary else 0\n for name in line[start:]:\n name=str(name).strip()\n if dictionary:\n output[name]={}\n else:\n output[0].append(name)\n variants.append(name)\n elif dictionary:\n for i in range(len(variants)):\n if i<(len(line)-1):\n output[variants[i]][line[0]]=line[i+1]\n else:\n output[variants[i]][line[0]]=None\n else:\n temp=[]\n for i in range(len(variants)):\n if i=2:\n params[str(line[0]).strip()]=line[1]\n else:\n pass\n else:\n pass\n i=0\n for sym in pinout:\n if len(pinout)>1:\n postfix = \"_%d\"%i\n width = params[\"Width%d\"%i]\n else:\n postfix = \"\"\n width = params[\"Width\"]\n symbols.append(symbolIC(symbolName + postfix,\\\n pinsLeft=sym[0], pinsRight=sym[1], width=width, refDes=defaults.icRefDes,showPinNames=True, showPinNumbers=True))\n i=i+1\n return symbols\n \n def test_load_symbol_advanced():\n print(icGenerator.load_symbol_advanced(test_path))\n \n \"\"\"\n universal generator for IC symbols from xls files\n \"\"\"\n def generate(fileName, pinNames=[], footprints=[], namePosfix=\"\", symbolType=\"dual\",size=0):\n \"\"\"\n generate one or many parts from pinout file\n fileName: name of file with pinouts\n pinNames: pin configuration: [[pins left], [pins right],...[pins left], [pins right]]\n like: [[\"1\",\"2\",\"3\"],[\"6\",\"5\",\"4\"]] or [[\"1\",\"2\"],[\"6\",\"5\"],[\"4\",\"7\"],[\"8\",\"9\"]]\n footprints: list of footprint objects\n namePostfix: postfix to IC name read from pinout\n \"\"\"\n pinout=icGenerator.loadPinout(fileName)\n ret=[]\n if not pinNames:\n #auto generate\n if symbolType==\"quad\":\n nPins=len(pinout[0][\"pins\"])\n nSide=int((nPins)/4)\n #if additional pin above N*4 (thermal pad)\n plus=((nPins%4)>0)*1\n pinNames=np.array([[None]*(nSide+plus)]*4)\n for side in range(4):\n for i in range(nSide):\n pinNames[side,i]=pinout[0][\"pins\"][i+side*nSide]\n if plus:\n pinNames[3,nSide]=pinout[0][\"pins\"][nPins-1]\n else:\n raise ValueError(\"Auto pinout for %s symbol type not implemented yet!\" % symbolType)\n #for each pinout variant\n for v in pinout:\n # generate symbol(s)\n symbols=[]\n pins=[]\n for pinNameCol in pinNames:\n pinCol = []\n for p in pinNameCol:\n if p:\n p=str(p)\n pinCol.append([v[\"pinNames\"][p], p, v[\"pinTypes\"][p]])\n else:\n pinCol.append(None)\n pins.append(pinCol)\n if symbolType==\"dual\":\n #for 1..2 pin columns - one symbol, for 2..3 - 2 etc.\n nSymbols = int((len(pinNames)+1)/2)\n for i in range(nSymbols):\n if nSymbols>1:\n symPostfix = \"_%d\" % i\n else:\n symPostfix = \"\"\n symbols.append(symbolIC(v[\"name\"]+symPostfix+namePosfix, pinsLeft=pins[i*2], pinsRight=pins[i*2+1],\\\n width=size, refDes=defaults.icRefDes,showPinNames=True, showPinNumbers=True))\n elif symbolType==\"quad\":\n symbols.append(symbolICquad(v[\"name\"]+namePosfix,\\\n pins=pins,size=size))\n else:\n raise ValueError(\"invalid symbolType: %s!\" % symbolType)\n for p in v[\"partNames\"]:\n _part = part(p+namePosfix, defaults.icRefDes)\n _part.symbols.extend(symbols)\n _part.footprints.extend(footprints)\n ret.append(_part)\n return ret\n \n def loadPinout(fileName):\n \"\"\"\n Load pinout from ods file.\n \"\"\"\n try:\n sheet = np.array(pyexcel_ods3.get_data(fileName)[\"pinout\"])\n test=sheet[:,0] #check proper conversion to numpy.array\n except Exception as ex:\n print(\"Error! Maybe sheet contains empty cells (especially at ends of rows)?\")\n raise ex\n rowV = sheet[0]\n nVersions = int((len(rowV)-1)/2)\n ret=[0]*nVersions #initialize return structure\n for nV in range(nVersions):\n ret[nV]={}\n ret[nV][\"name\"]=rowV[nV*2+2]\n partNames=sheet[1,nV*2+2]\n partNames=partNames.split(\"\\n\")\n ret[nV][\"partNames\"]=partNames\n ret[nV][\"pins\"]=sheet[2:,0]\n pinTypes=sheet[2:,nV*2+1]\n pinNames=sheet[2:,nV*2+2]\n ret[nV][\"pinTypes\"]={}\n ret[nV][\"pinNames\"]={}\n for i in range(len(ret[nV][\"pins\"])):\n ret[nV][\"pinTypes\"][ret[nV][\"pins\"][i]]=pinType.fromStr[pinTypes[i]]\n ret[nV][\"pinNames\"][ret[nV][\"pins\"][i]]=pinNames[i]\n return ret\n \n def _testLoadPinout():\n \"\"\"\n test for loadPinout function\n \"\"\"\n print(icGenerator.loadPinout(\"pinoutTest.ods\"))\n\n def _testGenerate():\n \"\"\"\n test for generate function\n \"\"\"\n fp=[footprintQfp(32, 0.8, density=density) for density in [\"N\", \"L\", \"M\"]]\n pins=[[\"1\",\"2\",None,\"3\",\"4\"],[\"5\",\"6\",\"7\",\"8\"]]\n print(icGenerator.generate(\"pinoutTest.ods\",pins,fp,\"\"))\n\n def _testGenerate2():\n \"\"\"\n test for generate function\n \"\"\"\n print(icGenerator.generate(\"pinoutTest.ods\",symbolType=\"quad\"))\n\nif __name__ == \"__main__\":\n icGenerator.test_load_footprints_advanced()\n \n ","repo_name":"NiceCircuits/pcbLibraryManager","sub_path":"src/pcbLibraryManager/parts/icGenerator.py","file_name":"icGenerator.py","file_ext":"py","file_size_in_byte":14090,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"36388826531","text":"class Solution:\n def sortColors(self, nums: List[int]) -> None:\n low=0\n high=len(nums)-1\n def partition(nums,low,high):\n i=low-1\n pivot=nums[high]\n for j in range(low,high):\n if nums[j]<=pivot:\n i+=1\n nums[i],nums[j]=nums[j],nums[i]\n nums[i+1],nums[high]=nums[high],nums[i+1]\n \n return i+1\n def Quicksort(nums,low,high):\n if low L:\n dfs(root.left)\n if root.val < R:\n dfs(root.right)\n\n dfs(root)\n return self.result\n","repo_name":"lxyshuai/leetcode","sub_path":"938. Range Sum of BST.py","file_name":"938. Range Sum of BST.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16658830535","text":"from python.collections import *\n\n\ndef test_q1_collections_counter(capsys, monkeypatch):\n inputs = [\"10\",\n \"2 3 4 5 6 8 7 6 5 18\",\n \"6\",\n \"6 55\",\n \"6 45\",\n \"6 55\",\n \"4 40\",\n \"18 60\",\n \"10 50\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q1_collections_counter.main()\n captured = capsys.readouterr()\n output = \"200\\n\"\n assert captured.out == output\n\n\ndef test_q2_defaultdict_tutorial(capsys, monkeypatch):\n inputs = [\"5 2\",\n \"a\", \"a\", \"b\", \"a\", \"b\",\n \"a\", \"b\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q2_defaultdict_tutorial.main()\n captured = capsys.readouterr()\n output = \"1 2 4\\n3 5\\n\"\n assert captured.out == output\n\n inputs = [\"1 1\",\n \"abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaxxxxxxxxxx\",\n \"abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaxxxxxxxxx\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q2_defaultdict_tutorial.main()\n captured = capsys.readouterr()\n output = \"-1\\n\"\n assert captured.out == output\n\n\ndef test_q3_py_collections_namedtuple(capsys, monkeypatch):\n inputs = [\"5\",\n \"ID MARKS NAME CLASS\",\n \"1 97 Raymond 7\",\n \"2 50 Steven 4\",\n \"3 91 Adrian 9\",\n \"4 72 Stewart 5\",\n \"5 80 Peter 6\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q3_py_collections_namedtuple.main()\n captured = capsys.readouterr()\n output = \"78.00\\n\"\n assert captured.out == output\n\n inputs = [\"5\",\n \"MARKS CLASS NAME ID\",\n \"92 2 Calum 1\",\n \"82 5 Scott 2\",\n \"94 2 Jason 3\",\n \"55 8 Glenn 4\",\n \"82 2 Fergus 5\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q3_py_collections_namedtuple.main()\n captured = capsys.readouterr()\n output = \"81.00\\n\"\n assert captured.out == output\n\n\ndef test_q4_py_collections_ordereddict(capsys, monkeypatch):\n inputs = [\"9\",\n \"BANANA FRIES 12\",\n \"POTATO CHIPS 30\",\n \"APPLE JUICE 10\",\n \"CANDY 5\",\n \"APPLE JUICE 10\",\n \"CANDY 5\",\n \"CANDY 5\",\n \"CANDY 5\",\n \"POTATO CHIPS 30\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q4_py_collections_ordereddict.main()\n captured = capsys.readouterr()\n output = (\"BANANA FRIES 12\\n\"\n \"POTATO CHIPS 60\\n\"\n \"APPLE JUICE 20\\n\"\n \"CANDY 20\\n\")\n assert captured.out == output\n\n\ndef test_q5_word_order(capsys, monkeypatch):\n inputs = [\"4\",\n \"bcdef\",\n \"abcdefg\",\n \"bcde\",\n \"bcdef\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q5_word_order.main()\n captured = capsys.readouterr()\n output = (\"3\\n2 1 1\\n\")\n assert captured.out == output\n\n\ndef test_q6_py_collections_deque(capsys, monkeypatch):\n inputs = [\"6\",\n \"append 1\",\n \"append 2\",\n \"append 3\",\n \"appendleft 4\",\n \"pop\",\n \"popleft\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q6_py_collections_deque.main()\n captured = capsys.readouterr()\n output = \"1 2\\n\"\n assert captured.out == output\n\n\ndef test_q7_most_commons(capsys, monkeypatch):\n inputs = [\"aabbbccde\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q7_most_commons.main()\n captured = capsys.readouterr()\n output = \"b 3\\na 2\\nc 2\\n\"\n assert captured.out == output\n\n inputs = [\"szrmtbttyyaymadobvwniwmozojggfbtswdiocewnqsjrkimhovimghixqryqgzhgbakpncwupcadwvglmupbexijimonxdowqsjinqzytkooacwkchatuwpsoxwvgrrejkukcvyzbkfnzfvrthmtfvmbppkdebswfpspxnelhqnjlgntqzsprmhcnuomrvuyolvzlni\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q7_most_commons.main()\n captured = capsys.readouterr()\n output = \"o 12\\nm 11\\nn 11\\n\"\n assert captured.out == output\n\n\ndef test_q8_piling_up(capsys, monkeypatch):\n inputs = [\"2\",\n \"6\",\n \"4 3 2 1 3 4\",\n \"3\",\n \"1 3 2\"]\n monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))\n\n q8_piling_up.main()\n captured = capsys.readouterr()\n output = \"Yes\\nNo\\n\"\n assert captured.out == output\n","repo_name":"mxdzi/hackerrank","sub_path":"tests/test_python_collections.py","file_name":"test_python_collections.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39342718124","text":"class Bits:\n def __init__(self, xs):\n self.bits = xs\n\n def retrieve_bits(self):\n return self.bits\n\n \n def flip(self, n): \n if self.bits[n] == True:\n self.bits[n] = False\n else:\n self.bits[n] = True\n\n \n \n# Do not modify test case below \nbs = Bits([True, False, False, False, True, True])\nbs.flip(3)\n\ndef is_odd(x):\n return x%2 == 1\n \n \ndef all_false(xs):\n return True not in xs\n\ndef element_wise_and(xs,ys):\n for i in range(len(xs)):\n xs[i] = xs[i] and ys[i]\n return xs\n\ndef decrement(xs):\n for i in range(len(xs)-1, -1, -1):\n if xs[i] == True:\n xs[i] = False\n break\n else:\n xs[i] = True\n return xs\n\n\n#print(decrement([True, False, True, False, False]))\n\ndef count_true(xs):\n count = 0\n while not all_false(xs):\n xs = element_wise_and(xs, decrement(xs))\n count += 1\n return count\n \n \n \n \ndef compute_parity(xs):\n return is_odd(count_true(xs))\n\n\n\n\ndef check_parity(xs,p):\n return compute_parity(xs) == p\n\nclass Bits_with_parity(Bits):\n def __init__(self, xs):\n super().__init__(xs)\n self.parity = compute_parity(xs)\n\n def retrieve_bits(self):\n if check_parity(self.bits, self.parity):\n return self.bits\n else:\n return \"DATA LOST\"\n \n \n\n \n# Do not modify the test cases below:\nsome_bits = Bits_with_parity([True, True, False, False, False])\n\ndef encode(xs):\n result = []\n for i in range(len(xs)):\n result.extend([xs[i]]*3)\n return result\n\n#print(encode([True, False, True]))\n\ndef decode(xs):\n result = [True]*(len(xs)//3)\n for i in range(len(xs)//3):\n check = xs[i*3:(i+1)*3]\n print(check)\n if sum(check) == 1:\n result[i] = False\n elif sum(check) == 2:\n result[i] = True\n else:\n result[i] = xs[i*3]\n return result\n\n#print(decode(encode([True, False, True])))\n\n\nstorage = ()\ndef genCurr(func, minArgs):\n def helper(*args):\n global storage\n storage += args\n if len(storage) != minArgs:\n return None\n else:\n return func(*storage)\n\n \n return helper\n\n \n\ndef f(x,y,v,w):\n return x * v + (y - w)\n\ncurry_f = genCurr(f,4)\nprint(curry_f(2,3))\nprint(curry_f(7,5))\n\ndef cannibal(c, m):\n if m == 0:\n if c > 2:\n return ((2,0), (1, 0)) + cannibal(c-1, m)\n else:\n return ((c, 0), )\n \n if c > m or c >= 4:\n return False\n if c + m <= 2:\n return ((c, m), )\n elif c == 1:\n return ((1, 1), (0, 1)) + cannibal(0, m)\n elif c == 2:\n return ((2, 0), (1, 0), (0, 2), (1, 0), (2, 0)) + cannibal(0, m - 2)\n elif c == 3:\n return ((2, 0), (1, 0), (2, 0), (1, 0), (0, 2), (1, 1), (0, 2), (1, 0), (2, 0), (1, 0), (2, 0)) + cannibal(0, m-3)\n\nprint(cannibal(1, 1))\n\n\n\n","repo_name":"jianningzhuang/CS1010X-Programming_Methodology","sub_path":"Practical Exam/CS1101S 2013_14.py","file_name":"CS1101S 2013_14.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"73282568897","text":"# Script for visualizing the value of the objective function for the variant identification objective\n\nimport fastaparser\nimport os\nimport pandas as pd\nimport numpy as np\nfrom itertools import combinations \nimport seaborn as sns\nimport matplotlib.ticker as ticker\nimport sys\nfrom pandas.api.types import is_numeric_dtype\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\n\nplt.rcParams['font.size'] = 20\nplt.rcParams[\"axes.labelsize\"] = 18\nplt.rcParams[\"xtick.labelsize\"] = 16\nplt.rcParams[\"ytick.labelsize\"] = 16\nplt.rcParams['legend.fontsize'] = 16\nplt.rcParams[\"legend.frameon\"] = False\nplt.rcParams['axes.spines.right'] = False\nplt.rcParams['axes.spines.top'] = False\nplt.rcParams['axes.spines.top'] = False\n# ax.spines['right'].set_color('red')\n# ax.spines['left'].set_color('red')\nplt.rcParams['text.color'] = 'black'\nplt.rcParams['axes.labelcolor'] = 'black'\nplt.rcParams['xtick.color'] = 'black'\nplt.rcParams['ytick.color'] = 'black'\nplt.rcParams['font.family'] = 'Helvetica'\n\ncmap = plt.cm.get_cmap('viridis')\ngcmap = plt.cm.get_cmap('gray')\nbase_col = \"#bbbbbb\"\nadapt_col = \"#555555\" \nevolutionary_col = \"#55ad70\"\nwgan_col = (.35, .09, .35) \n\n\nsns.set_theme(font=\"Helvetica\", style='ticks')\nplt.rcParams['pdf.fonttype'] = 42\nplt.rcParams['ps.fonttype'] = 42\nplt.rcParams['svg.fonttype'] = 'none'\n\nfrom matplotlib import font_manager\nfont_manager.fontManager.addfont('/home/ubuntu/Helvetica.ttf')\n\n\n# Function to compute the value of the fitness given the minimum activity on on-target set and the maximum activity on the off-target set\ndef act_value(min_t1, max_t2):\n return (1/(1 + a*np.exp(k*(min_t1 - o)))) + r*-(1/(1 + a*np.exp(k*(max_t2 - o))))\n\n\n#evolutionary parameters\na = 5.897292\nk = -2.857755\no = -2.510856\nr = 1.736507\n\n\nzz = np.arange(-4, -.4, .1)\nranged = pd.DataFrame(columns = zz, index = zz)\nfor i, min_t1 in enumerate(zz):\n for j, max_t2 in enumerate(zz):\n ranged.iloc[i, j] = act_value(min_t1, max_t2)\n\nfig, ax = plt.subplots(nrows =1, ncols = 1, figsize = (6, 6))\nax = sns.heatmap(ranged.astype(float), square = True, cbar_kws = {'shrink' : 0.7})\nax.set(ylabel=\"Minimum Activity of Guide on $T_1$\", xlabel=\"Maximum Activity of Guide on $T_2$\")\n# format text labels\nfmt = '{:0.2f}'\nxticklabels = []\nfor item in ax.get_xticklabels():\n item.set_text(fmt.format(float(item.get_text())))\n xticklabels += [item]\nyticklabels = []\nfor item in ax.get_yticklabels():\n item.set_text(fmt.format(float(item.get_text())))\n yticklabels += [item]\n\nax.set_xticklabels(xticklabels)\nax.set_yticklabels(yticklabels)\nax.collections[0].colorbar.set_label(\"Objective Function Value, $f_D(g|T_1, T_2)$\")\nplt.locator_params(axis='both', nbins=10)\nfig.savefig('./computational/disc_obj_fn_evolutionary.pdf', dpi = 500)\n\n\n\n#wgan parameters \na = 3.769183\nk = -3.833902\no = -2.134395\nr = 2.973\n\nzz = np.arange(-4, -.4, .1)\nranged = pd.DataFrame(columns = zz, index = zz)\nfor i, min_t1 in enumerate(zz):\n for j, max_t2 in enumerate(zz):\n ranged.iloc[i, j] = act_value(min_t1, max_t2)\n \n \nfig, ax = plt.subplots(nrows =1, ncols = 1, figsize = (6, 6))\nax = sns.heatmap(ranged.astype(float), square = True, cbar_kws = {'shrink' : 0.7})\nax.set(ylabel=\"Minimum Activity of Guide on $T_1$\", xlabel=\"Maximum Activity of Guide on $T_2$\")\n# format text labels\nfmt = '{:0.2f}'\nxticklabels = []\nfor item in ax.get_xticklabels():\n item.set_text(fmt.format(float(item.get_text())))\n xticklabels += [item]\nyticklabels = []\nfor item in ax.get_yticklabels():\n item.set_text(fmt.format(float(item.get_text())))\n yticklabels += [item]\n\nax.set_xticklabels(xticklabels)\nax.set_yticklabels(yticklabels)\nax.collections[0].colorbar.set_label(\"Objective Function Value, $f_D(g|T_1, T_2)$\")\nplt.locator_params(axis='both', nbins=10)\nfig.savefig('./computational/disc_obj_fn_wgan.pdf', dpi = 500)\n\n\n","repo_name":"broadinstitute/mea-cas13-analysis","sub_path":"figures/supp_diff_objective_function_visualization.py","file_name":"supp_diff_objective_function_visualization.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"37853241004","text":"import urllib.request\r\nfrom bs4 import BeautifulSoup\r\nfrom collections import OrderedDict\r\nimport json\r\nimport svgwrite\r\nimport xlsxwriter\r\n\r\n'''\r\n!important things\r\neverylink has some specials attribute\r\nto get data, those attribute must be same.\r\n'''\r\n\r\ndef linkedIn_Scapper(url):\r\n file = open(url, 'rb')\r\n data = file.read()\r\n profile = OrderedDict()\r\n \r\n #parse html data in BeautifulSoup \r\n soup = BeautifulSoup(data, \"html.parser\")\r\n \r\n #1) Photo_Link must be in
tag and class should be 'photo'\r\n photo = soup.find_all(\"a\", { \"class\" : \"photo\" })\r\n profile[\"photo\"] = link_href(photo)\r\n \r\n #2) User Details\r\n profile['userDetails'] = OrderedDict()\r\n details = remove(soup.find_all(\"h1\", { \"id\" : \"name\" }))\r\n profile['userDetails'][\"userName\"] = details\r\n headline = remove(soup.find_all(\"p\", { \"class\" : \"headline title\" }))\r\n profile['userDetails'][\"headline\"] = headline\r\n location = remove(soup.find_all(\"span\", {\"class\" : \"locality\"}))\r\n profile['userDetails'][\"location\"] = location\r\n industry = remove(soup.find_all(\"dd\", {\"class\" : \"descriptor\"}))\r\n profile['userDetails'][\"industry\"] = industry\r\n connections = remove(soup.find_all(\"div\", {\"class\" : \"member-connections\"}))\r\n profile['userDetails'][\"connections\"] = connections\r\n \r\n #3) Education\r\n profile['education'] = OrderedDict()\r\n details = (soup.find_all(\"ul\", { \"class\" : \"schools\" }))\r\n school_data = BeautifulSoup(str(details)[1:-1], \"html.parser\")\r\n schools = (school_data.find_all(\"li\", { \"class\" : \"school\" }))\r\n \r\n a = []\r\n for i in schools:\r\n schoolNameTag = (i.find(\"h4\", { \"class\" : \"item-title\" }))\r\n schoolNameATag = (i.find(\"a\", { \"data-tracking-control-name\" : \"pp_sprof\"}))\r\n schoolName = bettag(schoolNameATag)\r\n DegreeName = (i.find(\"h5\", { \"class\" : \"item-subtitle\" }))\r\n DegreeTag = (i.find(\"span\", { \"class\" : \"translated translation\"}))\r\n Degree = bettag(DegreeTag).split(',')\r\n time = (i.find(\"span\", { \"class\" : \"date-range\" }))\r\n timespan = tagsBettag(time) ###------------------------------------\r\n #print(b'\\xe2\\x80\\x93'.decode('utf-8'))\r\n a.append([schoolName, Degree[0], Degree[1]])\r\n \r\n profile['education'] = a\r\n \r\n #4) Experience\r\n profile['experience'] = OrderedDict()\r\n details = (soup.find_all(\"section\", { \"id\" : \"experience\" }))\r\n positions_data = BeautifulSoup(str(details)[1:-1], \"html.parser\")\r\n positions = (positions_data.find_all(\"li\", { \"class\" : \"position\" }))\r\n\t\r\n a = []\r\n for i in positions:\r\n positionsTag = (i.find(\"h4\", { \"class\" : \"item-title\" }))\r\n positionsTag = bettag(tagsBettag(positionsTag))\r\n companyTag = (i.find(\"h5\", { \"class\" : \"item-subtitle\" }))\r\n companyTag = bettag(tagsBettag(companyTag))\r\n time = (i.find(\"span\", { \"class\" : \"date-range\" }))\r\n time = timeTag(tagsBettag(time))\r\n a.append([companyTag,positionsTag,time])\r\n\t\t#print(positions)\r\n \r\n profile['experience'] = a\r\n \r\n\t#5)Skills \r\n profile['skills'] = OrderedDict()\r\n details = (soup.find_all(\"section\", { \"class\" : \"profile-section skills-section\" }))\r\n skills_data = BeautifulSoup(str(details)[1:-1], \"html.parser\")\r\n skills = (skills_data.find_all(\"span\", { \"class\" : \"wrap\" }))\r\n \r\n a = []\t\r\n for i in skills:\r\n skill = bettag(tagsBettag(i))\r\n a.append(skill)\r\n profile['skills'] = a\r\n \r\n #######################################################################################\r\n #print(profile)\r\n r = json.dumps(profile)\r\n with open('data.json', 'w') as f:\r\n f.write(r)\r\n\t\t\r\n workbook = xlsxwriter.Workbook('hello.xlsx')\r\n worksheet = workbook.add_worksheet()\r\n\r\n worksheet.write('A1', 'Item')\r\n worksheet.write('B1', 'Cost')\r\n row = 1\r\n col = 0\r\n sorted(profile)\r\n for i in (profile):\r\n print(i)\r\n worksheet.write(row, col, profile[i])\r\n worksheet.write(row, col + 1, profile[i])\r\n row += 1\r\n workbook.close()\r\n #createSVG(r)\r\n #print(r)\r\n\t\r\ndef timeTag(string):\r\n a = []\r\n data = string[6:]\r\n a.append(data[:data.find('<')])\r\n data = data[37:]\r\n a.append(data[:data.find('<')])\r\n data = data[data.find('<')+9:-1]\r\n a.append(data[:data.find('<')])\r\n return a\r\n\t\r\ndef tagsBettag(string):\r\n data = str(string)\r\n start = data.find('<')\r\n end = data.find('>')\r\n end1 = data[::-1].find('<')\r\n return data[end+1:len(data)-end1]\r\n \r\ndef bettag(string):\r\n data = str(string)\r\n start = data.find('<')\r\n end = data.find('>')\r\n start1 = data.find('<',end)\r\n return data[end+1:start1]\r\n\r\ndef remove(string):\r\n #print(string)\r\n data = str(string)\r\n data = data[1:-1]\r\n start = data.find('<')\r\n while start>=0:\r\n end = data.find('>')\r\n front = data[:start]\r\n back = data[end+1:]\r\n data = front+back\r\n start = data.find('<')\r\n return data\r\n\r\ndef createSVG(data):\r\n with open('data.html', 'w') as f:\r\n f.write('GraphPython
')\r\n dwg = svgwrite.Drawing('test.svg', profile='tiny')\r\n dwg.add(dwg.g)\r\n dwg.add(dwg.circle(center=(0, 0), r=500, stroke=svgwrite.rgb(255,0,0,'%')))\r\n dwg.add(dwg.text('Test', insert=(0, 2), fill='red'))\r\n dwg.save()\r\n\r\ndef link_href(link):\r\n string = str(link)\r\n start_sign = 'href=\"'\r\n start = string.find('href=\"')\r\n end = string.find('\"',start+len(start_sign))\r\n return string[start+len(start_sign):end]\r\n \r\n \r\nlinkedIn_Scapper(\"profile.html\")","repo_name":"tc18/TkScrapper","sub_path":"LinkedInScapper/linkedIn_Scapper.py","file_name":"linkedIn_Scapper.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39145215635","text":"# this is a game called connect4\r\n# you can play it with your friend or AI\r\n\r\n\r\nimport math\r\nimport random\r\nimport pygame\r\n\r\n\r\ndef drawGrid(color):\r\n s = 20\r\n e = 580\r\n d = 93\r\n w = 5\r\n for i in range(8):\r\n pygame.draw.line(win, color,\r\n (s+d*i, s), (s+d*i, e), w)\r\n for i in range(7):\r\n pygame.draw.line(win, color,\r\n (s, s+d*i), (e+d, s+d*i), w)\r\n\r\n\r\ndef nought(color, center):\r\n pygame.draw.circle(win, color, center, 43)\r\n\r\n\r\ndef isWinner(turn):\r\n streak = 0\r\n for i in range(6):\r\n for j in range(7):\r\n if grid[i][j] == turn:\r\n streak += 1\r\n if streak == 4:\r\n return True\r\n else:\r\n streak = 0\r\n if j > 2:\r\n break\r\n\r\n for i in range(7):\r\n for j in range(6):\r\n if grid[j][i] == turn:\r\n streak += 1\r\n if streak == 4:\r\n return True\r\n else:\r\n streak = 0\r\n if j > 1:\r\n break\r\n\r\n for i in range(3):\r\n for j in range(6-i):\r\n if grid[i+j][j] == turn:\r\n streak += 1\r\n if streak == 4:\r\n return True\r\n else:\r\n streak = 0\r\n if j+i > 1:\r\n break\r\n\r\n for i in range(3):\r\n for j in range(6-i):\r\n if grid[j][i+j+1] == turn:\r\n streak += 1\r\n if streak == 4:\r\n return True\r\n else:\r\n streak = 0\r\n if i+j > 1:\r\n break\r\n\r\n for i in range(3, 6):\r\n for j in range(1+i):\r\n if grid[i-j][j] == turn:\r\n streak += 1\r\n if streak == 4:\r\n return True\r\n else:\r\n streak = 0\r\n streak = 0\r\n\r\n for i in range(1, 4):\r\n for j in range(5, -2+i, -1):\r\n if grid[j][i+5-j] == turn:\r\n streak += 1\r\n if streak == 4:\r\n return True\r\n else:\r\n streak = 0\r\n return False\r\n\r\n\r\ndef isTie():\r\n for i in range(6):\r\n for j in range(7):\r\n if grid[i][j] == 0:\r\n return False\r\n return True\r\n\r\n\r\n# def reset():\r\n# global grid, turn, undoaix, undoaiy, undox, undoy\r\n# undoaix, undoaiy, undox, undoy = -1, -1, -1, -1\r\n# for i in range(3):\r\n# for j in range(3):\r\n# grid[i][j] = \" \"\r\n# turn = random.choice([X, O])\r\n# play()\r\n\r\n\r\n# def undo(x, y):\r\n# global grid, turn\r\n# grid[x][y] = \" \"\r\n# turn = opponent(turn)\r\n# xcord, ycord = coordinates(x, y)\r\n# win.blit(undopic, (xcord-10, ycord-10))\r\n# if turn == X:\r\n# drawGrid(red)\r\n# else:\r\n# drawGrid(green)\r\n# pygame.draw.rect(win, blue, (24+93*x, 24+93*y, 86, 86))\r\n\r\n\r\ndef endText(msg):\r\n global grid, turn\r\n for i in range(6):\r\n for j in range(7):\r\n grid[i][j] = 0\r\n\r\n text = pygame.font.SysFont(\r\n None, 100).render(msg, True, white)\r\n win.blit(text, [350 - 20*len(msg), 250])\r\n\r\n pygame.draw.rect(win, white, (680, 400, 110, 70))\r\n text = pygame.font.SysFont(\r\n None, 40).render(\"Play\", True, black)\r\n win.blit(text, [700, 410])\r\n text = pygame.font.SysFont(\r\n None, 40).render(\"Again!\", True, black)\r\n win.blit(text, [690, 440])\r\n\r\n pygame.draw.rect(win, white, (680, 500, 110, 70))\r\n text = pygame.font.SysFont(\r\n None, 40).render(\"Main\", True, black)\r\n win.blit(text, [700, 510])\r\n text = pygame.font.SysFont(\r\n None, 40).render(\"Menu\", True, black)\r\n win.blit(text, [700, 540])\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit()\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n mx, my = pygame.mouse.get_pos()\r\n if 680 <= mx <= 790 and 400 <= my <= 470:\r\n play()\r\n elif 680 <= mx <= 790 and 500 <= my <= 570:\r\n main()\r\n pygame.display.update()\r\n Clock.tick(fps)\r\n\r\n\r\ndef minimaxPro(alpha, beta, isMaximizing):\r\n global grid\r\n if isWinner(turn):\r\n return 1\r\n if isWinner(3-turn):\r\n return -1\r\n if isTie():\r\n return 0\r\n if isMaximizing:\r\n bestScore = -math.inf\r\n for j in range(7):\r\n for i in range(5, -1, -1):\r\n if not grid[i][j]:\r\n grid[i][j] = turn\r\n score = minimaxPro(alpha, beta, False)\r\n grid[i][j] = 0\r\n bestScore = max(score, bestScore)\r\n alpha = max(alpha, score)\r\n if beta <= alpha:\r\n break\r\n return bestScore\r\n else:\r\n bestScore = math.inf\r\n for j in range(7):\r\n for i in range(5, -1, -1):\r\n if not grid[i][j]:\r\n grid[i][j] = 3-turn\r\n score = minimaxPro(alpha, beta, True)\r\n grid[i][j] = 0\r\n bestScore = min(score, bestScore)\r\n beta = min(beta, score)\r\n if beta <= alpha:\r\n break\r\n return bestScore\r\n\r\n\r\ndef AI():\r\n global grid, turn\r\n bestScore = -math.inf\r\n x = 0\r\n for j in range(7):\r\n for i in range(5, -1, -1):\r\n if not grid[i][j]:\r\n grid[i][j] = turn\r\n score = minimaxPro(-math.inf, math.inf, False)\r\n grid[i][j] = 0\r\n if score > bestScore:\r\n bestScore = score\r\n x = j\r\n for i in range(5, -1, -1):\r\n if not grid[i][x]:\r\n grid[i][x] = turn\r\n for j in range(6):\r\n if turn == 1:\r\n nought(red, (67+93*x, 67+93*j))\r\n else:\r\n nought(green, (67+93*x, 67+93*j))\r\n pygame.display.update()\r\n if i == j:\r\n break\r\n pygame.time.delay(50)\r\n pygame.draw.rect(\r\n win, blue, (24+93*x, 24+93*j, 86, 86))\r\n if isWinner(turn):\r\n endText(\"AI WIN!\")\r\n elif isTie():\r\n endText(\"TIE\")\r\n turn = 3-turn\r\n if turn == 1:\r\n drawGrid(red)\r\n else:\r\n drawGrid(green)\r\n break\r\n\r\n\r\ndef play():\r\n global turn, grid\r\n win.fill(blue)\r\n if turn == 1:\r\n drawGrid(red)\r\n else:\r\n drawGrid(green)\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit()\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n mx, my = pygame.mouse.get_pos()\r\n x = (mx-20)//93\r\n if 0 <= x <= 6:\r\n for i in range(5, -1, -1):\r\n if not grid[i][x]:\r\n grid[i][x] = turn\r\n for j in range(6):\r\n if turn == 1:\r\n nought(red, (67+93*x, 67+93*j))\r\n else:\r\n nought(green, (67+93*x, 67+93*j))\r\n pygame.display.update()\r\n if i == j:\r\n break\r\n pygame.time.delay(50)\r\n pygame.draw.rect(\r\n win, blue, (24+93*x, 24+93*j, 86, 86))\r\n if isWinner(turn):\r\n endText(\"YOU WIN!\")\r\n elif isTie():\r\n endText(\"TIE\")\r\n turn = 3-turn\r\n if turn == 1:\r\n drawGrid(red)\r\n else:\r\n drawGrid(green)\r\n if level != -1:\r\n AI()\r\n break\r\n pygame.display.update()\r\n Clock.tick(fps)\r\n\r\n\r\ndef difficulty():\r\n global level\r\n win.fill(blue)\r\n text = pygame.font.SysFont(\r\n None, 80).render(\"Select Difficulty!\", True, white)\r\n win.blit(text, [200, 60])\r\n\r\n pygame.draw.rect(win, white, (260, 130, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"Easy\", True, black)\r\n win.blit(text, [300, 140])\r\n\r\n pygame.draw.rect(win, white, (260, 200, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"Medium\", True, black)\r\n win.blit(text, [300, 210])\r\n\r\n pygame.draw.rect(win, white, (260, 270, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"Hard\", True, black)\r\n win.blit(text, [300, 280])\r\n\r\n pygame.draw.rect(win, white, (260, 340, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"Impossible\", True, black)\r\n win.blit(text, [300, 350])\r\n\r\n pygame.draw.rect(win, white, (260, 410, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"Main Menu\", True, black)\r\n win.blit(text, [300, 420])\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit()\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n mx, my = pygame.mouse.get_pos()\r\n if 260 <= mx <= 560 and 130 <= my <= 190:\r\n level = 0\r\n play()\r\n elif 260 <= mx <= 560 and 200 <= my <= 260:\r\n level = 1\r\n play()\r\n elif 260 <= mx <= 560 and 270 <= my <= 330:\r\n level = 2\r\n play()\r\n elif 260 <= mx <= 560 and 340 <= my <= 400:\r\n level = 3\r\n play()\r\n elif 260 <= mx <= 560 and 410 <= my <= 460:\r\n main()\r\n pygame.display.update()\r\n Clock.tick(fps)\r\n\r\n\r\ndef main():\r\n win.fill(blue)\r\n text = pygame.font.SysFont(\r\n None, 100).render(\"Connect 4\", True, white)\r\n win.blit(text, [240, 100])\r\n\r\n pygame.draw.rect(win, white, (260, 200, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"YOU VS FRIEND\", True, black)\r\n win.blit(text, [275, 210])\r\n\r\n pygame.draw.rect(win, white, (260, 300, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"YOU VS AI\", True, black)\r\n win.blit(text, [300, 310])\r\n\r\n pygame.draw.rect(win, white, (260, 400, 300, 60))\r\n text = pygame.font.SysFont(\r\n None, 50).render(\"EXIT!\", True, black)\r\n win.blit(text, [330, 410])\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit()\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n mx, my = pygame.mouse.get_pos()\r\n if 260 <= mx <= 560 and 200 <= my <= 260:\r\n level = -1\r\n play()\r\n elif 260 <= mx <= 560 and 300 <= my <= 360:\r\n difficulty()\r\n elif 260 <= mx <= 560 and 400 <= my <= 460:\r\n exit()\r\n pygame.display.update()\r\n Clock.tick(fps)\r\n\r\n\r\npygame.init()\r\npygame.display.set_caption(\"Connect 4\")\r\nwin = pygame.display.set_mode((800, 600))\r\nClock = pygame.time.Clock()\r\nfps = 10\r\nblack = (0, 0, 0)\r\nwhite = (255, 255, 255)\r\nred = (250, 51, 51)\r\ngreen = (51, 250, 89)\r\nblue = (0, 0, 128)\r\n\r\n\r\ngrid = [[0 for x in range(7)] for y in range(6)]\r\nlevel = -1\r\nturn = random.randint(1, 2)\r\nmain()\r\n","repo_name":"GeekyAmit5/Connect4","sub_path":"connect4.py","file_name":"connect4.py","file_ext":"py","file_size_in_byte":11903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16962114593","text":"import base64\n\nfrom mbed import mbed\nfrom contextlib import contextmanager\nimport argparse\nimport json\nimport os\nimport subprocess\nimport sys\n\nPYTHON = sys.executable or 'python3'\nROOT_DIR = os.path.dirname(os.path.realpath(__file__))\nAPP_CONFIG_FILE = os.path.join(ROOT_DIR, 'mbed_app.json')\n\n\ndef _prepare_env(target):\n with open('.mbed', 'w') as f:\n f.write('ROOT=.\\n')\n f.write('TARGET=%s\\n' % (target,))\n f.write('TOOLCHAIN=GCC_ARM\\n')\n mbed.deploy()\n\n\n@contextmanager\ndef _safe_chdir(path):\n current_dir = os.getcwd()\n os.chdir(path)\n try:\n yield\n finally:\n os.chdir(current_dir)\n\n\ndef _get_known_targets():\n with open(os.path.join(ROOT_DIR, 'mbed_app.json'), 'r') as cfg:\n config = json.load(cfg)\n\n return [target for target in config['target_overrides'].keys() if target != '*']\n\n\ndef _traverse_config(config, *paths):\n def traverse_config_impl(path):\n result = config\n for key in path:\n if result is None:\n return None\n result = result.get(key, None)\n return result\n\n for path in paths:\n result = traverse_config_impl(path)\n if result is not None:\n return result\n\n return result\n\n\ndef _compile_bootloader(target):\n bootloader_rootdir = os.path.join(ROOT_DIR, 'mbed-bootloader')\n with _safe_chdir(bootloader_rootdir):\n with open('.mbed', 'w') as f:\n f.write('ROOT=.\\n')\n os.chdir('presets')\n subprocess.check_call([PYTHON, 'build_presets.py', target])\n subprocess.check_call([PYTHON, 'export.py', os.path.join(ROOT_DIR, 'mbed-bootloader-bin')])\n\n\ndef _get_or_create_manifest_dev_config():\n manifest_dev_config = os.path.join(ROOT_DIR, '.manifest-dev-tool', 'dev.cfg.yaml')\n if not os.path.isfile(manifest_dev_config):\n with _safe_chdir(ROOT_DIR):\n subprocess.check_call([PYTHON, '-m', 'manifesttool.dev_tool.dev_tool', 'init'])\n # Remove update_default_resources.c, manifest-dev-tool creates it but we don't want it\n try:\n os.unlink(os.path.join(ROOT_DIR, 'update_default_resources.c'))\n except FileNotFoundError:\n pass\n return manifest_dev_config\n\n\ndef _load_cert_as_der(cert_file):\n with open(cert_file, 'rb') as f:\n cert = f.read()\n\n if b'-----BEGIN' in cert:\n # Probably a PEM file\n import cryptography\n import cryptography.hazmat\n import cryptography.hazmat.primitives\n import cryptography.hazmat.primitives.serialization\n import cryptography.x509\n cert = cryptography.x509.load_pem_x509_certificate(cert).public_bytes(\n cryptography.hazmat.primitives.serialization.Encoding.DER)\n\n return cert\n\n\ndef _prepare_fota_config(app_config, manifest_config, update_certificate):\n if manifest_config is None:\n manifest_config = _get_or_create_manifest_dev_config()\n\n import yaml\n with open(manifest_config, 'r') as f:\n manifest_config = yaml.safe_load(f)\n\n # support both manifest-tool and manifest-dev-tool config formats\n vendor_id = _traverse_config(manifest_config, ['vendor', 'vendor-id'], ['vendor-id'])\n class_id = _traverse_config(manifest_config, ['device', 'class-id'], ['class-id'])\n if update_certificate is None:\n update_certificate = os.path.join(ROOT_DIR, '.manifest-dev-tool', 'dev.cert.der')\n update_certificate = _load_cert_as_der(update_certificate)\n\n if not vendor_id or not class_id or not update_certificate:\n raise ValueError('vendor-id, class-id and update certificate must be provided for FOTA')\n\n app_config['target_overrides']['*']['anjay-mbed-fota.update-cert'] = base64.b64encode(\n update_certificate).decode()\n app_config['target_overrides']['*']['anjay-mbed-fota.vendor-id'] = vendor_id\n app_config['target_overrides']['*']['anjay-mbed-fota.class-id'] = class_id\n with open(APP_CONFIG_FILE, 'w') as f:\n json.dump(app_config, f, indent=4)\n f.write('\\n')\n\n\ndef _main(args):\n parser = argparse.ArgumentParser(\n description='Initializes the project, by setting up the target and compiling bootloader')\n parser.add_argument('--target', type=str, choices=_get_known_targets(), required=True,\n help='Name of the board to prepare the build for')\n parser.add_argument('--manifest-config', type=str,\n help='Configuration file for manifest-tool. If not provided, a development configuration will be used and created if necessary.')\n parser.add_argument('--update-certificate', type=str,\n help='Certificate file that will be used for verifying the update images. May be empty for development configuration.')\n args = parser.parse_args(args)\n\n with _safe_chdir(ROOT_DIR):\n _prepare_env(args.target)\n\n with open(APP_CONFIG_FILE, 'r') as cfg:\n config = json.load(cfg)\n\n extra_labels = _traverse_config(config, ['target_overrides', args.target,\n 'target.extra_labels_add'])\n if any(label.startswith('BL_') for label in (extra_labels or [])):\n _compile_bootloader(args.target)\n\n fota_enable = _traverse_config(config,\n ['target_overrides', args.target, 'anjay-mbed-fota.enable'])\n if fota_enable:\n _prepare_fota_config(config, args.manifest_config, args.update_certificate)\n\n\nif __name__ == '__main__':\n sys.exit(_main(sys.argv[1:]))\n","repo_name":"AVSystem/Anjay-mbedos-client","sub_path":"bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":5547,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"11779799903","text":"CASSANDRA = 'cassandra'\nPOSTGRESQL = 'postgresql'\nMYSQL = 'mysql'\nMONGODB = 'mongodb'\n\nVALID_DBMS = (CASSANDRA, POSTGRESQL, MYSQL, MONGODB)\n\nMANDATORY_FIELDS = {\n CASSANDRA: ['database_name', 'port', 'version', 'username', 'password'],\n POSTGRESQL: ['database_name', 'port', 'version', 'username', 'password', 'dns', 'topology'],\n MYSQL: ['database_name', 'port', 'version', 'username', 'password', 'dns', 'topology'],\n MONGODB: ['database_name', 'port', 'version', 'username', 'password', 'dns', 'topology']\n}\n\nSGBD_CASSANDRA = 'C'\nSGBD_MYSQL = 'M'\nSGBD_POSTGRESQL = 'P'\nSGBD_MONGODB = 'G'\nSGBD_CHOICES = {\n SGBD_CASSANDRA: \"Cassandra\",\n SGBD_POSTGRESQL: \"PostgreSQL\",\n SGBD_MYSQL: 'MySQL',\n SGBD_MONGODB: 'MongoDB'\n}\n\nSGBD = {\n CASSANDRA: SGBD_CASSANDRA,\n MYSQL: SGBD_MYSQL,\n POSTGRESQL: SGBD_POSTGRESQL,\n MONGODB: SGBD_MONGODB\n}\n\nMYSQL_SINGLE = 1\nMYSQL_FOXHA = 3\nMONGODB_SINGLE = 9\nMONGODB_REPLICA_SET = 10\nCASSANDRA_CLUSTER = 18\nPOSTGRESQL_SINGLE = 19\nPOSTGRESQL_STAND_BY = 20\n\nTOPOLOGY = {\n 'POSTGRESQL_SINGLE': POSTGRESQL_SINGLE,\n 'POSTGRESQL_STANDBY': POSTGRESQL_STAND_BY,\n 'MYSQL_SINGLE': MYSQL_SINGLE,\n 'MYSQL_FOXHA': MYSQL_FOXHA,\n 'MONGODB_SINGLE': MONGODB_SINGLE,\n 'MONGODB_REPLICA_SET': MONGODB_REPLICA_SET\n}\n\nTOPOLOGIA_CHOICES = {\n CASSANDRA_CLUSTER: \"Cassandra Cluster\",\n POSTGRESQL_SINGLE: \"PostgreSQL Single Instance\",\n POSTGRESQL_STAND_BY: \"PostgreSQL com Stand By Database\",\n MYSQL_SINGLE: \"MySQL Single Instance\",\n MYSQL_FOXHA: \"MySQL FOXHA\",\n MONGODB_SINGLE: \"MongoDB Single Instance\",\n MONGODB_REPLICA_SET: \"MongoDB Replica Set\"\n}\n\nINSTANCIA_MYSQL = 1\nINSTANCIA_MONGODB = 4\nINSTANCIA_MONGODB_ARBITER = 5\nINSTANCIA_POSTGRESQL = 16\nINSTANCIA_POSTGRESQL_STAND_BY = 17\nINSTANCIA_CASSANDRA = 18\n\nINSTANCIA = {\n CASSANDRA_CLUSTER: INSTANCIA_CASSANDRA,\n POSTGRESQL_SINGLE: INSTANCIA_POSTGRESQL,\n POSTGRESQL_STAND_BY: INSTANCIA_POSTGRESQL_STAND_BY,\n MYSQL_FOXHA: INSTANCIA_MYSQL\n}\n\nINSTANCIA_CHOICES = {\n 'INSTANCIA_MONGODB': INSTANCIA_MONGODB,\n 'INSTANCIA_MONGODB_ARBITER': INSTANCIA_MONGODB_ARBITER\n}\n\n\nclass Constants:\n def __init__(self, dbms, **kwargs):\n self.dbms = dbms\n self.kwargs = kwargs\n self._set_db_constants()\n\n def _set_db_constants(self):\n if self.dbms == CASSANDRA:\n self._topology_id = CASSANDRA_CLUSTER\n else:\n try:\n topology_code = self.kwargs.get('topology')\n self._topology_id = TOPOLOGY[topology_code]\n except KeyError:\n raise Exception(\n \"Invalid topology choice. \"\n \"Please choose one of the following: {}\".format(\n list(TOPOLOGY.keys())\n )\n )\n\n self._topology_name = TOPOLOGIA_CHOICES[self._topology_id]\n self._sgbd_id = SGBD[self.dbms]\n self._sgbd_name = SGBD_CHOICES[self._sgbd_id]\n\n @property\n def topology_id(self):\n return self._topology_id\n\n @property\n def topology_name(self):\n return self._topology_name\n\n @property\n def sgbd_id(self):\n return self._sgbd_id\n\n @property\n def sgbd_name(self):\n return self._sgbd_name\n","repo_name":"bento-dbaas/monitor-provider","sub_path":"monitor_provider/providers/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"35348867147","text":"from ase.io import read\nfrom ase import Atoms\nfrom ase.calculators.emt import EMT\nfrom ase.calculators.aims import Aims\nfrom ase.constraints import FixAtoms, FixBondLengths\nfrom ase.optimize import BFGS\nfrom ase.build import fcc111, add_adsorbate, surface, molecule, bulk\nimport numpy as np\nfrom ase.visualize import view\n\n########### ISAMBARD/FHI-AIMS SPECIFIC ###############\n#import os\n#command=\"aprun -n \"+os.environ[\"NPROCS\"]+\" /home/ca-alogsdail/fhi-aims-gnu/bin/aims.\"+os.environ[\"VERSION\"]+\".scalapack.mpi.x\"\n#os.environ[\"ASE_AIMS_COMMAND\"]=command\n#os.environ[\"AIMS_SPECIES_DIR\"]=\"/home/ca-alogsdail/fhi-aims-gnu/species_defaults/light\"\n######################################################\n\n## Set separate calculators for each species:\n## Adsorbate, surface and both\n## Calculator in this case - FHI-AIMS, other choices available - see ase.calculators\n## Check configuration/bugtest with EMT calculator\n\ndef get_aims_calculator(n):\n #\"gas\" for gas-phase reactants and \"periodic\" for a periodic systems\n if(n==\"gas\"):\n return Aims(xc='pbe',\n spin='none',\n vdw_correction_hirshfeld=\"True\",\n relativistic=('atomic_zora','scalar'),\n #use_dipole_correction='True',\n #default_initial_moment=2.0,\n compute_forces=\"true\"\n #output=['mulliken']\n )\n else:\n if(n==\"periodic\"):\n return Aims(xc='pbe',\n spin='none',\n k_grid=(3,3,1),\n vdw_correction_hirshfeld=\"True\",\n relativistic=('atomic_zora','scalar'),\n use_dipole_correction='True',\n # default_initial_moment=2.0,\n compute_forces=\"true\",\n output=['mulliken'],\n elsi_restart=(\"write\",1)\n )\n\n## Make a new directory for all generated files\n## Comment/remove this section if using on HAWK - backup created by the default submission script\nimport os\nif os.path.exists(\"data_folder\"):\n print(\"Make sure to back up important data before running again in the same directory.\")\n print(\"All previous .traj configurations are overwritten\")\n print()\nos.mkdir(\"data_folder\")\nos.chdir(\"data_folder\")\n\n######ADSORBATE#########\n## Define adsorbate, rotate and pre-optimize\nmolecule=molecule(\"H2\")\n#molecule.rotate(90, 'x')\n\n## You can also read the file geometry e.g. .traj file instead of calculating every time\n#molecule = read(\"adsorbate.traj\")\n\n#molecule.set_calculator(get_aims_calculator(\"gas\"))\nmolecule.set_calculator(EMT())\n\n## Optimize\nmolecule_opt = BFGS(molecule, trajectory=\"adsorbate.traj\", restart=\"adsorbate.pckl\")\nmolecule_opt.run(fmax=0.01)\n\n############SURFACE################################\nfrom math import sqrt\n \n## Edit these\natomic_species='Au'\nshortest_M_M_distance=2.939\nunit_cell_depth=3\nunit_cell_width=3\nslab_depth=4\nvacuum_region_size=10.0\n\n## Create surface\nslab = fcc111(atomic_species, a=shortest_M_M_distance*sqrt(2), size=(unit_cell_width,unit_cell_depth,slab_depth))\n#slab = fcc100(atomic_species, a=lattice_parameter*sqrt(2), size=(unit_cell_width,unit_cell_depth,slab_depth))\n\n## Add vacuum\nslab.center(vacuum=vacuum_region_size, axis=2)\n\n## In short Pd surface\n#slab2 = fcc111('Pd', a=3.914, size=(3,3,4), vacuum=20)\n\n## For non-common(e.g. polymetallic) surfaces need to\n## Define bulk and then cut it\n#a = 3.78\n#bulk = Atoms('Pd2Cu2',\n# scaled_positions=[(0, 0, 0),\n# (0.5, 0.5, 0),\n# (0.5, 0, 0.5),\n# (0, 0.5, 0.5),\n# ],\n# cell=[a, a, a],\n# pbc=True)\n#slab3 = surface(bulk, (1, 1, 1), 4)\n#slab3.center(vacuum=10, axis=2)\n\n## Set constraint for surface/bulk characteristics\nmask0 = [atom.tag > 2 for atom in slab]\nconstraint0 = FixAtoms(mask=mask0)\nslab.set_constraint([constraint0])\n\n#slab.set_calculator(get_aims_calculator(\"periodic\"))\nslab.set_calculator(EMT())\n#print(slab.get_potential_energy())\n\n## Preview your generated surface prior to running calculations\n## Don't use this on HAWK or ISAMBARD! Job will end prematurely.\n#view(slab)\n#view(molecule)\n\n## Optimize the surface\nsurface_opt = BFGS(slab, trajectory=\"surface.traj\", restart='surface.pckl')\nsurface_opt.run(fmax=0.01)\n\n## If happy with your structures, remove triple quotes to proceed\n\"\"\"\n##########ADDING ADSORBATE ONTO THE SURFACE######\n## Remove constraints and add adsorbate\nslab.set_constraint()\n\n## If build using ase.build can specify adsorption sites\nadd_adsorbate(slab, molecule, 2.0, 'ontop')\n\n## Oherwise x-y coordinates - offset is specified in Angstrom\n#add_adsorbate(slab, molecule, 2.0, position=(4.0, 2.4))\n## Generate a new mask based on the changed number of atoms and constrain last two layers\nmask1 = [atom.tag > 2 for atom in slab]\nconstraint = FixAtoms(mask=mask1)\nslab.set_constraint([constraint])\n#slab.set_calculator(get_aims_calculator(\"periodic\"))\nslab.set_calculator(EMT())\n## Optimize\ndyn = BFGS(slab, trajectory='ads_slab.traj', restart=\"ads_slab.pckl\")\ndyn.run(fmax=0.01) #tighten to min 0.01 eV/A for actual calculation\n## Extract Binding energy from optimised structures\noptimised_molecule=read(\"adsorbate.traj\")\noptimised_surface=read(\"surface.traj\")\noptimised_slab=read(\"ads_slab.traj\")\ne_opt_molecule = optimised_molecule.get_potential_energy()\ne_opt_surface = optimised_surface.get_potential_energy()\ne_opt_slab = optimised_slab.get_potential_energy()\nprint(\"Energy of adsorbate: \", e_opt_molecule)\nprint(\"Energy of a clean surface: \", e_opt_surface)\nprint(\"Energy of an optimised slab: \", e_opt_slab)\nprint(\"Binding Energy: \", (e_opt_slab-(e_opt_molecule+e_opt_surface)))\n\"\"\"\n","repo_name":"ikowalec/software","sub_path":"build/Adsorbate.py","file_name":"Adsorbate.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"80"} +{"seq_id":"32052360914","text":"import socket\r\nimport threading\r\nPORT = 22567\r\nADDR = ('127.0.0.1', PORT)\r\ndef threaded(client, addr):\r\n \r\n print(\"[NEW CONNECTION] \" + str(ADDR) + \" connected.\")\r\n print(f\"[ACTIVE CONNECTIONS] {threading.activeCount() - 1-7}\")\r\n while True :\r\n \r\n recieved_message = client.recv(1024).decode()\r\n if recieved_message == \"CLOSE SOCKET\":\r\n break\r\n response = recieved_message.upper()\r\n client.send(bytes(response.encode()))\r\n \r\n print(f\"[ACTIVE CONNECTIONS] {threading.activeCount() - 1-8}\")\r\n\r\n client.close()\r\n# Functionality of the server\r\n#\r\n#\r\n# do not forget to release the thread if you've locked it\r\ndef main():\r\n \r\n print(\" Server is starting...\")\r\n #initiate server socket with the TCP connection\r\n server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n # binding the server socket with the localhost as ip and port number\r\n port=22567\r\n server_socket.bind(('127.0.0.1',port)) # '127.0.0.1' is the localhost in ipv4␣format\r\n # make the socket listen on this port\r\n server_socket.listen(20)\r\n # listening forever\r\n print(\" server has started, waiting for a connection\") \r\n# Open server socket as in MS0\r\n#\r\n#\r\n while True:\r\n \r\n client, addr = server_socket.accept()\r\n# Locking the thread that will be assigned to the client\r\n threading.Lock().acquire()\r\n ClientThread = threading.Thread(target=threaded, args=(client,addr))\r\n #print(f\"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}\")\r\n ClientThread.start()\r\n #print(f\"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}\")\r\n# start new thread\r\n#\r\n#\r\n \r\nif __name__ == \"__main__\":\r\n main()","repo_name":"ahmedthaabet/NETW503_ahmed_thabet_55-22567","sub_path":"MS1_ahmed_thabet_55-22567/SERVER.py","file_name":"SERVER.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"72404643779","text":"import logging\nimport time\nimport queue\nfrom abc import abstractmethod\nfrom threading import Thread\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta, MO\n\nfrom binance_client import constants\nfrom utils.time import get_candle_time, get_now\n\nimport settings\n\nfrom event.event import EventType, HeartBeatEvent\nfrom .base import BaseRunner\nfrom event.event import TimeFrameEvent\n\nlogger = logging.getLogger(__name__)\n\n\nclass TimeframePublisher:\n \"\"\"\n thread to send heartbeat\n \"\"\"\n name = 'TimeframePublisher'\n heartbeat = None\n heartbeat_counter = 0\n timezone = settings.TIMEZONE\n TIMEFRAME_CHOICES = sorted(constants.PERIOD_CHOICES, reverse=True)\n\n def __init__(self, publish_method, heartbeat=None):\n if not publish_method:\n raise Exception('publish_method is mandatory.')\n self.publish_method = publish_method\n self.heartbeat = heartbeat\n self._active = False\n\n self._candle_times = {}\n now = get_now(self.timezone)\n for timeframe in self.TIMEFRAME_CHOICES:\n self._candle_times[timeframe] = get_candle_time(now, timeframe)\n\n def run(self):\n while self._active:\n now = get_now(self.timezone)\n timestamp = int(now.timestamp())\n\n # heart beat\n if self.heartbeat and not timestamp % self.heartbeat:\n hbe = HeartBeatEvent(self.heartbeat_counter)\n self.publish_method(hbe)\n self.heartbeat_counter += 1\n # print(f'heartbeat, {now}')\n\n # publish timeframe event\n new_timeframes = []\n newest_time = None\n for timeframe in self.TIMEFRAME_CHOICES:\n newest_time = get_candle_time(now, timeframe)\n if self._candle_times[timeframe] != newest_time:\n new_timeframes.append(timeframe)\n self._candle_times[timeframe] = newest_time\n\n if new_timeframes:\n event = TimeFrameEvent(new_timeframes,\n newest_time,\n self._candle_times[new_timeframes[0]],\n self.timezone,\n now)\n self.publish_method(event)\n\n time.sleep(1)\n print('HeartbeatPublisher stopped.')\n\n def stop(self):\n self._active = False\n if self.heartbeat_counter:\n print(f'Total heartbeat = {self.heartbeat_counter}')\n\n def start(self):\n self._active = True\n self.timer = Thread(target=self.run)\n self.timer.setName(self.name)\n self.timer.setDaemon(True)\n self.timer.start()\n\n\nclass TimeframeRunner(BaseRunner):\n \"\"\"Basic runner with a heartbeat and timeframe event\"\"\"\n\n def __init__(self, enqueue, dequeue, heartbeat=None, *args, **kwargs):\n super(TimeframeRunner, self).__init__(enqueue, dequeue)\n self.register(*args)\n\n self.timeframe_publisher = TimeframePublisher(enqueue, heartbeat=heartbeat)\n\n def run(self):\n print('%s statup.' % self.__class__.__name__)\n print('Registered handler: %s' % ', '.join([x.__class__.__name__ for x in self.handlers]))\n print('\\n')\n self.timeframe_publisher.start()\n\n while self.running:\n event = self.get()\n\n if event:\n if settings.DEBUG:\n logger.debug(\n f\"New {event.type} Event: {event.__dict__ if event.type !=EventType.HEARTBEAT else ''}\")\n\n self.handle_event(event)\n\n def stop(self):\n self.timeframe_publisher.stop()\n super(TimeframeRunner, self).stop()\n\n\nif __name__ == '__main__':\n timerhandler = TimeframePublisher(5, lambda: 2)\n timerhandler.handle = lambda msg: print(1)\n timerhandler.start()\n\n # python -m event.runner\n from event.handler import *\n import queue\n\n q = queue.Queue(maxsize=2000)\n d = DebugHandler(q)\n timeframe_ticker = TimeFrameTicker(q, timezone=0)\n r = TimeframeRunner(q, 1, d, timeframe_ticker)\n r.run()\n","repo_name":"lorne-luo/venom","sub_path":"runner/timeframe.py","file_name":"timeframe.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"17248446167","text":"\"\"\"This module contains the main component for the map-page.\n All components for this page are placed on this widget.\"\"\"\nimport os\nimport pathlib\nimport math\nfrom PyQt5 import QtWidgets, QtCore, QtGui\nfrom pyqt_led import Led #pylint: disable=W0611\n\nclass MapLayout(QtWidgets.QWidget):\n \"\"\"This class inherits from a QWidget.\n It contains all components on the 'map' page.\"\"\"\n def __init__(self, MainWindow, parent):\n super().__init__(parent)\n self.main_window = MainWindow\n\n self.color_on = 'green'\n self.color_off = 'black'\n self.shape = 'circle'\n\n self.base_path = os.path.join(pathlib.Path(__file__).parent.absolute(), '../../img/')\n\n width = parent.width()\n height = parent.height()\n \n self.x_pos = [int(width * x) for x in [.34, .515, .685, .09, .89, \n .528, .718]]\n self.y_pos = [int(height * y) for y in [0.06, 0.060, 0.06, 0.26, 0.32, \n 0.765, 0.78]]\n self.diameter = int(width * 0.03)\n self.value_progress_bar = 50\n\n self.create_leds()\n self.create_progress_bar(self.value_progress_bar, width, height)\n self.create_background(width, height)\n\n def create_leds(self):\n \"\"\"Create all the LED's and place them in the correct spot.\"\"\"\n for i in range(len(self.x_pos)):\n exec(f\"self.LED_{i+1} = Led(parent=self,\" \n f\"on_color=Led.{self.color_on},\" \n f\"off_color=Led.{self.color_off},\"\n f\"shape=Led.{self.shape},\" \n f\"build='debug',\" \n f\"ind={i})\")\n exec(f\"self.LED_{i+1}.setGeometry(QtCore.QRect({self.x_pos[i]}, {self.y_pos[i]},\" \n f\"{self.diameter}, {self.diameter}))\")\n exec(f\"self.LED_{i+1}.setCheckable(False)\")\n \n def create_progress_bar(self, default_value, width, height):\n \"\"\"Create the progress bar to visualize the amount of hydrogen stored.\"\"\"\n # self.storage_bar = QtWidgets.QProgressBar(self)\n # self.storage_bar.setGeometry(QtCore.QRect(int(width * 0.310), int(height * 0.5), \n # int(width * 0.021), int(height * 0.25)))\n # self.storage_bar.setProperty(\"value\", default_value)\n # self.storage_bar.setOrientation(QtCore.Qt.Vertical)\n self.text_font = QtGui.QFont()\n self.text_font.setPixelSize(int(height * 0.05))\n\n self.storage_level = QtWidgets.QLabel(self)\n self.storage_level.setFont(self.text_font)\n self.storage_level.setText(\"0 mL\")\n self.storage_level.setGeometry(QtCore.QRect(int(width * 0.395), int(height * 0.5), \n int(width * 0.1), int(height * 0.25)))\n # self.hydrogen_text.setAlignment(QtCore.Qt.AlignTop|QtCore.Qt.AlignLeft)\n\n # self.storage_bar.setDisabled(True)\n #self.storage_bar.setAutoFillBackground(True)\n # self.storage_bar.setStyleSheet(\" \")\n\n def create_background(self, width, height):\n \"\"\"Create a label to display a background image.\"\"\"\n \n self.map_picture = QtWidgets.QLabel(self)\n self.map_picture.setGeometry(QtCore.QRect(0, 0, width, height))\n self.map_picture.setPixmap(QtGui.QPixmap(self.base_path + 'None.png'))\n self.map_picture.setScaledContents(True)\n self.map_picture.lower()\n\n def get_current_values(self, values, readings):\n \"\"\"Update the map to match with the current data.\n Use multiple other functions to accomplish this.\"\"\"\n solar = values[0] #readings['zonPC']\n wind = values[1] #readings['windPC'] \n demand = values[2] #readings['loadPC']\n h2ref = readings['H2_PC']\n self.storage_level.setText(\"{0:.0f} mL\".format(readings['tank_level']))\n self.update_background(solar, demand)\n self.update_leds(solar, wind, demand, h2ref)\n \n # def update_progress_bar(self, val):\n # \"\"\"Update the progress bar to match with the current data.\"\"\"\n # self.storage_bar.setProperty('value', val)\n # self.storage_bar.update()\n # self.value_progress_bar = val\n \n def update_background(self, solar_power, power_demand):\n \"\"\"Update the background to match with the current data.\"\"\"\n solar_power = round(solar_power, 0)\n power_demand = round(power_demand, 0) if self.value_progress_bar > 0 else 0\n\n val = \"SL\" + str(min(math.floor(power_demand / 25), 3)) if solar_power > 50 else \"L\" + str(min(math.floor(power_demand / 25), 3)) #pylint: disable=line-too-long\n \n \n self.map_picture.setPixmap(QtGui.QPixmap(self.base_path + f\"{val}.png\"))\n \n def update_leds(self, solar, wind, demand, diff):\n \"\"\"Update the LED's to match with the current data.\"\"\"\n led_list = []\n solar = round(solar, 0)\n demand = round(demand, 0)\n\n if diff > 0 and self.value_progress_bar < 100:\n led_list.append(1)\n elif diff < 0 and self.value_progress_bar > 0:\n led_list.append(6)\n \n if solar > 50:\n led_list.append(7)\n \n if wind > 50:\n led_list.append(4)\n \n if demand > 75 and self.value_progress_bar > 0:\n led_list.append(2)\n led_list.append(3)\n led_list.append(5)\n elif demand > 50 and self.value_progress_bar > 0:\n led_list.append(2)\n led_list.append(5)\n elif demand >= 25 and self.value_progress_bar > 0:\n led_list.append(2)\n \n for led in range(1, len(self.x_pos) + 1):\n if led in led_list:\n exec(f\"self.LED_{led}.set_status(True)\")\n else:\n exec(f\"self.LED_{led}.set_status(False)\")\n \n\n\n \n","repo_name":"FabianBallast/BEP","sub_path":"UI/src/src/map/map_layout.py","file_name":"map_layout.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"39043350720","text":"from benchtmpl.workflow.parameter.base import TemplateParameter\n\nimport benchtmpl.error as err\nimport benchtmpl.workflow.parameter.declaration as pd\n\n\ndef create_parameter_index(parameters, validate=True):\n \"\"\"Create instances of template parameters from a list of dictionaries\n containing parameter declarations. The result is a dictionary containing the\n top-level parameters, indexed by their unique identifier.\n\n Parameters\n ----------\n parameters: list(dict)\n List of dictionaries containing template parameter declarations\n validate: bool, optional\n Flag indicating if given template parameter declarations are to be\n validated against the parameter schema or not.\n\n Returns\n -------\n dict(benchtmpl.workflow.parameter.base.TemplateParameter)\n\n Raises\n ------\n benchtmpl.error.InvalidTemplateError\n benchtmpl.error.UnknownParameterError\n \"\"\"\n result = dict()\n for para in parameters:\n # Validate the template parameters if the validate flag is True\n if validate:\n pd.validate_parameter(para)\n # Create a TemplateParameter instance for the parameter. Keep\n # track of children for parameter that are of type DT_LIST or\n # DT_RECORD. Children are added after all parameters have been\n # instantiated.\n p_id = para[pd.LABEL_ID]\n # Ensure that the identifier of all parameters are unique\n if p_id in result:\n raise err.InvalidTemplateError('parameter \\'{}\\' not unique'.format(p_id))\n c = None\n if para[pd.LABEL_DATATYPE] in [pd.DT_LIST, pd.DT_RECORD]:\n c = list()\n tp = TemplateParameter(pd.set_defaults(para), children=c)\n result[p_id] = tp\n # Add parameter templates to the list of children for their\n # respective parent (if given). We currently only support one level\n # of nesting.\n for para in parameters:\n if pd.LABEL_PARENT in para:\n p_id = para[pd.LABEL_ID]\n parent = para[pd.LABEL_PARENT]\n if not parent is None:\n result[parent].add_child(result[p_id])\n return result\n\n\ndef sort_parameters(parameters):\n \"\"\"Sort a given list of parameter declaration by the parameter index that is\n part of the parameter declaration. Parameters with the same index value are\n ordered by increasing value of their name.\n\n Parameters\n ----------\n parameters: list(benchtmpl.workflow.parameter.base.TemplateParameter)\n List of termplate parameters\n\n Returns\n -------\n list(benchtmpl.workflow.parameter.base.TemplateParameter)\n \"\"\"\n return sorted(parameters, key=lambda p: (p.index, p.identifier))\n","repo_name":"scailfin/benchmark-templates","sub_path":"benchtmpl/workflow/parameter/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38846714405","text":"from diagrams import Cluster, Diagram, Edge\nfrom diagrams.aws.network import Endpoint\nfrom diagrams.c4 import Container\nfrom diagrams.onprem.database import ClickHouse\nfrom diagrams.onprem.network import Nginx\nfrom diagrams.onprem.queue import Kafka\n\nwith Diagram(\n \"UGC Service\", show=False, direction=\"TB\", graph_attr={\"splines\": \"spline\"}\n):\n gateway = Nginx(\"API Gateway\")\n with Cluster(\"API\"):\n endpoint = Endpoint(\"Endpoint\")\n token_validator = Container(\n \"Token Validator\", description=\"Validate token signature\"\n )\n payload_serializer = Container(\n \"Payload Serializer\", description=\"Validate and serialize data\"\n )\n api_kafka = Container(\"Kafka Producer\")\n\n kafka = Kafka(\"UGC Storage\")\n\n with Cluster(\"UGC ETL\"):\n etl_kafka = Container(\"Kafka Consumer\")\n data_transformer = Container(\n \"Transformer\", description=\"Prepare data before loading\"\n )\n etl_olap = Container(\"OLAP Connector\")\n\n olap = ClickHouse(\"OLAP DB\")\n\n gateway >> Edge(label=\"Incoming packet\") >> endpoint\n\n endpoint >> token_validator\n endpoint >> payload_serializer >> api_kafka >> kafka\n\n kafka >> etl_kafka >> data_transformer >> etl_olap >> olap\n","repo_name":"stranded-in-python/movix","sub_path":"architecture/movix-ugc.py","file_name":"movix-ugc.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38463782327","text":"#!/usr/bin/env python3\nimport Adafruit_BBIO.GPIO as GPIO\n\nGPIO.setup(\"P8_8\", GPIO.IN)\nGPIO.setup(\"P8_10\", GPIO.IN)\nGPIO.setup(\"P8_12\", GPIO.IN)\nGPIO.setup(\"P8_14\", GPIO.IN)\nGPIO.setup(\"P8_16\", GPIO.OUT)\nGPIO.setup(\"P8_18\", GPIO.OUT)\nGPIO.setup(\"P8_15\", GPIO.OUT)\nGPIO.setup(\"P8_17\", GPIO.OUT)\n\ndef my_callback(inputbutton):\n\tif inputbutton == \"P8_8\":\n\t\tGPIO.output(\"P8_16\", GPIO.input(\"P8_8\"))\n\tif inputbutton == \"P8_10\":\n\t\tGPIO.output(\"P8_18\", GPIO.input(\"P8_10\"))\n\tif inputbutton == \"P8_12\":\n\t\tGPIO.output(\"P8_15\", GPIO.input(\"P8_12\"))\n\tif inputbutton == \"P8_14\":\n\t\tGPIO.output(\"P8_17\", GPIO.input(\"P8_14\"))\n\nGPIO.add_event_detect(\"P8_8\", GPIO.BOTH, callback = my_callback, bouncetime=20)\nGPIO.add_event_detect(\"P8_10\", GPIO.BOTH, callback = my_callback, bouncetime=20)\nGPIO.add_event_detect(\"P8_12\", GPIO.BOTH, callback = my_callback, bouncetime=20)\nGPIO.add_event_detect(\"P8_14\", GPIO.BOTH, callback = my_callback, bouncetime=20)\n\nwhile True:\n\tcontinue\n","repo_name":"efast616/ECE434","sub_path":"hw02/buttonPress.py","file_name":"buttonPress.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26895343090","text":"import telebot\r\nimport sympy\r\nimport random\r\n\r\nfrom telebot import types\r\n\r\nbot = telebot.TeleBot('token')\r\n\r\n\r\n# @bot.message_handler(commands=['start'])\r\n# def welcome(message):\r\n# sti = open('static/welcome.webp', 'rb')\r\n# bot.send_sticker(message.chat.id, sti)\r\n#\r\n# # keyboard\r\n# markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n# item1 = types.KeyboardButton(\"🎲 Рандомное число\")\r\n# item2 = types.KeyboardButton(\"😊 Как дела?\")\r\n#\r\n# markup.add(item1, item2)\r\n#\r\n# bot.send_message(message.chat.id,\r\n# \"Добро пожаловать, {0.first_name}!\\nЯ - {1.first_name}, бот созданный чтобы быть подопытным кроликом.\".format(\r\n# message.from_user, bot.get_me()),\r\n# parse_mode='html', reply_markup=markup)\r\n\r\n\r\n@bot.message_handler(content_types=['text'])\r\ndef lalala(message):\r\n try:\r\n if message.chat.type == 'private':\r\n\r\n if message.text == '/start':\r\n bot.send_message(message.chat.id, 'ХАЙ')\r\n return\r\n\r\n x, y = sympy.symbols('x y')\r\n\r\n usertext = message.text.split('\\n')\r\n\r\n xi = usertext[0].split('=')\r\n eta = usertext[1].split('=')\r\n enterux = usertext[2].split('=')\r\n enteruy = usertext[3].split('=')\r\n enteruxx = usertext[4].split('=')\r\n enteruyy = usertext[5].split('=')\r\n enteruxy = usertext[6].split('=')\r\n\r\n xix = sympy.diff(xi[1], x)\r\n xixx = sympy.diff(xix, x)\r\n xiy = sympy.diff(xi[1], y)\r\n xiyy = sympy.diff(xiy, y)\r\n etax = sympy.diff(eta[1], x)\r\n etaxx = sympy.diff(etax, x)\r\n etay = sympy.diff(eta[1], y)\r\n etayy = sympy.diff(etay, y)\r\n etaxy = sympy.diff(etay, x)\r\n xixy = sympy.diff(xiy, x)\r\n\r\n xixy, xix, xiy, xiyy = str(xixy), str(xix), str(xiy), str(xiyy)\r\n etax, etaxx, etay, etayy = str(etax), str(etaxx), str(etay), str(etayy)\r\n etaxy, xixy = str(etaxy), str(xixy)\r\n\r\n dicfun = {'*log(e)': ''}\r\n\r\n for key in dicfun.keys():\r\n xixy = xixy.replace(key, dicfun[key])\r\n xix = xix.replace(key, dicfun[key])\r\n xiy = xiy.replace(key, dicfun[key])\r\n xiyy = xiyy.replace(key, dicfun[key])\r\n etax = etax.replace(key, dicfun[key])\r\n etaxx = etaxx.replace(key, dicfun[key])\r\n etay = etay.replace(key, dicfun[key])\r\n etayy = etayy.replace(key, dicfun[key])\r\n etaxy = etaxy.replace(key, dicfun[key])\r\n xixy = xixy.replace(key, dicfun[key])\r\n\r\n bot.send_message(message.chat.id, f'ξx={xix}\\nξy={xiy}\\n')\r\n bot.send_message(message.chat.id, f'ηx={etax}\\nηy={etay}\\n')\r\n bot.send_message(message.chat.id, f'ξxx={xixx}\\nξyy={xiyy}\\n')\r\n bot.send_message(message.chat.id, f'ηxx={etaxx}\\nηyy={etayy}\\n')\r\n bot.send_message(message.chat.id, f'ξxy={xixy}\\nηxy={etaxy}\\n')\r\n\r\n dicvar = {'a': 'Uξ', 'b': 'Uη', 'g': 'Uξη', 'd': 'Uξξ', 'f': 'Uηη'}\r\n\r\n ux = sympy.simplify(f'a*{xix} + b*{etax}')\r\n uy = sympy.simplify(f'a*{xiy} + b*{etay}')\r\n uxx = sympy.simplify(\r\n f'd*{xix}*{xix} + 2*g*{xix}*{etax} + f*{etax}*{etax} + a*{xixx} + b*{etaxx}')\r\n uxy = sympy.simplify(\r\n f'd*{xix}*{xiy} + g*({xix}*{etay} + {xiy}*{etax}) + f*{etax}*{etay} + a*{xixy} + b*{etaxy}')\r\n uyy = sympy.simplify(\r\n f'd*{xiy}*{xiy} + 2*g*{xiy}*{etay} + f*{etay}*{etay} + a*{xiyy} + b*{etayy}')\r\n\r\n ux = str(ux)\r\n uy = str(uy)\r\n uyy = str(uyy)\r\n uxx = str(uxx)\r\n uxy = str(uxy)\r\n\r\n equat = sympy.simplify(\r\n f'{enterux[1]}*({ux}) + {enteruy[1]}*({uy}) + {enteruxx[1]}*({uxx}) + {enteruyy[1]}*({uyy}) + {enteruxy[1]}*({uxy})')\r\n\r\n equat = str(equat)\r\n\r\n for key in dicvar.keys():\r\n ux = ux.replace(key, dicvar[key])\r\n uy = uy.replace(key, dicvar[key])\r\n uxx = uxx.replace(key, dicvar[key])\r\n uxy = uxy.replace(key, dicvar[key])\r\n uyy = uyy.replace(key, dicvar[key])\r\n equat = equat.replace(key, dicvar[key])\r\n\r\n bot.send_message(message.chat.id, f'Ux={ux}\\nUy={uy}\\nUxx={uxx}\\nUyy={uyy}\\nUxy={uxy}\\n')\r\n bot.send_message(message.chat.id, f'Подстановка: {equat}')\r\n\r\n # if message.text == '🎲 Рандомное число':\r\n # bot.send_message(message.chat.id, str(random.randint(0, 100)))\r\n # elif message.text == '😊 Как дела?':\r\n #\r\n # markup = types.InlineKeyboardMarkup(row_width=2)\r\n # item1 = types.InlineKeyboardButton(\"Хорошо\", callback_data='good')\r\n # item2 = types.InlineKeyboardButton(\"Не очень\", callback_data='bad')\r\n #\r\n # markup.add(item1, item2)\r\n #\r\n # bot.send_message(message.chat.id, 'Отлично, сам как?', reply_markup=markup)\r\n # else:\r\n # bot.send_message(message.chat.id, 'Я не знаю что ответить 😢')\r\n\r\n except Exception as e:\r\n bot.send_message(message.chat.id, 'непон')\r\n\r\n\r\n# @bot.callback_query_handler(func=lambda call: True)\r\n# def callback_inline(call):\r\n# try:\r\n# if call.message:\r\n# if call.data == 'good':\r\n# bot.send_message(call.message.chat.id, 'Вот и отличненько 😊')\r\n# elif call.data == 'bad':\r\n# bot.send_message(call.message.chat.id, 'Бывает 😢')\r\n#\r\n# # remove inline buttons\r\n# bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=\"😊 Как дела?\",\r\n# reply_markup=None)\r\n#\r\n# # show alert\r\n# bot.answer_callback_query(callback_query_id=call.id, show_alert=False,\r\n# text=\"ЭТО ТЕСТОВОЕ УВЕДОМЛЕНИЕ!!11\")\r\n#\r\n# except Exception as e:\r\n# print(repr(e))\r\n\r\n\r\n# RUN\r\nbot.polling(none_stop=True)\r\n","repo_name":"kulikrch/BotMath","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"21468730765","text":"\"\"\"\nTotal selling prices, total capital gains, and total capital losses calculated\nfrom the CSV files.\n\"\"\"\n\nimport csv\nfrom codecs import iterdecode\nfrom decimal import Decimal\nfrom typing import Iterable, List, Optional, Tuple\n\nfrom ibkr_report.definitions import (\n CURRENCY,\n USE_DEEMED_ACQUISITION_COST,\n AssetCategory,\n DataDiscriminator,\n Field,\n FieldValue,\n ReportOptions,\n TradeDetails,\n)\nfrom ibkr_report.exchangerates import ExchangeRates\nfrom ibkr_report.trade import Trade\n\n\nclass Report:\n \"\"\"Total selling prices, total capital gains, and total capital losses\n calculated from the CSV files.\n\n When calculating the amount of profit or loss, you can deduct the deemed\n acquisition cost from the selling price of the shares, instead of deducting\n the purchase price of the shares as well as the expenses incurred in\n making a profit.\n\n Args:\n file (Iterable[bytes]): The input file in CSV format.\n report_currency (str): The currency used in the output.\n use_deemed_acquisition_cost (bool): Whether to use the deemed acquisition cost\n if it benefits you.\n\n Attributes:\n prices (Decimal): Total selling prices.\n gains (Decimal): Total capital gains.\n losses (Decimal): Total capital losses.\n details(List[TradeDetails]): Details from trades such as dates and quantities.\n options (ReportOptions): Report currency, whether to use the deemed\n acquisition cost.\n rates (ExchangeRates): Euro foreign exchange rates.\n \"\"\"\n\n prices: Decimal = Decimal(0)\n gains: Decimal = Decimal(0)\n losses: Decimal = Decimal(0)\n details: List[TradeDetails]\n options: ReportOptions\n rates: ExchangeRates\n _trade: Optional[Trade] = None\n\n def __init__(\n self,\n file: Optional[Iterable[bytes]] = None,\n report_currency: str = CURRENCY,\n use_deemed_acquisition_cost: bool = USE_DEEMED_ACQUISITION_COST,\n ) -> None:\n self.details = []\n self.options = ReportOptions(\n report_currency=report_currency.upper(),\n deemed_acquisition_cost=use_deemed_acquisition_cost,\n fields={},\n )\n self.rates = ExchangeRates()\n if file:\n self.add_trades(file)\n\n def add_trades(self, file: Iterable[bytes]) -> None:\n \"\"\"Adds trades from a CSV formatted report file.\"\"\"\n try:\n for items_list in csv.reader(iterdecode(file, \"utf-8\")):\n items = tuple(items_list)\n self._handle_one_line(items)\n except UnicodeDecodeError as err:\n raise ValueError(\"Input data not in UTF-8 text format.\") from err\n\n def is_stock_or_options_trade(self, items: Tuple[str, ...]) -> bool:\n \"\"\"Checks whether the current row is part of a trade or not.\"\"\"\n if (\n len(self.options.fields) == len(items)\n and items[self.options.fields[Field.TRADES]] == FieldValue.TRADES\n and items[self.options.fields[Field.HEADER]] == FieldValue.HEADER\n and items[self.options.fields[Field.DATA_DISCRIMINATOR]]\n in (DataDiscriminator.TRADE, DataDiscriminator.CLOSED_LOT)\n and items[self.options.fields[Field.ASSET_CATEGORY]]\n in (AssetCategory.STOCKS, AssetCategory.OPTIONS)\n ):\n return True\n return False\n\n def _handle_one_line(self, items: Tuple[str, ...]) -> None:\n if all(item in items for item in Field):\n self.options.fields = {}\n self._trade = None\n for index, item in enumerate(items):\n self.options.fields[item] = index\n return\n if self.options.fields and self.is_stock_or_options_trade(items):\n self._handle_trade(items)\n\n def _handle_trade(self, items: Tuple[str, ...]) -> None:\n \"\"\"Parses prices, gains, and losses from trades.\"\"\"\n if (\n items[self.options.fields[Field.DATA_DISCRIMINATOR]]\n == DataDiscriminator.TRADE\n ):\n self._trade = Trade(items, self.options, self.rates)\n self.prices += self._trade.total_selling_price\n if (\n items[self.options.fields[Field.DATA_DISCRIMINATOR]]\n == DataDiscriminator.CLOSED_LOT\n ):\n if not self._trade:\n raise ValueError(\"Tried to close a lot without trades.\")\n details = self._trade.details_from_closed_lot(items)\n if details.realized > 0:\n self.gains += details.realized\n else:\n self.losses -= details.realized\n self.details.append(details)\n","repo_name":"oittaa/ibkr-report-parser","sub_path":"ibkr_report/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"80"} +{"seq_id":"23360941423","text":"from dao import intent_dao, dialogue_dao\nfrom util.comUtil import CommonUtil\nfrom util.logger import Logger\n\n\n# (通过意图创建对话列表)\ndef copyDialogue(workspace_id, version_id, cookie):\n intentList = intent_dao.getIntentList(workspace_id, version_id, cookie)\n for one in intentList:\n dialogue = dialogue_dao.addDialogue(one[\"name\"], one[\"description\"], workspace_id, version_id, cookie)\n dialogue_dao.updateDialogue(dialogue[\"id\"], dialogue[\"id\"], workspace_id, version_id, cookie)\n dialogue_dao.addRelationShipIntentAndDialogue(dialogue[\"id\"], one[\"id\"], workspace_id, version_id, cookie)\n\n\n# (通过意图创建对话列表)\ndef createDialogue(workspace_id, version_id, dialogue_name, intent_id, cookie):\n dialogue = dialogue_dao.addDialogue(dialogue_name, dialogue_name, workspace_id, version_id, cookie)\n dialogue_dao.updateDialogue(dialogue[\"id\"], dialogue[\"id\"], workspace_id, version_id, cookie)\n dialogue_dao.addRelationShipIntentAndDialogue(dialogue[\"id\"], intent_id, workspace_id, version_id, cookie)\n return dialogue\n\n\n# (通过意图创建对话列表)\ndef createDialogueOld(workspace_id, dialogue_name, intent_id, cookie):\n dialogue = dialogue_dao.addDialogueOld(dialogue_name, dialogue_name, workspace_id, cookie)\n dialogue_dao.updateDialogueOld(dialogue[\"id\"], dialogue[\"id\"], workspace_id, cookie)\n dialogue_dao.addRelationShipIntentAndDialogueOld(dialogue[\"id\"], intent_id, workspace_id, cookie)\n return dialogue\n\n\n# 更新对话信息\ndef updateDialogueInfo(workspace_id, version_id, cookie):\n dialogueList = dialogue_dao.getDialogueList(workspace_id, version_id, cookie)\n for dialogue in dialogueList:\n if dialogue is None:\n continue\n dialogue_dao.updateDialogue(dialogue[\"id\"], dialogue[\"id\"], workspace_id, version_id, cookie)\n Logger.info(\"dialogue_id:{}, dialogue_name:{}\".format(dialogue[\"id\"], dialogue[\"name\"]))\n\n\n# 获取对话列表\ndef getDialogueNew(workspace_id, version_id, dialogue_name, cookie):\n dialogueList = dialogue_dao.getDialogueList(workspace_id, version_id, cookie)\n dialogue_id = -2\n for dialogue in dialogueList:\n if dialogue_name == dialogue[\"name\"]:\n dialogue_id = \"{}\".format(dialogue[\"id\"])\n Logger.info(\"dialogue_id:{}, dialogue_name:{}\".format(dialogue[\"id\"], dialogue[\"name\"]))\n break\n return dialogue_id\n\n\n# 获取对话列表\ndef getDialogueList(workspace_id, version_id, cookie):\n dialogueList = dialogue_dao.getDialogueList(workspace_id, version_id, cookie)\n return dialogueList\n\n\n# 获取对话列表-旧\ndef getDialogueOld(workspace_id, dialogue_name, cookie):\n dialogueList = dialogue_dao.getDialogueFromOld(workspace_id, cookie)\n dialogue_id = -2\n for dialogue in dialogueList:\n if dialogue_name in dialogue[\"name\"]:\n dialogue_id = \"{}\".format(dialogue[\"id\"])\n Logger.info(\"dialogue_id:{}, dialogue_name:{}\".format(dialogue[\"id\"], dialogue[\"name\"]))\n break\n return dialogue_id\n\n\ndef getAllDialogueIds(workspace_id, version_id, cookie):\n dialogueList = dialogue_dao.getDialogueList(workspace_id, version_id, cookie)\n ids = []\n for i in range(0, len(dialogueList)):\n ids.append(dialogueList[i][\"id\"])\n return ids\n\n\n# 根据话术内容获取对话ID\ndef getDialogueIdByContext(workspace_id, version_id, context, cookie):\n util = CommonUtil()\n dialogue_name = util.get_dialogue_name(context)\n if dialogue_name is None:\n return -2\n dialogue_id = getDialogueNew(workspace_id, version_id, dialogue_name, cookie)\n return dialogue_id\n\n\n# 根据话术内容获取跳转子流程\ndef getDialogueName(context):\n util = CommonUtil()\n dialogue_name = util.get_dialogue_name(context)\n if dialogue_name is None:\n return None\n return dialogue_name\n\n\n# 根据话术内容获取对话ID\ndef getDialogueIdByContextOld(workspace_id, context, cookie):\n util = CommonUtil()\n dialogue_name = util.get_dialogue_name(context)\n if dialogue_name is None:\n return -2\n dialogue_id = getDialogueOld(workspace_id, dialogue_name, cookie)\n return dialogue_id\n\n\n\nif __name__ == '__main__':\n cookie = \"JSESSIONID=node018srjpu2kwxm11ikflal8aevwc330973.node0\"\n node_id = getDialogueIdByContext(74915, 74916, \"【引导加微环节-挂机】|【常规首句】\", cookie)\n print(node_id)\n pass","repo_name":"LiangYa/pythonBot","sub_path":"service/dialogue_service.py","file_name":"dialogue_service.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"6640780958","text":"import random\nfrom queens_fitness import fitness_fn_positive\n\n\np_mutation = 1\nnum_of_generations = 150\ncrossover_rate = 0.9\n\n\ndef genetic_algorithm(population, fitness_fn, minimal_fitness):\n for generation in range(num_of_generations):\n print(\"Generation {}:\".format(generation) + \" \" + str(len(population)))\n #print_population(population, fitness_fn)\n\n new_population = set()\n\n for i in range(len(population)):\n mother, father = random_selection(population)\n \n if random.uniform(0, 1) < crossover_rate:\n child1, child2 = reproduce(mother, father, fitness_fn)\n\n if random.uniform(0, 1) < p_mutation:\n child1 = mutate(child1)\n\n if random.uniform(0, 1) < p_mutation:\n child2 = mutate(child2)\n\n new_population.add(child1)\n new_population.add(child2)\n\n # Add new population to population, use union to disregard\n # duplicate individuals\n\n population = population.union(new_population)\n\n population = prune_population(population)\n\n fittest_individual = get_fittest_individual(population, sorter)\n\n if minimal_fitness <= fitness_fn(fittest_individual):\n break\n\n print(\"Final generation {}:\".format(generation))\n print_population(population)\n\n return fittest_individual\n\ndef sorter(individual):\n return individual[1]\n\n\ndef prune_population(population):\n \n list_population = list(population)\n\n print(\"Before: \" + str(len(list_population)))\n\n list_population.sort(key=sorter, reverse = True)\n\n length = len(list_population)\n\n if (length > 130 ):\n place = int(1/2 * length) \n else: \n place = 130\n\n list_population = list_population[0: place]\n print(\"After: \" + str(len(list_population)))\n\n\n return set(list_population)\n\n\n \n\ndef print_population(population):\n for individual in population:\n fitness = individual[1]\n print(\"{} - fitness: {}\".format(individual[0], fitness))\n\n\ndef reproduce(mother, father, fitness_fn):\n '''\n Reproduce two individuals with single-point crossover\n Two children are returned.\n '''\n\n mother = list(mother[0])\n father = list(father[0])\n \n child1 = []\n child2 = []\n\n crossover = random.randrange(0, len(mother))\n for i in range(len(mother)):\n if i < crossover:\n child1.append(mother[i])\n child2.append(father[i])\n else:\n child1.append(father[i])\n child2.append(mother[i])\n\n return (tuple(child1), fitness_fn((child1, 0))), (tuple(child2), fitness_fn([child2, 0]))\n\n\ndef mutate(individual):\n '''\n Mutate an individual by randomly assigning one of its bits\n Return the mutated individual\n '''\n\n mutation = list(individual)\n\n index = random.randrange(len(mutation))\n if (mutation[index] == 0):\n mutation[index] = 1\n elif (mutation[index] == 1):\n mutation[index] = 0\n\n return tuple(mutation)\n\n\ndef random_selection(population):\n \"\"\"\n Compute fitness of each in population according to fitness_fn and add up\n the total. Then choose 2 from sequence based on percentage contribution to\n total fitness of population\n Return selected variable which holds two individuals that were chosen as\n the mother and the father\n \"\"\"\n\n # Python sets are randomly ordered. Since we traverse the set twice, we\n # want to do it in the same order. So let's convert it temporarily to a\n # list.\n ordered_population = list(population)\n\n fitness_list = []\n\n for chromosome in ordered_population:\n fitness_list.append(chromosome[1])\n\n total_score = sum(fitness_list)\n\n selected = []\n\n for i in range(2):\n r = random.randrange(total_score * 100) / 100\n score_counter = 0\n for chromosome in ordered_population:\n score_counter += chromosome[1]\n if score_counter >= r:\n selected.append(chromosome)\n break\n\n return selected[0], selected[1]\n\n\n\ndef get_fittest_individual(iterable, func):\n return max(iterable, key=func)\n\n\ndef get_initial_population(n, count):\n '''\n Randomly generate count individuals of length n\n Note since its a set it disregards duplicate elements.\n '''\n return set([\n tuple(random.randrange(0, n) for _ in range(n))\n for _ in range(count)\n ])\n\ndef calculate_fitness(population, fitness_fn):\n \n pop = list(population)\n setpop = []\n\n for i in pop:\n setpop.append((i, fitness_fn((i, 0))))\n\n return set(setpop)\n\n\n\ndef main():\n minimal_fitness = 28\n\n # Curly brackets also creates a set, if there isn't a colon to indicate a dictionary\n\n initial_population = get_initial_population(8, 8)\n\n initial_population = calculate_fitness(initial_population, fitness_fn_positive)\n\n fittest = genetic_algorithm(initial_population, fitness_fn_positive, minimal_fitness)\n print('Fittest Individual: ' + str(fittest) + \" with fitness \" + str(fitness_fn_positive(fittest)))\n\n\nif __name__ == '__main__':\n pass\n main()\n","repo_name":"ratgen/artificial_intelligence","sub_path":"perat17-AI-handin/week10/Homework/ga_queens.py","file_name":"ga_queens.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"30740200436","text":"'''\nCreated on Mar 27, 2018\n\n@author: Stefan\n'''\nfrom random import randint,random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom Problem import Problem\nfrom Population import Population\nfrom Individ import Individ\n\nclass Algorithm():\n def __init__(self):\n self.problem = Problem()\n self.readProblem()\n self.pop = Population(self.problem.getDimPop(),self.problem.getXMin(), self.problem.getXMax(), self.problem.getYMin(), self.problem.getYMax())\n \n \n \n def readProblem(self):\n self.problem.loadData(\"C:\\\\Users\\\\Stefan-PC\\\\eclipse-workspace\\\\Lab2EA\\\\input.txt\")\n \n def run(self,noIteratii): \n \n results = []\n for i in range(noIteratii):\n self.iteration(self.pop, self.problem.getPM(), self.problem.getXMin(), self.problem.getXMax(), self.problem.getYMin(), self.problem.getYMax())\n \n fitnessValues = []\n for x in self.pop.individs:\n fitnessValues.append(x.fitness())\n fitnessValues = sorted(fitnessValues)\n \n results.append(fitnessValues[0])\n \n \"\"\" arr = np.array(results)\n m = np.mean(arr,axis=0)\n means=[]\n for i in range(noIteratii):\n means.append(m)\n plt.plot(range(0,noIteratii),means)\n plt.plot( range(0,noIteratii),results)\n plt.show()\n \"\"\"\n return fitnessValues[0]\n \n\n \n def iteration(self,pop, pM, xmin, xmax, ymin, ymax):\n '''\n an iteration\n \n pop: the current population\n pM: the probability the mutation to occur\n xmin, xmax, ymin, ymax: bounds for x and y\n '''\n newGen = []\n \n recompPop = self.pop.selectForRecombination(self.problem.getDimPop() // 2)\n for i in range(self.problem.getDimPop() // 2):\n i1=randint(0,recompPop.getLen()-1)\n i2=randint(0,recompPop.getLen()-1)\n if (i1!=i2):\n c=recompPop[i1].blendcorssover(recompPop[i2])\n c.mutate(pM, xmin, xmax, ymin, ymax)\n #c2.mutate(pM,xmin,xmax,ymin,ymax)\n newGen.append(c)\n else:\n i-=1\n self.pop.selectForSurvival(newGen)\n\n \n","repo_name":"stefandelibas/UBB","sub_path":"AI/Lab2EA/Algorithm.py","file_name":"Algorithm.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"15823975495","text":"import torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader,random_split\nfrom torch.nn.utils import clip_grad_value_\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom ddc_pub.custom_callbacks import LearningRateSchedule\nfrom data_gen import Data_generate\nfrom parser import args\nfrom torch_model3 import Model_mol_all\n# from torch_modelaae import Model_mol_all\nimport numpy as np\nimport h5py\nfrom vectorizers import SmilesVectorizer\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3\"\n##########################load dataset######################################\ndata = Data_generate(\"datasets/DRD2_TRAIN_MOLS.h5\")\nprint('generate dataset ok!')\ntrain_size = int(0.9 * len(data))\nval_size = len(data) - train_size\ntrain_data, val_data = random_split(data, [train_size, val_size])\ntrainloader = DataLoader(dataset=train_data,batch_size=args.batch_size,shuffle=False,num_workers=8,drop_last=True)\nvalloader = DataLoader(dataset=val_data,batch_size=args.batch_size,shuffle=False,num_workers=8)\nlen(trainloader)\nlen(valloader)\n\n#########################weight init############################################\n # 1. 根据网络层的不同定义不同的初始化方式\ndef weight_init(m):\n if isinstance(m, nn.Linear):\n nn.init.xavier_normal_(m.weight)\n nn.init.constant_(m.bias, 0)\n # elif isinstance(m, nn.LSTM):\n # nn.init.xavier_normal_(m.weight.data)\n # 是否为批归一化层\n elif isinstance(m, nn.BatchNorm1d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n#################################adjust_lr#####################################\n# model = Model_mol_all(args)\n# #将weight_init应用在子模块上\n# model.apply(weight_init)\n# model.cuda()\n# optimizer = Adam(model.parameters(), lr=args.lr)\n# def adjust_lr(optimizer, epoch, epoch_to_start=500, last_epoch=999,\n# lr_init=1e-3, lr_final=1e-6,lr=args.lr):\n# decay_duration = last_epoch - epoch_to_start\n# if epoch < epoch_to_start:\n# cur_lr = lr\n# else:\n# # Slope of the decay\n# k = -(1 / decay_duration) * np.log(lr_final / lr_init)\n#\n# ad_lr = lr_init * np.exp(-k * (epoch - epoch_to_start))\n# cur_lr = ad_lr\n# for param_group in optimizer.param_groups:\n# param_group['lr'] = cur_lr\n# for epoch in args.epochs:\n# adjust_lr(optimizer, epoch)\n#########################train model########################################\ndef train():\n smilesvec1 = SmilesVectorizer(\n canonical=False,\n augment=True,\n maxlength=args.maxlen,\n charset=args.charset,\n binary=False,\n )\n model = Model_mol_all(args)\n #将weight_init应用在子模块上\n model.apply(weight_init)\n model.cuda()\n # model = nn.DataParallel(model)\n # model = nn.DataParallel(model, device_ids=[0, 1])\n optimizer = Adam(model.parameters(), lr=args.lr)\n scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=args.patience,\n verbose=True,min_lr=1e-6)\n criterion = nn.NLLLoss()\n # criterion = nn.CrossEntropyLoss()\n for epoch in range(args.epochs):\n train_losses = []\n model.train()\n pred_list = []\n\n for batch_idx, (enc_x, dec_x, dec_y) in enumerate(trainloader):\n train_correct = 0\n\n enc_x,dec_x,dec_y = enc_x.cuda(),dec_x.cuda(),dec_y.cuda()\n #print('dec_y',dec_y.shape)#[64, 132]\n\n optimizer.zero_grad()\n enc_output,y_pre = model(enc_x, dec_x)#[64, 35, 132]\n print(enc_output)\n print(enc_output.shape)\n #print('y_pre',y_pre.shape)\n loss = criterion(y_pre, dec_y)\n train_losses.append(loss.item())\n # Backward and optimizer\n loss.backward()\n\n pred_gpu = torch.argmax(y_pre, dim=1)\n pred = pred_gpu.cpu().numpy()\n pred_list.extend(pred)\n\n train_correct += pred_gpu.eq(dec_y).sum().item()\n print('pred_gpu',pred_gpu[0])\n print('dec_y',dec_y[0])\n\n ## 按值裁剪\n ### 指定clip_value之后,裁剪的范围就是[-clip_value, clip_value]\n # clip_grad_value_(model.parameters(), clip_value = args.clip_value)\n optimizer.step()\n if batch_idx % 100 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}\\tTrain_accuracy: {:.6f}'.format(\n epoch, batch_idx, len(trainloader),\n 100. * batch_idx / len(trainloader), loss.item(),\n train_correct / (args.batch_size*pred.shape[-1])\n ))\n\n ############################save train smiles#####################################\n if epoch == 9:\n smiles_list = []\n for j in pred_list:\n smiles = \"\".join(smilesvec1._int_to_char[i] for i in j if i != 33)\n smiles_list.append(smiles)\n smiles_ar = np.array(smiles_list)\n print(\"transform to smiles finish!\\n\")\n dt = h5py.special_dtype(vlen=str)\n with h5py.File('torch_datasets/train_smiles_list.hdf5', 'w') as f:\n ds = f.create_dataset('smiles', smiles_ar.shape, dtype=dt)\n ds[:] = smiles_ar\n print(\"save train_smiles_list!\\n\")\n\n ####validate####\n model.eval()\n val_total_loss = 0\n correct = 0\n pred_list_v = []\n with torch.no_grad():\n val_losses = []\n for enc_input_v, dec_input_v, dec_output_v in valloader:\n enc_x_v,dec_x_v,dec_y_v = enc_input_v.cuda(), dec_input_v.cuda(), dec_output_v.cuda()\n #print(enc_x.shape)#torch.Size([64, 133, 35])\n enc_output,y_pre_v = model(enc_x_v, dec_x_v)#torch.Size([64, 35, 132])\n #print('y_pre_v:',y_pre.shape)#torch.Size([64, 35, 132])\n val_loss = criterion(y_pre_v, dec_y_v)\n val_losses.append(val_loss.item())\n\n pred_gpu = torch.argmax(y_pre_v, dim=1)\n #print('pred',pred.shape)\n #print(pred.shape)#torch.Size([64, 132])\n pred = pred_gpu.cpu().numpy()\n pred_list_v.extend(pred)\n\n correct += pred_gpu.eq(dec_y_v).sum().item()\n\n with open(\"datasets/mean_train_loss\", \"a\") as f:\n f.write(str(np.mean(train_losses)))\n f.write('\\n')\n with open(\"datasets/mean_val_loss\", \"a\") as f:\n f.write(str(np.mean(val_losses)))\n f.write('\\n')\n print('\\ntrain mean loss:{:.6f}\\nval mean loss:{:.4f}\\n'.format(np.mean(train_losses),np.mean(val_losses)))\n print('val accuracy:({:.6f})\\n'.format(correct / (val_size*pred.shape[-1])))\n\n scheduler.step(val_loss)\n ######################save val smiles#############################\n if epoch == 30:\n smiles_list_v = []\n for j in pred_list_v:\n smiles = \"\".join(smilesvec1._int_to_char[i] for i in j if i != 33)\n smiles_list_v.append(smiles)\n smiles_ar = np.array(smiles_list_v)\n print(\"transform to smiles finish!\\n\")\n dt = h5py.special_dtype(vlen=str)\n with h5py.File('torch_datasets/val_smiles_list.hdf5', 'w') as f:\n ds = f.create_dataset('smiles', smiles_ar.shape, dtype=dt)\n ds[:] = smiles_ar\n print(\"save val_smiles_list!\\n\")\n\n\n torch.save(model.state_dict(), 'torch_models/model_params.pkl')\n # 保存和加载整个模型\n torch.save(model, 'torch_models/model.pkl')\n print('save model finish!')\n #model = torch.load('model.pkl')\n\nif __name__ == '__main__':\n train()\n\n","repo_name":"baitutanglj/torch1.4_Deep-Drug-Coder","sub_path":"train_torch_model3.py","file_name":"train_torch_model3.py","file_ext":"py","file_size_in_byte":7775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"24865001116","text":"days = {\n 'Domingo': 0,\n 'Jueves': 1,\n 'Lunes': 2,\n 'Martes': 3,\n 'Miercoles': 4,\n 'Sabado': 5,\n 'Viernes': 6,\n}\ntowns = {\n 'azcapotzalco': 0,\n 'coyoacan': 1,\n 'cuajimalpa': 2,\n 'gam': 3,\n 'iztacalco': 4,\n 'iztapalapa': 5,\n 'magdalena': 6,\n 'milpa': 7,\n 'alvaro': 8,\n 'tlahuac': 9,\n 'tlalpan': 10,\n 'xochimilco': 11,\n 'benito': 12,\n 'cuauhtemoc': 13,\n 'miguel': 14,\n 'venustiano': 15,\n}\naccidents = {\n 'accidente-choque con lesionados': 0,\n}","repo_name":"carloslme/ds-portfolio","sub_path":"predictive-analytics/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39199421823","text":"from os import name\nfrom clustering_hyperparameters.dataset.dataset import Dataset\nfrom .metrics import get_all_metrics\nfrom clustering_hyperparameters.models.clustering_model import ClusteringModel\n\n\nimport numpy as np\nfrom sklearn.preprocessing import normalize\n\n\nfrom pathlib import Path\nimport time\n\ndef cluster(config):\n # setup model\n model, dataset, dataset_labels = setup(config)\n model.fit(dataset)\n predicted_labels = model.get_labels()\n metrics = get_all_metrics(dataset_labels, predicted_labels)\n return metrics\n\n\ndef setup(config):\n \"\"\"\n Setup and return the datasets and model required for training.\n\n :param config: config dictionary\n :return: Tuple of datasets and model required for training.\n \"\"\"\n dataset_index = int(config[\"dataset_index\"])\n to_normalize = config[\"normalize\"]\n dataset_name = config[\"suite\"][\"datasets\"][dataset_index][\"name\"]\n\n suite_name = config[\"suite\"][\"name\"]\n cache_dir = config[\"suite\"][\"cache_dir\"]\n\n dataset_obj = Dataset(name=dataset_name, data_path=None, cache_dir=cache_dir, autoload=True)\n\n dataset, dataset_labels = dataset_obj.get_all()\n \n if to_normalize:\n dataset = normalize(dataset) \n\n model_name = config[\"model\"][\"base_model\"]\n model_params = config[\"model\"][\"params\"]\n\n model = ClusteringModel.by_name(model_name)(**model_params)\n return model, dataset, dataset_labels\n","repo_name":"mishra-sid/clustering_hyperparameters","sub_path":"src/clustering_hyperparameters/cluster/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"35399041029","text":"import asyncio\nfrom pyppeteer import connect, launch\n\n# webSocketDebuggerUrl = 'ws://45.254.64.7:9222/devtools/browser/11ec6655-2eab-4524-ad73-0a074042c932'\n\n\nasync def close_dialog(dialog):\n if dialog.message == '1':\n print('detect xss')\n await dialog.dismiss()\n\n\n\nasync def scan(url):\n browser = await launch(headless=True, args=['--disable-xss-auditor'])\n # 连接chrome实例\n # browser = await connect({'browserWSEndpoint': webSocketDebuggerUrl})\n page = await browser.newPage()\n page.on('dialog', lambda dialog: asyncio.ensure_future(close_dialog(dialog)))\n await page.goto(url)\n await page.close()\n await browser.close()\n\n\nif __name__ == '__main__':\n payload = '\">'\n url = 'http://vps.yy/info.php?id=1{payload}'.format(payload=payload)\n print(url)\n\n\n\n asyncio.get_event_loop().run_until_complete(scan(url))","repo_name":"aboutbo/UltraPlus","sub_path":"plugins/xss/xss.py","file_name":"xss.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38917106324","text":"import numpy as np\n\nfrom msmbuilder.decomposition import tICA, SparseTICA\nfrom msmbuilder.example_datasets import DoubleWell\n\n\ndef build_dataset():\n slow = DoubleWell(random_state=0).get_cached().trajectories\n data = []\n\n # each trajectory is a double-well along the first dof,\n # and then 9 degrees of freedom of gaussian white noise.\n for s in slow:\n t = np.hstack((s, np.random.randn(len(s), 9)))\n data.append(t)\n return data\n\n\ndef test_doublewell():\n data = build_dataset()\n tica = tICA(n_components=1).fit(data)\n tic0 = tica.components_[0]\n\n stica = SparseTICA(n_components=1, verbose=False).fit(data)\n stic0 = stica.components_[0]\n\n np.testing.assert_array_almost_equal(stic0[1:], np.zeros(9))\n np.testing.assert_almost_equal(stic0[0], 0.58, decimal=1)\n","repo_name":"bojunliu0818/msmbuilder2022","sub_path":"msmbuilder/tests/test_sparsetica.py","file_name":"test_sparsetica.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"4836137881","text":"import pandas as pd\r\nimport numpy as np\r\nfrom app.utils.groupCal import calcByCondition, calcRet, create_sharpe_ratio, create_drawdowns, calcByConditionOneFive\r\nfrom app.utils.const import noneed_column\r\n\r\n\r\ndef getDatasInStore():\r\n data = pd.read_pickle(r'mongodata.pkl')\r\n return data\r\n\r\n\r\ndef getDataInTerm(datas, startdate, enddate):\r\n data = datas.loc[(datas['date'] >= startdate) & (datas['date'] <= enddate)]\r\n return data\r\n\r\n\r\ndef getChartsXaxis(datas, universe, frequency):\r\n datelist = datas[(datas.universe == universe) & (datas.frequency == frequency)][\"date\"].unique()\r\n return datelist.tolist()\r\n\r\n\r\ndef get_table1_result(dotdict):\r\n datas = getDatasInStore()\r\n datasTerms = getDataInTerm(datas, dotdict.startDate, dotdict.endDate)\r\n dotdict.datas = datasTerms\r\n dateList = getChartsXaxis(datasTerms, dotdict.universe, dotdict.frequency)\r\n allYAxisDatas = []\r\n save_dict_list = []\r\n groupList = [1.0, 2.0, 3.0, 4.0, 5.0]\r\n for group in groupList:\r\n dotdict.group = group\r\n conditionValues, multiValues = calcByCondition(dotdict)\r\n # 计算年化收益率的方法, 传入的值为初始序列\r\n rateByYearOne = calcRet(conditionValues)\r\n\r\n # 调用计算夏普比率的函数,返回一个数值类型的值\r\n sharpRatioOne = create_sharpe_ratio(conditionValues)\r\n\r\n # 调用最大回撤的函数,返回三个值,第一个值:最大回撤值,第二个值:开始时间,第三个值:结束时间\r\n # i j 只是列表的索引\r\n maxDownOne, i, j = create_drawdowns(multiValues)\r\n # print(maxDownOne, i, j)\r\n\r\n savedict = {'group': group,\r\n 'rateByYear': rateByYearOne,\r\n 'sharpRatio': sharpRatioOne,\r\n 'maxDown': maxDownOne,\r\n 'startDate': i,\r\n \"endDate\": j}\r\n save_dict_list.append(savedict)\r\n allYAxisDatas.append(multiValues)\r\n\r\n # 2.计算1.0-5.0和5.0-1.0 计算时这两个和其他五个组分开计算\r\n conditionValuesOneFive, multiValuesOneFive = calcByConditionOneFive(dotdict)\r\n # 开始计算这两个的指标值\r\n for i, m, group_name in zip(conditionValuesOneFive, multiValuesOneFive, ['1.0-5.0', '5.0-1.0']): # 1-5 和 5-1 共2个\r\n # 调用计算年化收益率的函数,返回一个数值类型的值\r\n rateByYearOne = calcRet(conditionValuesOneFive[i])\r\n # 调用计算夏普比率的函数,返回一个数值类型的值\r\n sharpRatioOne = create_sharpe_ratio(conditionValuesOneFive[i])\r\n # 调用计算最大回撤值的函数,返回一个数值类型的值\r\n maxDownOne, j, k = create_drawdowns(multiValuesOneFive[m])\r\n # 将返回值的结果放入列表中\r\n allYAxisDatas.append(multiValuesOneFive[m])\r\n savedict = {'group': group_name,\r\n 'rateByYear': rateByYearOne,\r\n 'sharpRatio': sharpRatioOne,\r\n 'maxDown': maxDownOne,\r\n 'startDate': j,\r\n \"endDate\": k}\r\n save_dict_list.append(savedict)\r\n\r\n tabledata = pd.DataFrame(save_dict_list)\r\n\r\n # 因为最大回撤时间段需要最大回撤的计算之后,所以在最后进行计算,计算最大回撤时间段,传入三个参数,第一个日期列表,第二个开始时间数字列表,第三个,结束时间数字列表\r\n # 定义一个存储最大回撤开始和结束组合而成的序列\r\n\r\n tabledata['startDate'] = tabledata['startDate'].apply(lambda x: str(dateList[x]))\r\n tabledata['endDate'] = tabledata['endDate'].apply(lambda x: str(dateList[x]))\r\n tabledata['maxDownTimeTerms'] = tabledata['startDate'].str.cat([tabledata.endDate], sep='-')\r\n\r\n # 根据之前算的7个组的年化收益率和最大回撤值来计算收益回撤比,返回的也是一个List列表\r\n # 计算回撤收益比 先保留三位小数再去绝对值\r\n tabledata['getByMaxDown'] = (tabledata['rateByYear'] / tabledata['maxDown']).apply(lambda x: abs(round(x + 0.0001, 3)))\r\n\r\n # 展示表格的格式转换\r\n tabledata['rateByYear'] = tabledata['rateByYear'].apply(lambda x: format(x, '.2%'))\r\n tabledata['sharpRatio'] = tabledata['sharpRatio'].apply(lambda x: round(x + 0.0001, 2))\r\n tabledata['maxDown'] = tabledata['maxDown'].apply(lambda x: round(x, 4))\r\n tabledata['getByMaxDown'] = tabledata['getByMaxDown'].apply(lambda x: format(x, '.2%'))\r\n\r\n return tabledata, dateList, allYAxisDatas\r\n\r\n\r\ndef get_table2_result(dotdict):\r\n # 获取右边的表格\r\n # 调用方法拿到所有要求的字段名\r\n datas = getDatasInStore()\r\n datasTerms = getDataInTerm(datas, dotdict.startDate, dotdict.endDate)\r\n dotdict.datas = datasTerms\r\n columnNames = datasTerms.columns.values\r\n # 定义一个不需要的列名list const里面的noneed_column\r\n deleteColumn = np.array(noneed_column)\r\n columnNames = np.setdiff1d(columnNames, deleteColumn, assume_unique=False)\r\n\r\n table2_dict_list = []\r\n\r\n for columnName in columnNames:\r\n dotdict.columnName = columnName\r\n\r\n # 拿到1-5和5-1的初始值和累乘值,两个变量都是List,每个List中的每一个项都是List类型\r\n conditionValuesOneFive, multiValuesOneFive = calcByConditionOneFive(dotdict)\r\n for i, m, tf in zip(conditionValuesOneFive, multiValuesOneFive, [0, 1]): # 1-5 和 5-1 共2个\r\n # 调用计算年化收益率的函数,返回一个数值类型的值\r\n rateByYearOne = calcRet(conditionValuesOneFive[i])\r\n # 调用计算最大回撤值的函数,返回一个数值类型的值\r\n maxDownOne, j, k = create_drawdowns(multiValuesOneFive[m])\r\n # 将返回值的结果放入列表中\r\n if tf == 0:\r\n table2_dict = {\"columnName\": columnName,\r\n \"rateByYear\": rateByYearOne,\r\n \"maxDown\": maxDownOne\r\n }\r\n if tf == 1:\r\n table2_dict = {\"columnName\": '-' + columnName,\r\n \"rateByYear\": rateByYearOne,\r\n \"maxDown\": maxDownOne\r\n }\r\n table2_dict_list.append(table2_dict)\r\n # 计算每一个指标收益回撤比,两个值1-5 和 5-1\r\n # 将年化收益率和收益回撤比分别加到List中去\r\n # 储存所有column的\r\n\r\n table2data = pd.DataFrame(table2_dict_list)\r\n\r\n table2data['getByMaxDown'] = (table2data['rateByYear'] / table2data['maxDown']).apply(lambda x: abs(round(x + 0.0001, 3)))\r\n\r\n # 表格排序,默认按照年化收益率倒叙排列\r\n table2_data = table2data[[\"columnName\", 'rateByYear', 'getByMaxDown']].sort_values(by=\"rateByYear\", ascending=False)\r\n\r\n # 展示表格的格式转换\r\n table2_data['rateByYear'] = table2_data['rateByYear'].apply(lambda x: format(x, '.2%'))\r\n table2_data['getByMaxDown'] = table2_data['getByMaxDown'].apply(lambda x: format(x, '.2%'))\r\n\r\n return table2_data\r\n","repo_name":"wydaisyck/Full-Stack-Data-Visualization","sub_path":"app/utils/get_table_result.py","file_name":"get_table_result.py","file_ext":"py","file_size_in_byte":7140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5022390787","text":"'''Входные данные\n\nШесть чисел x1, y1, r1, x2, y2, r2, где x1, y1, x2, y2 - координаты центров окружностей, а r1, r2 – их радиусы.\nВсе числа - действительные, не превышают по модулю 109, заданы не более чем с тремя знаками после запятой.\n\nВыходные данные\n\nКоличество точек пересечения. Если точек пересечения бесконечно много, то вывести -1.\n\nin = 0 0 5 5 0 1\n\nout = 2\n\n'''\nimport math\n\ndata = input()\nmas = data.split(\" \")\n\nr1 = int(mas[2])\nr2 = int(mas[5])\nR = r1 + r2\n\nx = abs(int(mas[0])) + abs(int(mas[3]))\ny = abs(int(mas[1])) + abs(int(mas[4]))\n\nL = math.sqrt(pow(x, 2) + (pow(y, 2)))\n\nif (R > L):\n print(2)\nelif (R < L):\n print(0)\nelif (R == L):\n print(1)\n","repo_name":"dm-stulov/e-olimp","sub_path":"Две окружности.py","file_name":"Две окружности.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"3787325801","text":"\r\n### Method 1 Using Simple Iteration\r\n### Run a while loop with the condition number >0.\r\n### Extract the last digit as Remainder using Modulo operator.\r\n### Using the formula reverse = ( reverse * 10 ) + remainder , we keep changing the reverse value.\r\n### Break down the Nunber using divide operator.\r\n### Print the reverse variable\r\n\r\n\r\n\r\nn = int(input(\"Enter a number:\"))\r\nrev=0\r\n\r\nwhile n>0:\r\n rev = rev * 10 + n % 10\r\n n=n//10\r\n\r\nprint(rev)\r\n\r\n\r\n## ***********************************************************************************************************\r\n\r\n\r\n\r\n### Method 2: Using String Slicing\r\n##-1 displays index in reverse order, but we should convert it into string\r\n\r\nnum = int(input(\"Enter Number:\"))\r\nprint(str(num)[::-1]) \r\n\r\n\r\n\r\n## ***********************************************************************************************************\r\n\r\n\r\n\r\n\r\n### Method 3: Using Recursion\r\n### Define a recursive function recursum() that takes in number and reverse variable as arguments.\r\n### Set the base case as number == 0 and step recursive call as recursum(num/10, reverse).\r\n### Print the returned value using print() function\r\n\r\n\r\ndef recursum(number,reverse):\r\n if number==0:\r\n return reverse\r\n remainder = int(number%10)\r\n reverse = (reverse*10)+remainder\r\n return recursum(int(number/10),reverse)\r\n\r\nnum = int(input(\"Enter number to be reversed: \"))\r\nreverse = 0\r\nprint(\"The reversed order is: \",recursum(num,reverse))\r\n ","repo_name":"Pranav0-3/Python","sub_path":"100-py-codes/Getting-Started/reverse-num.py","file_name":"reverse-num.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"80"} +{"seq_id":"24603255957","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport os\nimport sys\n\nfrom time import time\nfrom knn import KNN\nfrom utils import load_dataset, PeekablePriorityQueue, get_distance\n\n\ndef mds(dist, target):\n # [vec, val] = eigs(-.5*(D.^2 - sum(D.^2)'*ones(1,N)/N -\n # ones(N,1)*sum(D.^2)/N + sum(sum(D.^2))/(N^2)), max(dims), 'LR', opt);\n # mds 算法的具体实现\n # data:需要降维的矩阵\n # target:目标维度\n # return:降维后的矩阵\n dim = dist.shape[0]\n if target > dim:\n target = dim\n dist_ij = np.asarray(dist, np.float64)\n dist_ij_2 = dist_ij ** 2\n dist_i_2 = np.dot(np.mean(dist_ij_2, axis=1).reshape((dim, 1)), np.ones((1, dim)))\n dist_j_2 = np.dot(np.ones((dim, 1)), np.mean(dist_ij_2, axis=0).reshape((1, dim)))\n dist_2 = np.mean(np.mean(dist_ij_2, axis=1))\n b = -0.5*(dist_ij_2-dist_i_2-dist_j_2+dist_2)\n eig_val, eig_vec = np.linalg.eig(b)\n list_idx = np.argsort(eig_val)[-target:]\n return np.dot(eig_vec[:, list_idx], np.sqrt(np.diag(eig_val[list_idx])))\n\n\ndef isomap(data, target, k):\n # isomap 算法的具体实现\n # data:需要降维的矩阵\n # target:目标维度\n # k:k 近邻算法中的超参数\n # return:降维后的矩阵\n inf = float('inf')\n data_count = data.shape[0]\n if k >= data_count:\n raise ValueError('K的值最大为数据个数 - 1')\n distance_mat = get_distance(data)\n knn_map = np.ones([data_count, data_count], np.float64) * inf\n adjlist = [[] for _ in range(data_count)]\n for idx in range(data_count):\n top_k = np.argpartition(distance_mat[idx], k)[:k + 1]\n # 使用无向边\n for p in top_k:\n p = int(p)\n if p != idx:\n adjlist[p].append(idx)\n adjlist[idx].append(p)\n for idx in range(data_count):\n adjlist[idx] = [(dst, distance_mat[idx][dst]) for dst in np.unique(adjlist[idx])]\n for idx in range(data_count):\n if not dijkstra(knn_map, adjlist, idx):\n return None\n return mds(knn_map, target)\n\n\ndef dijkstra(dist, adjlist, src):\n pqueue = PeekablePriorityQueue()\n pqueue.put((0, src))\n dist[src][src] = 0\n done = np.array([False]*dist.shape[0])\n while not pqueue.empty():\n sdist, u = pqueue.get()\n if done[u]:\n continue\n done[u] = True\n for dst, tdist in adjlist[u]:\n if dist[src][dst] > sdist + tdist:\n dist[src][dst] = sdist + tdist\n pqueue.put((dist[src][dst], dst))\n if not done.all():\n print(\"not complete\", done.shape[0]-np.count_nonzero(done))\n return False\n return True\n\n\n# ---------------------------- main ---------------------------- #\n\n\nDIR = './two datasets/'\nif __name__ == \"__main__\":\n start = time()\n if len(sys.argv) < 2:\n fileNamePrefix = 'sonar'\n else:\n fileNamePrefix = sys.argv[1]\n if len(sys.argv) < 3:\n n_components = 10\n else:\n n_components = int(sys.argv[2])\n train_X, train_Y = load_dataset(os.path.join(DIR, fileNamePrefix+\"-train.txt\"))\n test_X, test_Y = load_dataset(os.path.join(DIR, fileNamePrefix + \"-test.txt\"))\n data = np.concatenate((train_X, test_X))\n k = 6 if fileNamePrefix == 'sonar' else 4\n while True:\n data_low = isomap(data, n_components, k)\n # train_X_low = isomap(train_X, n_components, k)\n # test_X_low = isomap(test_X, n_components, k)\n # if train_X_low is not None and test_X_low is not None:\n if data_low is not None:\n break\n k += 1\n print('k of the knn:', k)\n train_X_low, test_X_low = data_low[:train_X.shape[0], :], data_low[train_X.shape[0]:, :]\n one_NN = KNN(train_X_low, train_Y, 1, n_components)\n test_y_pred = one_NN.predict(test_X_low)\n print('isomap(k={0:d},data={1:s}): {2:.4f}%'.\n format(n_components, fileNamePrefix, one_NN.score(test_Y, test_y_pred)*100))\n stop = time()\n print('time spent:', str(stop - start) + \"s\")\n\n","repo_name":"Solomonwisdom/Assignments","sub_path":"AML/homework1/isomap.py","file_name":"isomap.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5600170503","text":"# Pour pouvoir utiliser les fonctions de upemtk\nfrom upemtk import *\nimport psycopg2\n\ntry:\n cnx = psycopg2.connect(\"dbname='irwin' user='irwin' password=''\")\nexcept:\n print(\"An error occurred while connecting to the database!\")\nelse:\n cnx.autocommit = True\n cursor = cnx.cursor()\n requete = \"SELECT ref_batiment, hauteur FROM batiment;\"\n\n hauteurs = list()\n\n cursor.execute(requete)\n for result in cursor:\n hauteurs.append(result[1])\n\n cursor.close()\n cnx.close()\n\n LARGEUR_FENETRE = 400\n HAUTEUR_FENETRE = 400\n cree_fenetre(LARGEUR_FENETRE, HAUTEUR_FENETRE)\n\n\n for i, h in enumerate(hauteurs):\n rectangle(i * 20, HAUTEUR_FENETRE, (i + 1) * 20, HAUTEUR_FENETRE - h, remplissage='black')\n\n attente_clic()\n ferme_fenetre()\n","repo_name":"SlamaFR/L2-S3-Databases","sub_path":"TP4/python_sqlcity.py","file_name":"python_sqlcity.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26381063413","text":"bunker = {el: {} for el in input().split(', ')}\nn = int(input())\n\nfor _ in range(n):\n categories, items, info = input().split(' - ')\n quantity, quality = [int(z) for x in info.split(\";\") for z in x.split(\":\") if z.isdigit()]\n\n bunker[categories].update({items: [quantity, quality]})\n\ncount_items = sum([int(v[0]) for key, value in bunker.items() for k, v in value.items()])\nsum_quality = sum([int(v[1]) for key, value in bunker.items() for k, v in value.items()])\navg_quality = sum_quality / len(bunker)\nprint(f'Count of items: {count_items}')\nprint(f'Average quality: {avg_quality:.2f}')\n\nfor k, value in bunker.items():\n print(f\"{k} -> {', '.join([el for el in value.keys()])}\")","repo_name":"StoianBodurov/SoftUni","sub_path":"Python/Advanced/04-Comprehensions/exercise/9_bunker.py","file_name":"9_bunker.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"21221987737","text":"class Solution:\n def checkPerfectNumber(self, num: int) -> bool:\n # im thinking you just do the loop itself and see how it can be optimized\n # although one thing i can think of is that you only need to do up to half of n where n is num\n # you simply iterate and when you find i % n is 0 you add to that result and then also i //n as well\n # then you stop at n/2\n # you actually wanna stop after the sqrt and not num/2\n \n if num == 1:\n return False\n \n res = 0\n for i in range(1,int(sqrt(num) + 1)):\n if num % i == 0:\n res += i\n res += num // i \n res -= num\n print(res)\n \n return res == num\n \n ","repo_name":"nyeap96/LeetCode","sub_path":"507.py","file_name":"507.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"8894643098","text":"import PySimpleGUI as sg\n\nf = open(\"number.txt\", \"r\")\ncounter = f.read()\n\nsg.change_look_and_feel('DarkGrey3') \nlayout = [[sg.Image(\".png\",size=(68,88)),sg.Text(counter, font=(\"Arial\",40), key=\"upb\"), sg.Button(\" \",image_filename=\"Up.png\", enable_events=True)]]\n\n# Create the window\nwindow = sg.Window(\"Counter\", layout)\n\n# Create an event loop\nwhile True:\n event, values = window.read()\n # End program if user closes window or\n if event == \" \":\n f = open(\"number.txt\", \"r\")\n test = f.read()\n counter = int(test)\n \n counter += 1\n w = open(\"number.txt\", \"w\")\n w.write(str(counter))\n w.close()\n window[\"upb\"].update(counter)\n \n \n # presses the OK button\n if event == sg.WIN_CLOSED:\n break\n\nwindow.close()\n","repo_name":"MyrddynEmrys/simplecounter","sub_path":"counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"23278769992","text":"# encoding: utf-8\n\nfrom __future__ import print_function\nfrom keras.callbacks import LambdaCallback\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.optimizers import RMSprop\nfrom keras.models import load_model\nfrom janome.tokenizer import Tokenizer\nimport numpy as np\nimport random\nimport sys\nimport io\n\ndef sample(preds, temperature=1.0):\n # helper function to sample an index from a probability array\n preds = np.asarray(preds).astype('float64')\n preds = np.log(preds) / temperature\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n probas = np.random.multinomial(1, preds, 1)\n return np.argmax(probas)\n\n#\ndef get_token(text):\n text =Tokenizer().tokenize(text, wakati=True) # 分かち書きする\n return text\n\n#data\n\n#s= get_token(\"本日は、朝早く起きてました。\")\n#print(s)\n#quit()\nmaxlen = 5\nstep = 1\nsentences = []\nnext_chars = []\npath = './data.txt'\nwith io.open(path, encoding='utf-8') as f:\n text = f.read().lower()\nprint('corpus length:', len(text))\n\ntext =Tokenizer().tokenize(text, wakati=True) # 分かち書きする\n#print(text[0 :5])\n#quit()\n\nchars = text\ncount = 0\nchar_indices = {} # 辞書初期化\nindices_char = {} # 逆引き辞書初期化\n\nfor word in chars:\n if not word in char_indices: # 未登録なら\n char_indices[word] = count # 登録する \n count +=1\n# print(count,word) # 登録した単語を表示\n# 逆引き辞書を辞書から作成する\nindices_char = dict([(value, key) for (key, value) in char_indices.items()])\n\nstart_index = 0\n#quit()\n#\nprint('Build model...')\nmodel=load_model('model.h5')\n\n#pred\nfor diversity in [0.2]: # diversity は 0.2のみ使用 \n print('----- diversity:', diversity)\n generated = ''\n text= get_token(\"どんなつまらない仕事でも楽しんでやるのだ\")\n sentence = text[start_index: start_index + maxlen]\n generated += \"\".join(sentence)\n print(sentence )\n print('----- Generating with seed: \"' + \"\".join(sentence)+ '\"')\n sys.stdout.write(generated)\n\n for i in range(400):\n x_pred = np.zeros((1, maxlen, len(chars)))\n for t, char in enumerate(sentence):\n x_pred[0, t, char_indices[char]] = 1.\n\n preds = model.predict(x_pred, verbose=0)[0]\n next_index = sample(preds, diversity)\n next_char = indices_char[next_index]\n\n generated += next_char\n sentence = sentence[1:]\n # sentence はリストなので append で結合する\n sentence.append(next_char) \n\n sys.stdout.write(next_char)\n sys.stdout.flush()\n print()\n","repo_name":"kuc-arc-f/LSTM_make_colab","sub_path":"pred2.py","file_name":"pred2.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"43901517712","text":"\"\"\"\nA* Search\n---------\nHeuristic-based search for the shortest path in a graph.\n\nSee https://en.wikipedia.org/wiki/A*_search_algorithm\n\n\"\"\"\n\nimport heapq\nfrom typing import List, Tuple\n\n\nclass MinHeap:\n \"\"\"\n Min-heap implementation supporting updates to existing elements in constant time.\n\n Maintains a standard heap and a dictionary of current values for each element,\n allowing duplicates in the heap.\n\n Parameters\n ----------\n elements : [(int, int)]\n List of elements as (x, value).\n\n Methods\n -------\n add(x : int, value: float) -> None\n Adds x to the heap, and updates its value in the dictionary.\n The heap may contain multiple copies of x.\n pop() -> (int, float)\n Returns the minimum element from the heap. Pops from the heap until an element\n is found with a value matching its current value in the dictionary.\n \"\"\"\n\n def __init__(self, elements: List[Tuple[int, float]]):\n self.heap = [(val, x) for x, val in elements]\n self.elements = {x: val for x, val in elements}\n heapq.heapify(self.heap)\n\n def __len__(self) -> int:\n \"\"\"Returns the number of elements.\"\"\"\n return len(self.elements)\n\n def __contains__(self, x: int) -> bool:\n \"\"\"Returns True if x is an element of the MinHeap.\"\"\"\n return x in self.elements\n\n def add(self, x: int, value: float):\n \"\"\"Adds an element x to the MinHeap and updates the value in the dictionary.\"\"\"\n if x in self.elements and self.elements[x] == value:\n return\n self.elements[x] = value\n heapq.heappush(self.heap, (value, x))\n return\n\n def pop(self) -> Tuple[int, float]:\n \"\"\"Returns the minimum valid element from the heap.\"\"\"\n val, x = heapq.heappop(self.heap)\n while x not in self.elements or self.elements[x] != val:\n val, x = heapq.heappop(self.heap)\n del self.elements[x]\n return x, val\n\n\ndef find_shortest_path(\n grid: List[List[float]],\n src: Tuple[int, int],\n dst: Tuple[int, int],\n) -> List[Tuple[int, int]]:\n \"\"\"\n Finds the shortest path in a grid via A-star heuristic search.\n\n Let grid[i, j] = 0 if location (i, j) is blocked and cannot be traversed\n = c if passing through location (i, j) has cost c, c > 0\n\n A* proceeds as follows:\n • Choose the frontier node u with the minimum estimated cost to the destination.\n • For each neighbor v of u:\n • If the path to v through u is better than the current path to v:\n • Record u as the predecessor of v in the shortest known path to v.\n • Estimate the cost from v to the destination with heuristic function h(v).\n • Add v to the frontier with its estimated cost.\n\n Time : O(E), or O(b^d)\n Space : O(V), or O(b^d)\n\n where V is the number of vertices (nm), E is the number of edges (4nm), b is the\n branching factor (4), and d is the solution depth, or path length.\n \"\"\"\n n, m = len(grid), len(grid[0])\n\n def _h(v: Tuple[int, int]) -> float:\n \"\"\"Heuristic function for path selection. Estimates cost from v --> dst as the\n cost of going through v plus the manhattan distance between v to dst.\n \"\"\"\n return grid[v[0]][v[1]] + abs(dst[0] - v[0]) + abs(dst[1] - v[1])\n\n # prev[u] is the predecessor of u in shortest known path to u\n prev = dict()\n # cost[u] is the cost of the shortest path from src --> u\n cost = {(i, j): float(\"inf\") for i in range(n) for j in range(m)}\n\n prev[src] = src\n cost[src] = 0\n queue = MinHeap([(src, _h(src))])\n while len(queue) > 0:\n # Choose the frontier node with the minimum estimated cost to the destination\n u, _ = queue.pop()\n if u == dst:\n # Build path by traversing predecessors\n path = [dst]\n u = dst\n while u != prev[u]:\n u = prev[u]\n path.append(u)\n return path[::-1]\n\n # Explore neighbors\n r, c = u\n for i, j in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):\n if not (0 <= i < n and 0 <= j < m) or grid[i][j] == 0:\n continue\n v = (i, j)\n # If the path to neighbor v through u is better than the existing path to v\n cost_to_v_through_u = cost[u] + grid[r][c]\n if cost_to_v_through_u < cost[v]:\n prev[v] = u\n cost[v] = cost_to_v_through_u\n est_cost_to_dst = cost[v] + _h(v)\n queue.add(x=v, value=est_cost_to_dst)\n return None\n\n\ndef test_find_shortest_path():\n grid = [\n [1, 1, 1, 1, 1],\n [1, 1, 1, 5, 1],\n [1, 1, 5, 1, 1],\n [1, 5, 1, 1, 1],\n [5, 1, 1, 1, 1],\n ]\n src = (0, 0)\n dst = (4, 4)\n shortest_path = [\n (0, 0),\n (0, 1),\n (0, 2),\n (0, 3),\n (0, 4),\n (1, 4),\n (2, 4),\n (3, 4),\n (4, 4),\n ]\n\n path = find_shortest_path(grid, src, dst)\n assert all(x == y for x, y in zip(path, shortest_path))\n\n\ndef test_find_shortest_path_2():\n grid = [\n [1, 1, 1, 1, 1],\n [1, 0, 0, 0, 1],\n [1, 1, 9, 1, 1],\n [1, 0, 0, 0, 1],\n [1, 1, 1, 1, 1],\n ]\n src = (2, 1)\n dst = (2, 3)\n find_shortest_path(grid, src, dst)\n\n shortest_path = [(2, 1), (2, 2), (2, 3)]\n\n path = find_shortest_path(grid, src, dst)\n assert all(x == y for x, y in zip(path, shortest_path))\n\n\ndef test_find_shortest_path_3():\n grid = [\n [1, 20, 1, 1, 1],\n [1, 0, 1, 0, 1],\n [1, 0, 1, 0, 1],\n [1, 0, 1, 0, 1],\n [1, 1, 1, 20, 1],\n ]\n src = (0, 0)\n dst = (4, 4)\n shortest_path = [\n (0, 0),\n (1, 0),\n (2, 0),\n (3, 0),\n (4, 0),\n (4, 1),\n (4, 2),\n (3, 2),\n (2, 2),\n (1, 2),\n (0, 2),\n (0, 3),\n (0, 4),\n (1, 4),\n (2, 4),\n (3, 4),\n (4, 4),\n ]\n\n path = find_shortest_path(grid, src, dst)\n assert all(x == y for x, y in zip(path, shortest_path))\n\n\ndef test_find_shortest_path_none():\n grid = [\n [1, 1, 1, 1, 0],\n [1, 1, 1, 0, 1],\n [1, 1, 0, 1, 1],\n [1, 0, 1, 1, 1],\n [0, 1, 1, 1, 1],\n ]\n src = (0, 0)\n dst = (4, 4)\n find_shortest_path(grid, src, dst)\n\n path = find_shortest_path(grid, src, dst)\n assert path is None\n","repo_name":"ejonokuchi/practice","sub_path":"algorithms/a_star.py","file_name":"a_star.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"25110818700","text":"from django.contrib import admin\nfrom django.urls import path\nfrom app2 import views\n\n\n#revoir la facon de mettre des Urls , commence par le premier url puis parcours la liste\n\nurlpatterns = [\n path('/', views.index, name=\"index\"),\n path('home2/', views.home2, name=\"home\"),\n path('home3/', views.Question_choice, name=\"question\"),\n path('', views.index, name='index'),\n path('index2/', views.index2, name='index2'),\n # ex: /polls/5/\n path('specifics//', views.detail, name='detail'),\n # ex: /polls/5/results/\n path('/results/', views.results, name='results'),\n # ex: /polls/5/vote/\n path('/vote/', views.vote, name='vote'),\n path('resultat///', views.R, name=\"Res\"),\n\n \n]\n","repo_name":"girlcoder3/Review","sub_path":"Django/mysite/app2/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"72216814019","text":"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy.optimize import curve_fit, least_squares\n\ndef plot_initial_data(df):\n plt.plot( df['X'], df['Y'], color='red', label='Datos originales filtrados por tiempo')\n plt.show()\n\n\ndef model_f(t, E, Rs, CDL, B):\n return ( (((E/Rs) * np.exp(-(t/(Rs*CDL)) ))) + (B/np.sqrt(t)) + E )\n \ndef diffusive(t: np.ndarray, t0: float, E: float, Rs: float, Cdl: float, B: float) -> np.ndarray:\n return B/np.sqrt(t - t0) # + E\n\n\ndef capacitive(t: np.ndarray, t0: float, E: float, Rs: float, Cdl: float, B: float) -> np.ndarray:\n return E*(1 + np.exp(-(t - t0)/Rs/Cdl)/Rs)\n\n\ndef decay_model(t: np.ndarray, t0: float, E: float, Rs: float, Cdl: float, B: float) -> np.ndarray:\n i = (capacitive(t, t0, E, Rs, Cdl, B)\n + diffusive(t, t0, E, Rs, Cdl, B)\n + E )\n return i\n\n\nmodel_f = np.vectorize(model_f)\n\n\ntimepo_actual = 2.47E+02 + (5*60)\nrango = 5*60\n\n\n\nif __name__ == '__main__':\n\n\n\n df = pd.read_csv(r'C:\\Users\\TCCA_\\OneDrive\\Escritorio\\GUI_SUPERCAPACITORES\\raw_data.csv', names=['time', 'current'], skiprows=1)\n #print(df)\n \n\n \n\n df.time -= df.time.min()\n df = df[\n (df.time > 25) |\n (df.current > 2.5e-3)\n ].loc[1:, :]\n popt, *_ = curve_fit(\n f=decay_model, xdata=df.time, ydata=df.current,\n p0=(0.1, 0.1, 1e-2, 1e2, 0),\n bounds=(\n ( 0, 1e-6, 1e-3, 1, 0),\n (10, 1, 1, 1e3, 1),\n ),\n )\n #print(popt)\n \n fig, ax = plt.subplots()\n # plt.plot(df.time, df.current, label='Original data')\n # ax.semilogx(df.time, diffusive(df.time, *popt), label='Diffusive fit')\n # ax.semilogx(df.time, capacitive(df.time, *popt), label='Capacitive fit')\n # ax.semilogx(df.time, decay_model(df.time, *popt), label='Total fit')\n\n # plt.legend()\n #plt.show()","repo_name":"Chachacharli/Supercapacitores","sub_path":"project/test/test_fitten_constant.py","file_name":"test_fitten_constant.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40052950849","text":"from collections import Counter\ntemp = list(map(int, input().split()))\nques_num = temp[-1]\nls = [[] for i in range(0, ques_num)]\nfor i in range(0, temp[0]):\n answer = input()\n for j in range(0, ques_num):\n ls[j].append(answer[j])\nscores = list(map(int, input().split()))\nls_1 = [] #每道题最大重复人数\nfor i in range(0, ques_num):\n temp_1 = Counter(ls[i])\n ls_1.append(max(temp_1.values()))\nresult = 0\nfor i in range(0, ques_num):\n result += ls_1[i] * scores[i]\nprint(result)","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2834/60793/264673.py","file_name":"264673.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"33197434707","text":"#!/usr/bin/env python3\n\n# Created by: Matsuru Hoshi\n# Created on: Sept 2019\n# This is program tells you if number is +, -, or 0\n\nimport random\n\n\ndef main():\n # funciton finds +, -, or 0 number\n\n # Welcome statement\n print(\"Welcome, this is the NUMBER thing with + and - and 0.\")\n input(\"Press Enter to continue.\")\n\n # input\n number = float(input(\"What is your number: \"))\n\n # process\n if number < 0:\n print(\"-\")\n elif number > 0:\n print(\"+\")\n else:\n print(\"0\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"matsuru-hoshi/ICS3U-3-04-Python","sub_path":"integer_guesser.py","file_name":"integer_guesser.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70689222039","text":"# Knuth Morris Pratt (KMP) Algorithm\nclass KMPAlgorithm:\n def __init__(self,string,pattern):\n self.string = string\n self.pattern = pattern\n\n def preprocessPattern(self):\n print(\"Pattern - \",self.pattern)\n pattern_length = len(self.pattern)\n lps = [0]*pattern_length # longest proper prefix which is also a suffix\n length = 0\n i = 1\n while i < pattern_length:\n if self.pattern[i] == self.pattern[length]:\n length += 1\n lps[i] = length\n i += 1\n else:\n if length != 0:\n length = lps[length-1]\n else:\n lps[i] = 0\n i += 1\n print(\"Longest Proper Prefix - \",lps)\n return lps\n \n def search(self):\n lps = self.preprocessPattern()\n string_length = len(self.string)\n pattern_length = len(self.pattern)\n i = 0\n j = 0\n print(\"Text - \",self.string)\n while(i= 0:\n host, port = host.split(':')\n else:\n host, port = host, 22\n\n git_repository_name = '{}/{}'.format(user.username, project.slug)\n\n repository = serializer.save(user=user, git_repository_name=git_repository_name, host=host, port=port)\n task = self.run_clone_workflow(repository=repository)\n return {'task_id': task.id, 'status': task.status}\n\n def connect(self, *args, **kwargs):\n data = self.request.data\n\n host = data.get('host')\n port = data.get('port', 22)\n username = data.get('login')\n password = data.get('password')\n\n if host.find(':') >= 0:\n host, port = host.split(':')\n\n status, message = self.model.test_connection(host, port, username, password)\n return {'status': status, 'message': message, 'detail': [message,]}\n\n def hook_verify_request(self):\n pass\n\n def hook_receive(self, project_id, repository_id, *args, **kwargs):\n\n self.hook_verify_request()\n\n params = {'project_id': project_id}\n\n if repository_id is not None:\n params['id'] = repository_id\n\n repository_instance = self.model.objects.get(**params)\n status, message = repository_instance.receive_webhook(request=self.request, context=self.context)\n return {'status': status, 'message': message}\n\n def hook_install(self, project_id, repository_id, *args, **kwargs):\n params = {'project_id': project_id}\n if repository_id is not None:\n params['id'] = repository_id\n\n repository_instance = self.model.objects.get(**params)\n status, message = repository_instance.install_webhook(request=self.request, context=self.context)\n return {'status': status, 'message': message}\n\n def hook_generate(self, project_id, repository_id, *args, **kwargs):\n params = {'project_id': project_id}\n if repository_id is not None:\n params['id'] = repository_id\n\n repository_instance = self.model.objects.get(**params)\n data = repository_instance.generate_webhook(request=self.request, context=self.context)\n return {'content_type': 'text/plain', 'content': data, 'filename': 'hook.py'}\n\n\nclass GitSSHRepositoryWrapper(RepositoryInterface):\n\n model = GitSSHRepository\n serializer_class = GitSSHRepositoryCreateListSerializer\n\n def create(self, *args, **kwargs):\n organization = get_current_organization(self.request)\n user = self.request.user\n\n is_member = organization.is_member(user)\n\n if not is_member:\n raise exceptions.PermissionDenied('You have no permissions.')\n\n data = self.request.data.copy()\n\n private_key_file = self.request.FILES.get('private_key')\n if private_key_file is None:\n private_key_file = data['private_key']\n\n private_key_raw = private_key_file.file.read()\n private_key = base64.encodestring(private_key_raw)\n data['private_key'] = private_key\n\n serializer = self.get_serializer(data=data)\n serializer.is_valid(raise_exception=True)\n\n repository = serializer.save()\n # task = self.run_clone_workflow(repository=repository)\n # return {'task_id': task.id, 'status': task.status}\n return {'task_id': 'unknown', 'status': 'SUCCESS'}\n\n def hook_receive(self, project_id, repository_id, *args, **kwargs):\n params = {'project_id': project_id}\n if repository_id is not None:\n params['id'] = repository_id\n\n repository_instance = self.model.objects.get(**params)\n status, message = repository_instance.receive_webhook(request=self.request, context=self.context)\n return {'status': status, 'message': message}\n\n\nclass GitSSHv2RepositoryWrapper(RepositoryInterface):\n\n model = GitSSHv2Repository\n serializer_class = GitSSHv2RepositoryCreateListSerializer\n\n def create(self, *args, **kwargs):\n organization = get_current_organization(self.request)\n user = self.request.user\n\n is_member = organization.is_member(user)\n\n if not is_member:\n raise exceptions.PermissionDenied('You have no permissions.')\n\n data = self.request.data.copy()\n\n project = Project.objects.get(id=data.get('project'))\n repository_name = slugify(project.name)\n\n data['user'] = user.pk\n data['project'] = project.pk\n data['repository_name'] = repository_name\n\n serializer = self.get_serializer(data=data)\n serializer.is_valid(raise_exception=True)\n\n repository = serializer.save()\n # task = self.run_clone_workflow(repository=repository)\n # return {'task_id': task.id, 'status': task.status}\n return {'task_id': 'unknown', 'status': 'SUCCESS'}\n\n def retrieve(self, pk, *args, **kwargs):\n repository_instance = self.model.objects.get(pk=pk)\n serializer = self.get_serializer(repository_instance)\n return serializer.data\n\n def destroy(self, pk, *args, **kwargs):\n repository_instance = self.model.objects.get(pk=pk)\n repository_instance.delete()\n return {}\n\n def hook_receive(self, project_id, repository_id, *args, **kwargs):\n params = {'project_id': project_id}\n if repository_id is not None:\n params['id'] = repository_id\n\n token = self.request.META.get('HTTP_TOKEN', '')\n organization_from_token = ConfirmationHMAC.from_key(token)\n organization = get_current_organization(self.request)\n if organization != organization_from_token:\n raise exceptions.AuthenticationFailed()\n\n repository_instance = self.model.objects.get(**params)\n status, message = repository_instance.receive_webhook(request=self.request, context=self.context)\n return {'status': status, 'message': message}\n\n def hook_generate(self, project_id, repository_id, *args, **kwargs):\n params = {'project_id': project_id}\n if repository_id is not None:\n params['id'] = repository_id\n\n repository_instance = self.model.objects.get(**params)\n data = repository_instance.generate_webhook(request=self.request, context=self.context)\n return {'content_type': 'application/octet-stream', 'content': data, 'filename': 'install.py'}\n\n\nclass RepositoryGenericViewSet(viewsets.GenericViewSet):\n\n def initialize_request(self, request, *args, **kwargs):\n self.repository_type = kwargs.pop('type')\n setattr(request, 'raw_body', request.body)\n return super(RepositoryGenericViewSet, self).initialize_request(request, *args, **kwargs)\n\n def get_repository_class(self):\n return self.repository_classes[self.repository_type]\n\n def get_repository_context(self):\n body = self.request.raw_body\n return {\n 'request': self.request,\n 'query_params': self.request.query_params,\n 'data': self.request.data,\n 'body': body,\n 'view': self\n }\n\n def get_repository(self, *args, **kwargs):\n repository_class = self.get_repository_class()\n kwargs['context'] = self.get_repository_context()\n return repository_class(*args, **kwargs)\n\n\nclass RepositoryViewSet(RepositoryGenericViewSet):\n # permission_classes = [permissions.AllowAny, ]\n\n repository_classes = {\n 'github': GitHubRepositoryWrapper,\n 'bitbucket': BitBucketRepositoryWrapper,\n 'perforce': PerforceRepositoryWrapper,\n 'git': GitRepositoryWrapper,\n 'ssh': GitSSHRepositoryWrapper,\n 'ssh_v2': GitSSHv2RepositoryWrapper,\n\n }\n\n def create(self, request, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n data = repository.create(*args, **kwargs)\n return response.Response(status=status.HTTP_200_OK, data=data)\n\n def retrieve(self, request, pk, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n data = repository.retrieve(pk, *args, **kwargs)\n return response.Response(status=status.HTTP_200_OK, data=data)\n\n def destroy(self, request, pk, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n data = repository.destroy(pk, *args, **kwargs)\n return response.Response(status=status.HTTP_204_NO_CONTENT, data=data)\n\n @action(methods=['GET', ], detail=False, url_name='full-list', url_path=r'full')\n def full(self, request, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n data = repository.full()\n return response.Response(status=status.HTTP_200_OK, data=data)\n\n @action(methods=['POST', ], detail=False, url_name='test', url_path=r'connect')\n def connect(self, request, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n data = repository.connect(*args, **kwargs)\n if data['status'] is False:\n return response.Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data=data)\n return response.Response(status=status.HTTP_200_OK, data=data)\n\n\nclass RepositoryHookViewSet(RepositoryGenericViewSet):\n # permission_classes = [permissions.AllowAny, ]\n\n repository_classes = {\n 'github': GitHubRepositoryWrapper,\n 'bitbucket': BitBucketRepositoryWrapper,\n 'perforce': PerforceRepositoryWrapper,\n 'git': GitRepositoryWrapper,\n 'ssh': GitSSHRepositoryWrapper,\n 'ssh_v2': GitSSHv2RepositoryWrapper,\n\n }\n\n @action(methods=['POST', ], detail=False, permission_classes=[permissions.AllowAny, ],\n url_name='receive', url_path=r'(?P[0-9]+)(/(?P[0-9]+))?')\n def receive(self, request, project_id, repository_id=None, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n project = Project.objects.get(id=project_id)\n if not project.is_active:\n return response.Response(\n data={\"detail\": \"Project is not active\"},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR,\n )\n data = repository.hook_receive(project_id, repository_id, *args, **kwargs)\n if data['status'] is False:\n return response.Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data=data)\n return response.Response(status=status.HTTP_200_OK, data=data)\n\n @action(methods=['POST', ], detail=False, url_name='install',\n url_path=r'(?P[0-9]+)(/(?P[0-9]+))?/install')\n def install(self, request, project_id, repository_id=None, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n data = repository.hook_install(project_id, repository_id, *args, **kwargs)\n return response.Response(status=status.HTTP_200_OK, data=data)\n\n @action(methods=['GET', 'POST', ], detail=False, url_name='generate',\n url_path=r'(?P[0-9]+)(/(?P[0-9]+))?/generate')\n def generate(self, request, project_id, repository_id=None, *args, **kwargs):\n repository = self.get_repository(*args, **kwargs)\n data = repository.hook_generate(project_id, repository_id, *args, **kwargs)\n response = HttpResponse(status=status.HTTP_200_OK, content_type=data['content_type'])\n response['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(data['filename'])\n response.write(data['content'])\n return response\n\n # Temporary API for fetch project_id\n # TODO: change when git refactoring done\n @action(methods=['GET', ], detail=False, permission_classes=[permissions.AllowAny, ],\n url_name='fetch', url_path=r'fetch')\n def fetch(self, request, *args, **kwargs):\n project_name = request.query_params.get('project_name')\n projects = Project.objects.filter(name=project_name)\n if projects:\n project = projects[0]\n project_id = project.id\n data = {\n \"project_id\": project_id\n }\n else:\n data = {\n \"error\": \"Project didn't exist, check project name and try again!\"\n }\n return response.Response(status=status.HTTP_200_OK, data=data)\n","repo_name":"kolodyadanil/appsurify-testbrain-core","sub_path":"src/applications/api/integration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8582635613","text":"__author__ = \"Jens Honer\"\n__copyright__ = \"Copyright 2018, Jens Honer Tracking Toolbox\"\n__email__ = \"-\"\n__license__ = \"mit\"\n__version__ = \"1.0\"\n__status__ = \"Prototype\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\n\nfrom models.spline import map_idx\nfrom datatypes import dt_bbox, dt_z\n\n\nclass SplineDataSimulator(object):\n \"\"\"\n Simple data generation class\n\n \"\"\"\n\n def __init__(self, **kwargs):\n\n self._uc = 0\n\n self._dt_bbox = dt_bbox\n\n self._dt = kwargs.get('dt')\n self._steps = kwargs.get('steps')\n\n self._d = kwargs.get('d')\n self._sd = kwargs.get('sd')\n\n self._m_basis = np.array([[0.5, -1.0, 0.5],\n [-1.0, 1.0, 0.0],\n [0.5, 0.5, 0.0]], dtype='f4')\n self._p_basis_unscaled = kwargs.get('p_basis')\n self._p_basis_dim = len(self._p_basis_unscaled)\n\n self._sel_idx_full = np.arange(0, self._p_basis_dim + 3, dtype='i4') % self._p_basis_dim\n\n self._dt_gt = np.dtype([('m', 'f8', self._sd)])\n self._dt_z = dt_z\n\n self._gt_state = np.zeros(self._steps, dtype=self._dt_gt)\n self._measurements = np.zeros(0, dtype=self._dt_z)\n\n self._gt_state['m'][0] = kwargs.get('init_m')\n\n self._r = kwargs.get('r')\n\n self._poisson_scat_mean = kwargs.get('mean_scat_number')\n\n def _transition_f(self, u):\n \"\"\"\n transition function for state vector [x, y, phi, v, omega]\n\n time difference is implicit\n\n Parameters\n ----------\n u array_like\n sigma points\n\n \"\"\"\n\n u[0] += self._dt * u[3] * np.cos(u[2])\n u[1] += self._dt * u[3] * np.sin(u[2])\n\n u[2] += self._dt * u[4]\n\n def predict(self):\n self._gt_state['m'][self._uc] = self._gt_state['m'][self._uc - 1]\n self._transition_f(self._gt_state['m'][self._uc])\n\n def emit(self):\n \"\"\"\n Calculates random points on the spline surface and stores them into self._data\n\n \"\"\"\n\n # calculate rotation matrices\n s_phi_u, c_phi_u = np.sin(self._gt_state['m'][self._uc, 2]), np.cos(self._gt_state['m'][self._uc, 2])\n rot_u = np.asarray([[c_phi_u, -s_phi_u],\n [s_phi_u, c_phi_u]])\n\n # Random number of measurements\n cd_z = np.random.poisson(lam=self._poisson_scat_mean)\n\n # Randomly select indices and tau\n ref_idx = np.random.randint(0, self._p_basis_dim, cd_z)\n sel_idx = np.zeros(ref_idx.shape + (3,), dtype='i8')\n map_idx(ref_idx, self._sel_idx_full, sel_idx)\n tau = np.random.rand(cd_z)\n\n mp_base_sel_bare = np.dot(self._m_basis, self._p_basis_unscaled[sel_idx])\n measurements_t = np.zeros(cd_z, dtype=self._dt_z)\n measurements_t['xy'] = \\\n mp_base_sel_bare[2] + mp_base_sel_bare[1] * tau[:, None] + mp_base_sel_bare[0] * (tau ** 2)[:, None]\n measurements_t['xy'] = np.dot(measurements_t['xy'], rot_u.T)\n measurements_t['xy'] += self._gt_state['m'][self._uc, :2]\n measurements_t['ts'] = self._uc - 1\n\n self._measurements = np.concatenate((self._measurements, measurements_t))\n\n def step(self):\n self._uc += 1\n\n self.predict()\n self.emit()\n\n def extract(self):\n \"\"\"\n\n Returns\n -------\n\n gt: array_like,\n structured array of the ground truth trajectory\n measurements: array_like,\n structured array of the measurements in cartesian coordinates, dtype [('ts', 'i4'), ('xy', 'f4', (2,))]\n\n \"\"\"\n self._measurements['xy'] += np.random.multivariate_normal(np.zeros(2), self._r, len(self._measurements))\n gt_extr = np.zeros(self._gt_state.shape[0] - 1, dtype=np.dtype([('ts', 'i4')] + self._gt_state.dtype.descr))\n gt_extr['m'] = self._gt_state['m'][1:]\n gt_extr['ts'] = np.arange(len(gt_extr['ts']))\n return gt_extr, self._measurements\n\n def extrackt_bbox(self):\n \"\"\"\n Bounding box extraction function.\n The algorithm creates the minimal bounding box defined by the spline knots.\n\n Returns\n -------\n bbox_extr: array_like\n struct containing the time series of bounding boxes\n\n \"\"\"\n\n bbox_extr = np.zeros(self._steps - 1, dtype=self._dt_bbox)\n bbox_extr['ts'] = np.arange(self._steps - 1, dtype='i4')\n bbox_extr['center_xy'] = self._gt_state['m'][1:, :2]\n bbox_extr['orientation'] = self._gt_state['m'][1:, 2]\n basis_dim = np.max(self._p_basis_unscaled, axis=0)\n bbox_extr['dimension'] = 2 * basis_dim\n\n return bbox_extr\n\n\nif __name__ == \"__main__\":\n\n np.set_printoptions(precision=3, formatter={'float': '{: 0.3f}'.format})\n np.seterr('warn')\n\n steps = 100\n dt = 0.04\n\n config = {\n 'steps': steps + 1,\n 'd': 2,\n 'sd': 5,\n 'r': 0.05 ** 2 * np.identity(2),\n 'init_m': np.asarray([6.5, 2.5, 0.00, 12, 0.1]),\n 'p_basis': np.array([\n [2.5, 0.0],\n [2.5, 1.0],\n [0.0, 1.0],\n [-2.5, 1.0],\n [-2.5, 0.0],\n [-2.5, -1.0],\n [0.0, -1.0],\n [2.5, -1.0],\n ]),\n 'mean_scat_number': 125,\n }\n\n data_source = SplineDataSimulator(dt=dt, **config)\n\n for i in range(steps):\n print('step: {:3d}'.format(i))\n\n data_source.step()\n\n gt, measurements = data_source.extract()\n bboxes = data_source.extrackt_bbox()\n\n stride = 5\n\n color_sequence = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',\n '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5',\n '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f',\n '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']\n\n plt.style.use('ggplot')\n fig, ax = plt.subplots(2, 1, figsize=(20.0, 10.0))\n fig.suptitle('Single Target Framework Data Generation', fontsize=12, x=0.02, horizontalalignment='left')\n\n for a in ax:\n a.set_xlabel(r'$x$')\n a.set_ylabel(r'$y$')\n a.set_aspect('equal')\n\n ax[1].get_shared_x_axes().join(ax[0], ax[1])\n ax[1].get_shared_y_axes().join(ax[0], ax[1])\n\n\n def plot_rectangle(bboxes, ax, step, c='#ff7f0e'):\n\n for bbox in bboxes[bboxes['ts'] % step == 0]:\n s_phi_offset, c_phi_offset = np.sin(bbox['orientation']), np.cos(bbox['orientation'])\n rot = np.array([[c_phi_offset, - s_phi_offset], [s_phi_offset, c_phi_offset]])\n offset_xy = np.dot(rot, 0.5 * bbox['dimension'])\n\n r = Rectangle(xy=bbox['center_xy'] - offset_xy, width=bbox['dimension'][0], height=bbox['dimension'][1],\n angle=np.rad2deg(bbox['orientation']))\n\n ax.add_artist(r)\n r.set_clip_box(ax.bbox)\n r.set_alpha(0.8)\n r.set_facecolor('none')\n r.set_edgecolor(c)\n\n\n plot_rectangle(bboxes, ax[1], stride, c='#ff7f0e')\n ax[0].plot(gt['m'][:, 0], gt['m'][:, 1], label='track', c=color_sequence[0])\n\n sel = measurements['ts'] % stride == 0\n ax[1].plot(measurements['xy'][sel, 0], measurements['xy'][sel, 1],\n c='k', marker='.', linewidth=0, markersize=0.5, alpha=0.5, label='measurements')\n\n ax[0].plot(measurements['xy'][:, 0], measurements['xy'][:, 1],\n c='k', marker='.', linewidth=0, markersize=0.5, alpha=0.5, label='measurements')\n\n for a in ax:\n a.legend()\n\n plt.show()\n\n if False: # change to True to write data\n import os\n path = os.path.join(os.getcwd(), 'data')\n if not os.path.exists(path):\n os.makedirs(path)\n\n filename = r'simulated_data'\n np.save(os.path.join(path, filename + '.npy'), measurements)\n filename = r'gt_path'\n np.save(os.path.join(path, filename + '.npy'), gt)\n filename = r'gt_bboxes'\n np.save(os.path.join(path, filename + '.npy'), bboxes)\n","repo_name":"Fusion-Goettingen/ExtendedTargetTrackingToolbox","sub_path":"data/spline_simulator.py","file_name":"spline_simulator.py","file_ext":"py","file_size_in_byte":8023,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"85"} +{"seq_id":"19495258139","text":"import string\nimport random\n\nimport asyncio\nfrom aiohttp import web\n\n\n# func-callback by finished Task\ndef task_finished_callback(task: asyncio.Task, res: list, err: list):\n # get task-result\n task_result = task.result()\n # if result\n if task_result:\n if task_result[0]:\n if isinstance(task_result[0], list):\n res.extend(task_result[0])\n else:\n res.append(task_result[0])\n # if errors\n if task_result[1]:\n if isinstance(task_result[1], list):\n err.extend(task_result[1])\n else:\n err.append(task_result[1])\n else:\n err.append(get_error_item(reason='Undefined error'))\n\n\n# calc errors from validate-data (errors) by UnmarshalResult\ndef calc_errors_from_vd(errors: dict, data_on_validate: dict={}) -> list:\n # result list errors\n result_errors = []\n # errors = {field_name: [errors-msgs]}\n for field_name in errors:\n for msg in errors[field_name]:\n result_errors.append(get_error_item(selector=field_name, value=data_on_validate.get(field_name) if type(data_on_validate) == dict else data_on_validate, reason=msg))\n return result_errors\n\n\n# standard error item\ndef get_error_item(selector: str='', value=None, reason: str='Not found', **kwargs) -> dict:\n \"\"\"\n :param selector: str. Selector/field of error\n :param reason: str. Reason of error\n :param value: value. Value/id/selector-value\n :param kwargs: other params - added ro dict error\n :return: dict. Item error\n \"\"\"\n # default dict\n error = dict(\n reason=reason\n )\n if selector:\n error['selector'] = selector\n # add value\n if value:\n error['value'] = value\n # add other fields\n if kwargs:\n for i in kwargs:\n error[i] = kwargs[i]\n return error\n\n\n# standard result item\ndef get_result_item(data, fields) -> dict:\n \"\"\"\n :param data: dict or asyncpgsa.record.Record\n :param fields: list or set\n :return: dict\n \"\"\"\n result = {}\n # if dict\n if isinstance(data, dict):\n for field in fields:\n result[field] = data.get(field, None)\n # if Record\n else:\n for field in fields:\n try:\n result[field] = data[field]\n except:\n result[field] = None\n return result\n\n\n# validate dict by schema\ndef validate_by_schema(schema, data: dict) -> {dict, list}:\n # validate-data\n v_data, errors = None, []\n # validate\n vd = schema.load(data)\n # if error return error-item\n if vd.errors:\n errors.extend(calc_errors_from_vd(errors=vd.errors, data_on_validate=data))\n else:\n v_data = vd.data\n return v_data, errors\n\n\n# generate unique key\ndef keygen(size=12, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))","repo_name":"qtc-soft/schedule-api","sub_path":"core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18265352389","text":"from graphics import GraphWin, Point, Rectangle, Circle, Text\nfrom time import sleep\n\nwin = GraphWin(\"Animation\", 500, 500)\nwin.setCoords(0,0,50,50)\n\n#####begin() BEGINS THE SEQUENCE######\n\ndef begin():\n #Ready? Text\n begText1 = Text(Point(25,20), \"Ready?\")\n begText1.setFace(\"times roman\")\n begText1.draw(win)\n sleep(1.5)\n begText1.undraw()\n sleep(0.5)\n\n #\"Here's a point\" Text and Plotting first point\n begText2 = Text(Point(25,20), \"Here's a point.\")\n begText2.setFace(\"times roman\")\n begText2.draw(win)\n point1 = Point(25,25)\n point1.draw(win)\n sleep(1.5)\n begText2.undraw()\n sleep(0.5)\n\n #moving First point\n clickAnywhere = Text(Point(25, 20),\n \"Press 'l' or 'r' to move the point off the screen in either direction.\")\n clickAnywhere.setFace(\"times roman\")\n clickAnywhere.draw(win)\n #win.getMouse()\n key = win.getKey()\n clickAnywhere.undraw()\n if key == \"r\":\n for i in range(55):\n point1.move(.5,0)\n sleep(0.05)\n if key == \"l\":\n for i in range(55):\n point1.move(-.5,0)\n sleep(0.05)\n point1.undraw()\n\n #First Congrats Text and Transition\n greatxt = Text(Point(25,20), \"Great!\")\n greatxt.setFace(\"times roman\")\n greatxt.draw(win)\n sleep(1.5)\n greatxt.undraw()\n tranText = Text(Point(25,20), \"Now, click your mouse on the window to create a red circle\")\n tranText.setFace(\"times roman\")\n tranText.draw(win)\n win.getMouse()\n tranText.undraw()\n #call to next function\n drawCircle()\n\ndef drawCircle():\n #draws the red circle\n radius = 5\n circle1 = Circle(Point(25, 25), radius)\n circle1.setFill(\"red\")\n circle1.draw(win)\n\n #good job text\n goodJob = Text(Point(25, 35), \"Good Job!\")\n goodJob.setFace(\"times roman\")\n goodJob.draw(win)\n sleep(2)\n goodJob.undraw()\n\n #grow text\n grow = Text(Point(25,35), \"Now we will grow our circle.\")\n grow.setFace(\"times roman\")\n grow.draw(win)\n sleep(1.5)\n grow.undraw()\n sleep(.5)\n\n #click on the window text\n clickToGrow = Text(Point(25,35), \"Click on the window\")\n clickToGrow.setFace(\"times roman\")\n clickToGrow.draw(win)\n \n \n win.getMouse()\n circle1.undraw()\n clickToGrow.undraw()\n \n #grow your circle\n for i in range(10):\n radius = radius + 1\n circle2 = Circle(Point(25, 25), radius)\n circle2.setFill(\"red\")\n circle2.draw(win)\n circle2.undraw()\n circle2.draw(win)\n\n #WOW text for growing your circle\n wow = Text(Point(25, 43), \"WOW!\")\n wow.setSize(30)\n wow.setFace(\"times roman\")\n wow.draw(win)\n sleep(2)\n wow.undraw()\n\n #Shrink the circle prompt\n thenText = Text(Point(25, 43), \"Now, click to shrink it back down!\")\n thenText.setFace(\"times roman\")\n thenText.setSize(25)\n thenText.draw(win)\n \n win.getMouse()\n thenText.undraw()\n circle2.undraw()\n\n #Shrink your circle Function\n for i in range(10):\n radius = radius - 1\n circle3 = Circle(Point(25, 25), radius)\n circle3.setFill(\"red\")\n circle3.draw(win)\n circle3.undraw()\n circle3.draw(win)\n\n\n #small wow\n wow2 = Text(Point(25, 33), \"wow\")\n wow2.setFace(\"times roman\")\n wow2.draw(win)\n sleep(.35)\n wow2.undraw()\n\n wow2 = Text(Point(25, 33), \"wow.\")\n wow2.setFace(\"times roman\")\n wow2.draw(win)\n sleep(.5)\n wow2.undraw()\n\n wow2 = Text(Point(25, 33), \"wow..\")\n wow2.setFace(\"times roman\")\n wow2.draw(win)\n sleep(.5)\n wow2.undraw()\n\n wow2 = Text(Point(25, 33), \"wow...\")\n wow2.setFace(\"times roman\")\n wow2.draw(win)\n sleep(2)\n wow2.undraw()\n\n circle3.undraw()\n #call to next function\n moveCircle()\n\ndef moveCircle():\n #first move circle text\n moveCircle = Text(Point(25, 33), \"Now lets create and move circles wherever you'd like\")\n moveCircle.setFace(\"times roman\")\n moveCircle.draw(win)\n sleep(1.5)\n moveCircle.undraw()\n\n #second move circle text\n moveCircle2 = Text(Point(25, 33), \"When the red circle appears, move it by pressing 'w' 'a' 's' 'd'\")\n moveCircle2.setFace(\"times roman\")\n moveCircle2.draw(win)\n sleep(6)\n moveCircle2.undraw()\n\n #third color circle text\n moveCircle2 = Text(Point(25, 33), \"You can create a new circle with a different color by pressing 'r', 'g', 'b'\")\n moveCircle2.setFace(\"times roman\")\n moveCircle2.draw(win)\n sleep(6)\n moveCircle2.undraw()\n\n #new circle def\n circle = Circle(Point(25, 25), 5)\n setfill = \"red\"\n circle.setFill(setfill)\n circle.draw(win)\n\n #move circle with for loops and an if function\n for i in range(1000):\n key = win.getKey()\n if key == \"w\":\n for w in range(1):\n circle.move(0,2)\n if key == \"s\": \n for s in range(1):\n circle.move(0,-2)\n if key == \"d\":\n for d in range(1):\n circle.move(2,0)\n if key == \"a\":\n for a in range(1):\n circle.move(-2,0)\n \n if key == \"r\":\n circle = Circle(Point(25, 25), 5)\n setfill = \"red\"\n circle.setFill(setfill)\n circle.draw(win)\n if key == \"g\":\n circle = Circle(Point(25, 25), 5)\n setfill = \"green\"\n circle.setFill(setfill)\n circle.draw(win)\n if key == \"b\":\n circle = Circle(Point(25, 25), 5)\n setfill = \"blue\"\n circle.setFill(setfill)\n circle.draw(win)\n if key == \"x\":\n win.close()\n begin()\n #circle.undraw()\n \n win.close()\n\n\n \nbegin()\n#moveCircle()\n\n\n","repo_name":"joji-harada/python","sub_path":"animated.py","file_name":"animated.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42504791835","text":"import os\nimport runCmdAsJob\nimport stdpopsim #just to make sure we are in an env with it\n\nbaseDir = \"\"\nslimScriptDir = baseDir + \"slimScripts\"\nrawSlimScriptDir = baseDir + \"rawSlimScripts\"\noutDir = baseDir + \"slimOutput\"\nlogDir = baseDir + \"slimLogs\"\n\nos.system(f\"mkdir -p {rawSlimScriptDir} {slimScriptDir} {outDir} {logDir}\")\n\njobName = \"bgsIntroSlim\"\nlaunchFileName = \"bgsIntroSlim.sh\"\nwallTime = \"12:00:00\"\nqName = \"general\"\nmem = \"64G\"\n\nnumReps=100\n\nfor i in range(numReps):\n slimScriptFileName = f\"{slimScriptDir}/bgsSim_{i}.slim\"\n slimScriptFileName = f\"{rawSlimScriptDir}/bgsSim_{i}.slim\"\n outFileName = f\"{outDir}/bgsSim_{i}.out\"\n logFileName = f\"{logDir}/bgsSim_{i}.log\"\n\n cmd = f\"python extractSlimScriptForDmelAnnotDFE_randomWindow.py {rawSlimScriptDir}/bgsSim_{i}.slim\\n\"\n cmd += f\"python modifySlimScript.py {rawSlimScriptDir}/bgsSim_{i}.slim > {slimScriptDir}/bgsSim_{i}.slim\\n\"\n cmd += f\"slim -d physLen=1000000 -d donorPop=3 {slimScriptDir}/bgsSim_{i}.slim | gzip > {outDir}/bgsSim_{i}.out.gz\"\n runCmdAsJob.runCmdAsJobWithoutWaitingWithLog(cmd, jobName, launchFileName, wallTime, qName, mem, logFileName)\n","repo_name":"SchriderLab/introNets","sub_path":"bgsTest/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"927686470","text":"#!/usr/bash/env python3\n\"\"\" A program that allows users to choose 2 players from 4 different\noptions and play Rock,Paper ans Scissors game between them as well as\ndisplays score in each round and finally anounce the winner \"\"\"\n\nmoves = ['rock', 'paper', 'scissors']\n\n\nclass Player:\n \"\"\"This player class is a parent class for all the players in the\n game\"\"\"\n def move(self):\n pass\n\n def learn(self, my_move, their_move):\n pass\n\n\nclass AllRockP(Player):\n \"\"\"A player that always plays rocks and returns the value \"rock\"\n each time it is called.\"\"\"\n def move(self):\n return 'rock'\n\n\nclass RandomP(Player):\n \"\"\" A player that makes moves randomly and is a subclass of\n Player class.It returns random moves each time.\"\"\"\n def move(self):\n \"\"\"ths function returns random moves each time out of the moves\n list.\"\"\"\n import random\n mymove = random.choice(moves)\n return mymove\n\n\nclass ReflectiveP(Player):\n \"\"\" A subclass of player class that remembers and returns what other\n players's last move was.\"\"\"\n def __init__(self):\n \"this function contains initializers\"\n self.m = \"rock\"\n\n def learn(self, my_move, their_move):\n \"\"\"this function takes the moves of both players as inputs and stores\n the move of opponent player\"\"\"\n self.m = their_move\n\n def move(self):\n \"\"\"this function returns the move of opponent player as this players\n current move\"\"\"\n move = self.m\n return move\n\n\nclass CyclicP(Player):\n \"\"\"A subclass of player class that cycles through 3 moves and returns\n them in a cyclic order.\"\"\"\n def __init__(self):\n \"this function contains initializers\"\n self.m = \"rock\"\n self.num = 0\n\n def move(self):\n \"\"\"this move function returns moves in cyclical order\"\"\"\n self.num += 1\n self.index = moves.index(self.m) + self.num\n self.len = len(moves)\n if self.index % self.len == 0:\n return moves[0]\n elif self.index % self.len == 1:\n return moves[1]\n elif self.index % self.len == 2:\n return moves[2]\n else:\n return moves[0]\n\n\nclass HumanP(Player):\n \"\"\" A Human player that asks from valid input from user and returns\n that value.\"\"\"\n def move(self):\n \"\"\"this move function asks for an input from the user and returns\n valid move\"\"\"\n while True:\n mymove = input(\"Please enter your move:\").lower()\n if mymove in moves:\n return mymove\n else:\n return self.move()\n break\n\n\nclass Game:\n \"\"\"Game class that has 2 chosen players as inputs and has methods to\n play game rounds,count scores and announce winners.\"\"\"\n def __init__(self, P1, P2):\n \"\"\"this function takes the two types of chosen players as inputs\n and stores them in variables\"\"\"\n self.P1 = P1\n self.P2 = P2\n self.point1 = 0\n self.point2 = 0\n\n def beats(self, move1, move2):\n \"\"\"this function keeps a track of each move by two placers,compares\n then and returns the points of each player\"\"\"\n if (move1 == \"rock\" and move2 == \"scissors\") or \\\n (move1 == \"scissors\" and move2 == \"paper\") or \\\n (move1 == 'paper' and move2 == \"rock\"):\n print(\"Player1 is the winner \")\n self.point1 += 1\n elif (move2 == \"rock\" and move1 == \"scissors\") or \\\n (move2 == \"scissors\" and move1 == \"paper\") or \\\n (move2 == 'paper' and move1 == \"rock\"):\n print(\"Player2 is the winner \")\n self.point2 += 1\n else:\n print(\"Draw\")\n print(f\"Scores:Player 1: {self.point1} Player 2: {self.point2}\")\n return (self.point1, self.point2)\n\n def scores(self, move1, move2):\n \"\"\"this function takes the points of eaach player from the beats\n function and counts them to reveal points after each round.\"\"\"\n self.s = self.beats(move1, move2)\n return self.s\n\n def play_round(self):\n \"\"\"this function calls the move function of each player and displays\n them.It also calls the remeber function for specific players\"\"\"\n move1 = self.P1.move()\n move2 = self.P2.move()\n print(f\"Player 1: {move1} Player 2: {move2}\")\n self.P1.learn(move1, move2)\n self.P2.learn(move2, move1)\n self.final = self.scores(move1, move2)\n\n def play_game(self):\n \"\"\"this function marks the start of the game and calls the play_round\n function in a loop,compares the total points of each players and\n announces final winner\"\"\"\n print(\"Game start!\")\n for round in range(5):\n print(f\"\\n Round {round}:\")\n self.play_round()\n if self.final[0] > self.final[1]:\n print(\"\\n Player1 Is The Winner!!\")\n elif self.final[0] < self.final[1]:\n print(\"\\n Player2 Is The Winner!!\")\n else:\n print(\"\\n Draw!!\")\n print(f\"Final Scores: \\n Player1:{self.final[0]} \\\n Player2: {self.final[1]}\\n\")\n print(\"------------Game over-------------!\")\n\n\nif __name__ == '__main__':\n allplayers = [AllRockP(), RandomP(), CyclicP(), HumanP(), ReflectiveP()]\n\n def int_check(value):\n try:\n int(value)\n except ValueError:\n return False\n return True\n\n print(\"Select 2 Players from the following list:\\n\"\n \"0:AllRock 1:Random 2.Cyclic 3.Human 4.Reflective\\n\")\n\n player1 = input(\"Enter Your First Choice (0-4):\")\n while not (int_check(player1) and int(player1) >= 0 and int(player1) <= 4):\n player1 = input(\"\\nInvalid First Choice\\n Enter Choice(0-4):\")\n\n player2 = input(\"Enter Your Second Choice (0-4):\")\n while not (int_check(player2) and int(player2) >= 0 and int(player2) <= 4):\n player2 = input(\"\\nInvalid Second Choice\\n Enter Choice(0-4):\")\n\n game = Game(allplayers[int(player1)], allplayers[int(player2)])\n game.play_game()\n","repo_name":"Shenam-Bhamrah/Rock_Paper_Scissors","sub_path":"Rock_Paper_Scissors.py","file_name":"Rock_Paper_Scissors.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32900396842","text":"import matplotlib.pyplot as plt\nimport numpy as np\n#from mpl_toolkits.mplot3d import Axes3D\n# result=[]\n# with open('z-value.txt') as f:\n# for line in f:\n# result.append(map(float,line.split(',')))\n# # print(result)\n# plt.plot(result)\n# plt.xlabel('z-value')\n# plt.ylabel('numbers')\n# plt.show()\n\nfig = plt.figure()\n#ax = Axes3D(fig)\nresult=[]\nwith open('value.txt') as f:\n for line in f:\n result.append(map(float, line.split(' ')))\n\n#print result\n\n\nxyz=np.array(result)\n\nx=xyz[:,0]\n# y=xyz[:,1]\n# z=xyz[:,2]\n\n\nplt.plot(x)\nplt.show()\n# x_max=np.max(x)\n# x_min=np.min(x)\n# print 'x_max',x_max\n# print 'x_min',x_min\n#\n# y_max=np.max(y)\n# y_min=np.min(y)\n# print 'y_max',y_max\n# print 'y_min',y_min\n#\n# z_max=np.max(z)\n# z_min=np.min(z)\n# print 'z_max',z_max\n# print 'z_min',z_min\n#\n# # ax.scatter(x,y,z)\n# #\n# #\n# # ax.set_zlabel('Z-axis')\n# # ax.set_ylabel('Y-axis')\n# # ax.set_xlabel('X-axis')\n#\n#\n# plt.show()\n#\n","repo_name":"ttomchy/pointcloud-segmentation","sub_path":"visualize-z-value.py","file_name":"visualize-z-value.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"37623200327","text":"from regparser import utils\nfrom regparser.citations import internal_citations, Label\nfrom regparser.tree.appendix import carving, generic\nfrom regparser.tree.paragraph import ParagraphParser\nfrom regparser.tree.struct import Node\nimport string\n\nparParser = ParagraphParser(r\"\\(%s\\)\", Node.APPENDIX)\n\n\ndef trees_from(text, part, parent_label):\n \"\"\"Build a tree for the appendix section. It will have children for each\n appendix. Text is the text of the entire regulation, while part is the\n regulation's part (e.g. 1520.)\"\"\"\n children = []\n for begin, end in carving.appendices(text):\n title, appendix = utils.title_body(text[begin:end])\n appendix_letter = carving.get_appendix_letter(title, part)\n label = parent_label + [appendix_letter]\n sections = carving.appendix_sections(appendix, appendix_letter)\n if sections:\n child = paragraph_tree(\n appendix_letter, sections, appendix, label, title)\n else:\n child = generic_tree(appendix, label, title)\n children.append(child)\n return children\n\n\ndef letter_for(index):\n \"\"\"Convert an index into a letter (or letter pair). a-z, then aa-az-zz\"\"\"\n if index < 26:\n return string.ascii_lowercase[index]\n return (string.ascii_lowercase[(index // 26) - 1] # First letter in pair\n + string.ascii_lowercase[index % 26]) # Second letter\n\n\ndef generic_tree(text, label, title=None):\n \"\"\"Use the \"generic\" parser to build a tree. The \"generic\" parser simply\n splits on Title Case and treats body text as the node content.\"\"\"\n segments = generic.segments(text)\n if not segments:\n return Node(text, label=label, title=title, node_type=Node.APPENDIX)\n\n children = []\n for index, seg in enumerate(segments):\n start, end = seg\n seg_title, body = utils.title_body(text[start:end])\n label_character = letter_for(index)\n children.append(\n Node(body, label=(\n label + [label_character]),\n title=seg_title, node_type=Node.APPENDIX))\n\n return Node(text[:segments[0][0]], children, label, title, Node.APPENDIX)\n\n\ndef paragraph_tree(appendix_letter, sections, text, label, title=None):\n \"\"\"Use the paragraph parser to parse through each section in this\n appendix.\"\"\"\n if not sections:\n return Node(text, label=label, title=title, node_type=Node.APPENDIX)\n children = []\n for begin, end in sections:\n seg_title, section_text = utils.title_body(text[begin:end])\n sec_num = carving.get_appendix_section_number(\n seg_title, appendix_letter)\n exclude = [(pc.full_start, pc.full_end) for pc in\n internal_citations(section_text, Label(part=label[0]))]\n\n child = parParser.build_tree(\n section_text, exclude=exclude, label=label + [sec_num],\n title=seg_title)\n\n children.append(child)\n return Node(text[:sections[0][0]], children, label, title, Node.APPENDIX)\n","repo_name":"cfpb/regulations-parser","sub_path":"regparser/tree/appendix/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"85"} +{"seq_id":"41921707341","text":"import win32gui\nimport win32ui\nimport win32con\nimport pygetwindow\nimport numpy\nimport cv2\n\ndef StartYOLOV8():\n count = 0\n window_process = pygetwindow.getActiveWindow()\n\n title = window_process.title\n left = window_process.left\n top = window_process.top\n width = window_process.width\n height = window_process.height\n\n d = {\n \"title :\": title,\n \"left :\": left,\n \"top :\": top,\n \"width :\": width,\n \"height:\": height,\n }\n print(\"get windows app process info :\", d)\n\n while True:\n hdesktop = win32gui.GetDesktopWindow()\n desktop_dc = win32gui.GetWindowDC(hdesktop)\n img_dc = win32ui.CreateDCFromHandle(desktop_dc)\n mem_dc = img_dc.CreateCompatibleDC()\n screenshot = win32ui.CreateBitmap()\n screenshot.CreateCompatibleBitmap(img_dc, width, height)\n mem_dc.SelectObject(screenshot)\n mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY)\n\n # 展示图片 使用 numpy 转换\n signedIntsArray = screenshot.GetBitmapBits(True)\n img = numpy.frombuffer(signedIntsArray, dtype='uint8')\n img.shape = (height, width, 4)\n\n\n # cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)\n # cv2.imwrite(\"img.jpg\",img,[int(cv2.IMWRITE_JPEG_QUALITY), 100])\n # cv2.namedWindow('img') #命名窗口\n cv2.imshow(\"img\", img) # 显示\n cv2.waitKey(1)\n\n # 保存图片\n # screenshot.SaveBitmapFile(mem_dc, 'screenshot.png')\n\n # 释放临时内存\n mem_dc.DeleteDC()\n win32gui.DeleteObject(screenshot.GetHandle())\n\n count += 1\n print(\"截图了\", count, \"次\")\n\n print(\"start yolov8\")","repo_name":"WangRui1416431931/yolo_dnf","sub_path":"utils/process_yolo.py","file_name":"process_yolo.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"73943294356","text":"from pygments import highlight\nfrom pygments.lexer import Lexer\nfrom pygments.formatter import Formatter\nfrom pygments.lexers import (\n get_lexer_by_name, get_all_lexers, guess_lexer,\n find_lexer_class_by_name\n)\nfrom pygments.formatters import (\n TerminalFormatter,\n NullFormatter\n)\n\nfrom dataclasses import dataclass\nfrom typing import Optional\nfrom pygments.util import ClassNotFound\n\nfrom .streaming_lexer import (\n SinglePassStreamingLexer,\n Token,\n TokenType,\n TokenOrientation\n)\n\nfrom .color import (\n get_color_codes,\n ColorCode,\n)\n\n# Guessing languages takes time ...\n# Assume these are our candidates since\n# they likely cover upward of 90% of\n# usage\nGUESSABLE_LANGUAGES = [\n 'html',\n 'python',\n 'java',\n 'python2',\n 'c++',\n 'javascript',\n 'c#',\n 'sql',\n 'c',\n 'php',\n 'go',\n 'swift',\n 'kotlin',\n 'ruby',\n 'typescript',\n 'scala',\n 'r',\n 'rust',\n 'css',\n 'perl',\n 'make',\n 'text'\n]\n\ndef guess_lexer( text : str, **options ):\n '''\n Guess the lexer in use from GUESSABLE_LANGUAGES.\n\n Uses very primitive heuristics and is not very good.\n '''\n\n best_lexer = [0.0, None]\n\n for lexer_name in GUESSABLE_LANGUAGES:\n\n lexer = find_lexer_class_by_name(lexer_name)\n\n rv = lexer.analyse_text(text)\n\n if rv == 1.0:\n return lexer(**options)\n if rv > best_lexer[0]:\n best_lexer[:] = (rv, lexer)\n\n if not best_lexer[0] or best_lexer[1] is None:\n\n raise ClassNotFound('no lexer matching the text found')\n\n return best_lexer[1](**options)\n\n@dataclass\nclass CodefenceContext:\n language: str\n lexer : Lexer\n formatter : Formatter\n buffer : str = ''\n eof : bool = False\n\n def may_guess_language( self : \"CodefenceContext\" ):\n\n if self.eof:\n return True\n\n MIN_CHARACTERS = 150\n MIN_LINES = 2\n\n return (\n len(self.buffer) > MIN_CHARACTERS and\n self.buffer.count('\\n') > MIN_LINES\n )\n\n def get_highlighted_lines(self : \"CodefenceContext\"):\n\n if self.language is None:\n if self.may_guess_language():\n\n lexer = guess_lexer( self.buffer )\n\n self.language = lexer.name\n self.lexer = lexer\n\n else:\n return None\n\n\n idx = self.buffer.rfind('\\n')\n\n if idx == -1:\n return None\n else:\n lines = self.buffer[:idx+1]\n self.buffer = self.buffer[idx+1:]\n\n highlighted = highlight(\n lines,\n self.lexer,\n self.formatter,\n )\n\n return highlighted\n\nclass ChatColorizer( object ):\n\n lexer : SinglePassStreamingLexer\n formatter : Formatter\n cf_ctx : Optional[CodefenceContext]\n color_code : ColorCode\n text_emitted: bool\n\n def __init__( self : \"ChatColorizer\", no_color = False ):\n self.lexer = SinglePassStreamingLexer()\n\n self.cf_ctx = None\n\n if no_color:\n self.formatter = NullFormatter()\n else:\n self.formatter = TerminalFormatter()\n\n self.color_code = get_color_codes( no_color=no_color )\n self.text_emitted = False\n\n def add_chunk( self : \"ChatColorizer\", chunk : str ):\n self.lexer.add_chunk( chunk )\n\n def print( self : \"ChatColorizer\" ):\n\n for token in self.lexer.parse():\n\n if token.type == TokenType.EOF:\n break\n\n if token.type == TokenType.CODE_FENCE:\n\n if not self.text_emitted:\n print()\n self.text_emitted = True\n\n if token.orientation == TokenOrientation.BEGIN:\n assert self.cf_ctx is None\n\n lang = token.content\n\n try:\n lexer = get_lexer_by_name(lang)\n except ClassNotFound:\n # try to guess it\n lang = None\n lexer = None\n\n self.cf_ctx = CodefenceContext(lang, lexer, self.formatter)\n\n else:\n assert self.cf_ctx is not None\n\n self.cf_ctx.eof = True\n\n highlighted = self.cf_ctx.get_highlighted_lines()\n\n if highlighted:\n print( highlighted, end='', flush=True )\n\n self.cf_ctx = None\n\n # Add extra \\n to either side of a chunk\n print(f'{self.color_code.WHITE}```{self.color_code.RESET}', flush=True)\n\n continue\n\n if self.cf_ctx:\n\n self.cf_ctx.buffer += token.content\n highlighted = self.cf_ctx.get_highlighted_lines()\n\n if highlighted:\n print( highlighted, end='', flush=True )\n\n else:\n\n print( f'{self.color_code.WHITE}{token.content}{self.color_code.RESET}', end='', flush=True )\n self.text_emitted = True\n\n\n def finish( self : \"ChatColorizer\" ):\n self.lexer.finish()\n","repo_name":"flu0r1ne/gpt-chat-cli","sub_path":"src/gpt_chat_cli/chat_colorizer.py","file_name":"chat_colorizer.py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12349176205","text":"from bs4 import BeautifulSoup\nimport re\nimport sys\nimport requests\nimport unidecode\nfrom datetime import datetime\nfrom pytz import timezone\n\n\ndef _get_html(package_id):\n\n url = 'http://www.ctt.pt/feapl_2/app/open/objectSearch/objectSearch.jspx'\n data = {\"showResults\": \"true\", \"objects\": package_id}\n r = requests.post(url, data=data)\n return r.text\n\n\ndef _convert_date(d):\n f = d.split(' ')\n months = {\n \"Janeiro\": '01',\n \"Fevereiro\": \"02\",\n \"Marco\": \"03\",\n \"Abril\": \"04\",\n \"Maio\": \"05\",\n \"Junho\": \"06\",\n \"Julho\": \"07\",\n \"Agosto\": \"08\",\n \"Setembro\": \"09\",\n \"Outubro\": \"10\",\n \"Novembro\": \"11\",\n \"Dezembro\": \"12\"\n }\n day = int(f[1])\n if day < 10:\n day = '0' + str(day)\n\n month = f[2]\n n = month\n month = unidecode.unidecode(n)\n\n return f[3] + '/' + months[month] + '/' + str(day)\n\n\ndef _is_date(d):\n if re.search('\\d{4}$', d) is not None:\n return True\n else:\n return False\n\ndef _get_current_date_time():\n d = datetime.now(timezone('Europe/Lisbon'))\n year = str(d.year)\n month = str(d.month)\n day = str(d.day)\n hour = str(d.hour)\n minute = str(d.minute)\n if int(month) < 10:\n month = \"0\" + month\n if int(day) < 10:\n day = \"0\" + day\n if int(hour) < 10:\n hour = \"0\" + hour\n if int(minute) < 10:\n minute = \"0\" + minute\n\n return year + \"/\" + month + \"/\" + day + \" \" + hour + \":\" + minute\n\n\ndef get_package_status(p_id):\n\n html = _get_html(p_id)\n soup = BeautifulSoup(html, \"html.parser\")\n d = []\n package = {}\n\n for td in soup.find_all('td'):\n t = td.string\n if t is not None:\n t = re.sub(r'^\\s+', '', re.sub(r'\\s+$', '', td.string))\n d.append(t)\n\n package[\"id\"] = d.pop(0)\n d.pop(0)\n if d[0] == 'N/A':\n package[\"status\"] = [{\"status\": \"Not Found\", \"date\": _get_current_date_time(), \"reason\": None, \"place\": None, \"receiver\": None}]\n package[\"id\"] = p_id\n return package\n\n s_date = d.pop(0)\n s_time = d.pop(0)\n status = d.pop(0)\n\n package[\"status\"] = [{\"status\": status, \"date\": s_date + ' ' + s_time}]\n d.pop(0)\n d.pop(0)\n while (len(d) > 0):\n s_date = d.pop(0)\n if _is_date(s_date):\n s_time = d.pop(0)\n s_date_time = _convert_date(s_date) + ' ' + s_time\n else:\n s_time = s_date\n s_date = package[\"status\"][0][\"date\"]\n s_date = re.sub(r'\\ \\d\\d:\\d\\d$', '', s_date)\n s_date_time = s_date + ' ' + s_time\n\n status = d.pop(0)\n reason = d.pop(0)\n place = d.pop(0)\n receiver = d.pop(0)\n\n status_data = {\n \"status\": status,\n \"date\": s_date_time,\n \"reason\": reason,\n \"place\": place,\n \"receiver\": receiver\n }\n if package[\"status\"][0][\"date\"] == status_data[\"date\"]:\n package[\"status\"][0][\"reason\"] = status_data[\"reason\"]\n package[\"status\"][0][\"place\"] = status_data[\"place\"]\n package[\"status\"][0][\"receiver\"] = status_data[\"receiver\"]\n if package[\"status\"][0][\"status\"] == \"\":\n package[\"status\"][0][\"status\"] = status_data[\"status\"]\n\n else:\n package[\"status\"].append(status_data)\n\n return package\n\n","repo_name":"bmartins/python-ctt","sub_path":"ctt/ctt.py","file_name":"ctt.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15323850931","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import DetailView, ListView, CreateView, UpdateView, DeleteView, FormView\nfrom .models import Classroom, Subject, Lesson, TimeSlots, Grade\nfrom django.urls import reverse_lazy\nfrom .forms import CommentForm, ReplyForm, LessonForm\nfrom django.http import HttpResponseRedirect, HttpResponseForbidden\nfrom django.contrib.auth.decorators import login_required\nfrom completion.models import Completion\n\n\nclass ClassroomListView(ListView):\n context_object_name = 'classrooms'\n model = Classroom\n template_name = 'classroom/classroom_list_view.html'\n\n\n# class SubjectListView(DetailView):\n# context_object_name = 'classrooms'\n# extra_context = {\n# 'slots': TimeSlots.objects.all()\n# }\n# model = Classroom\n# template_name = 'classroom/subject_list_view.html'\n\n\nclass LessonListView(DetailView):\n context_object_name = 'subjects'\n model = Subject\n template_name = 'classroom/lesson_list_view.html'\n\n def get_context_data(self, *args, **kwargs):\n context = super(LessonListView, self).get_context_data(*args, **kwargs)\n user = self.object.classroom.bookings.student_id.user\n subject = self.object.id\n context['lesson_completions'] = Completion.objects.filter(user=user, subject=subject).values_list('lesson__pk', flat=True)\n\n return context\n\n\nclass LessonDetailView(DetailView, FormView):\n context_object_name = 'lessons'\n model = Lesson\n template_name = 'classroom/lesson_detail_view.html'\n form_class = CommentForm\n second_form_class = ReplyForm\n\n def get_context_data(self, **kwargs):\n context = super(LessonDetailView, self).get_context_data(**kwargs)\n subject = self.object.subject\n lesson = self.object.id\n context['completed'] = Completion.objects.filter(subject=subject.id, user=self.request.user, lesson=lesson).exists()\n\n if 'form' not in context:\n context['form'] = self.form_class(request=self.request)\n if 'form2' not in context:\n context['form2'] = self.second_form_class(request=self.request)\n return context\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n if 'form' in request.POST:\n form_class = self.get_form_class()\n form_name = 'form'\n else:\n form_class = self.second_form_class\n form_name = 'form2'\n\n form = self.get_form(form_class)\n\n if form_name == 'form' and form.is_valid():\n print(\"comment form is returned\")\n return self.form_valid(form)\n elif form_name == 'form2' and form.is_valid():\n print(\"reply form is returned\")\n return self.form2_valid(form)\n\n def get_success_url(self):\n self.object = self.get_object()\n classroom = self.object.Classroom\n subject = self.object.subject\n return reverse_lazy('classroom:lesson_detail', kwargs={'classroom': classroom.slug, 'subject': subject.slug, 'slug': self.object.slug})\n\n def form_valid(self, form):\n self.object = self.get_object()\n fm = form.save(commit=False)\n fm.author = self.request.user\n fm.lesson_name = self.object.comments.name\n fm.lesson_name_id = self.object.id\n fm.save()\n return HttpResponseRedirect(self.get_success_url())\n\n def form2_valid(self, form):\n self.object = self.get_object()\n fm = form.save(commit=False)\n fm.author = self.request.user\n fm.comment_name_id = self.request.POST.get('comment.id')\n fm.save()\n return HttpResponseRedirect(self.get_success_url())\n\ndef mark_lesson_as_done(request, **kwargs):\n\tuser = request.user\n\tsubject_id = kwargs.get('subject_id')\n\tlesson_id = kwargs.get('lesson_id')\n\tlesson = Lesson.objects.get(id=lesson_id)\n\tsubject = Subject.objects.get(id=subject_id)\n\tCompletion.objects.create(user=user, subject=subject, lesson=lesson)\n\n\treturn redirect('classroom:lesson_list', slug=subject.slug, subject_id=subject_id)\n\n\nclass LessonCreateView(CreateView):\n form_class = LessonForm\n context_object_name = 'subject'\n model = Subject\n template_name = 'classroom/lesson_create.html'\n\n def get_success_url(self):\n self.object = self.get_object()\n classroom = self.object.classroom\n return reverse_lazy('classroom:lesson_list', kwargs={'slug': self.object.slug, 'subject_id': self.object.id})\n\n def form_valid(self, form, *args, **kwargs):\n self.object = self.get_object()\n fm = form.save(commit=False)\n fm.created_by = self.request.user\n fm.Classroom = self.object.classroom\n fm.subject = self.object\n fm.save()\n return HttpResponseRedirect(self.get_success_url())\n\n\nclass LessonUpdateView(UpdateView):\n fields = ['name', 'position', 'video', 'ppt', 'Notes']\n model = Lesson\n template_name = 'classroom/lesson_update.html'\n context_object_name = 'lessons'\n\n\nclass LessonDeleteView(DeleteView):\n model = Lesson\n context_object_name = 'lessons'\n template_name = 'classroom/lesson_delete.html'\n\n def get_success_url(self):\n print(self.object)\n classroom = self.object.Classroom\n subject = self.object.subject\n return reverse_lazy('classroom:lesson_list', kwargs={'classroom': classroom.slug, 'slug': subject.slug})\n\n\ndef lesson_completed(request, **kwargs):\n lesson = Lesson.objects.get(id=kwargs.get('lesson_id'))\n\n if 'completed' in request.POST:\n lesson.completed = True\n lesson.save()\n\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n elif 'not_completed' in request.POST:\n lesson.completed = False\n lesson.save()\n\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n return render(request, 'classroom/lesson_detail_view.html')\n\n\n# def lesson_not_completed(request, **kwargs):\n# lesson = Lesson.objects.get(id=kwargs.get('id'))\n# print('executed not completed')\n# print(request.POST)\n# print(request.POST)\n# if 'submit' in request.POST:\n# if 'not_completed' == request.POST.get('submit'):\n# lesson.completed = False\n# lesson.save()\n#\n# return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n#\n# return render(request, 'classroom/lesson_detail_view.html')\n\nclass SubjectListView(DetailView):\n context_object_name = 'classrooms'\n extra_context = {\n 'slots': TimeSlots.objects.all()\n }\n model = Classroom\n template_name = 'classroom/subject_list_view.html'\n\n\n@login_required\ndef course_detail(request, **kwargs):\n\tuser = request.user\n\tsubject = Subject.objects.get(id=kwargs.get('subject_id'))\n\n\tcontext = {\n\t\t'subject': subject,\n\t}\n\n\treturn render(request, 'classroom/course.html', context)\n\n\ndef submissions(request, **kwargs):\n user = request.user\n subject_id = kwargs.get('subject_id')\n subject = Subject.objects.get(id=subject_id)\n grades = Grade.objects.filter(subject=subject, submission__user=user)\n context = {\n\t\t'grades': grades,\n\t\t'subject': subject\n\t}\n return render(request, 'classroom/submissions.html', context)\n\n\ndef student_submissions(request, **kwargs):\n user = request.user\n subject_id = kwargs.get('subject_id')\n subject = Subject.objects.get(id=subject_id)\n if user != subject.classroom.bookings.tutor_id.user:\n\t return HttpResponseForbidden()\n else:\n grades = Grade.objects.filter(subject=subject)\n context = {\n\t\t\t'subject': subject,\n\t\t\t'grades': grades,\n }\n return render(request,'classroom/studentgrades.html', context)\n\n\ndef grade_submission(request, **kwargs):\n user = request.user\n grade_id = kwargs.get('grade_id')\n subject_id = kwargs.get('subject_id')\n subject = Subject.objects.get(id=subject_id)\n grade = Grade.objects.get(id=grade_id)\n\n if user != subject.classroom.bookings.tutor_id.user:\n\t return HttpResponseForbidden()\n else:\n\t if request.method == 'POST':\n\t\t points = request.POST.get('points')\n\t\t grade.points = points\n\t\t grade.status = 'graded'\n\t\t grade.graded_by = user\n\t\t grade.save()\n\t\t return redirect('classroom:student-submissions', slug=subject.slug, subject_id=subject.id)\n context = {\n\t\t'subject': subject,\n\t\t'grade': grade,\n\t}\n\n return render(request, 'classroom/gradesubmission.html', context)\n","repo_name":"reinhardkent03/thesisproj","sub_path":"gurufinder/classroom/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42739991821","text":"import time\nfrom typing import Optional\n\nimport rich.progress\nfrom rlmeta.core.controller import Phase, ControllerLike\nfrom rlmeta.utils.stats_dict import StatsDict\n\nfrom agents.core import Agent, Learner\n\n\nclass DistributedAgent(Agent):\n def __init__(self, controller: ControllerLike, learner: Learner, writer=None):\n self._controller = controller\n self._learner = learner\n self._writer = writer\n self._stats_dict = StatsDict()\n self._start_time = time.perf_counter()\n\n def set_phase(self, phase=Phase.TRAIN):\n self._controller.set_phase(phase=phase)\n\n def train(self, num_steps: int) -> int:\n self._controller.set_phase(Phase.TRAIN)\n self._learner.prepare()\n for local_steps in rich.progress.track(range(num_steps), description=\"Training\"):\n metrics = self._learner.train_step()\n self._stats_dict.extend({k: float(v) for k, v in metrics.items()})\n if local_steps % 100 == 0:\n # self._writer.run.log({f\"{k}_mean\": v['mean'] for k, v in self._stats_dict.dict().items() if \"debug\" in k})\n self._writer.run.log({k: float(v) for k, v in metrics.items()})\n remote_metrics = self._controller.stats(Phase.TRAIN).dict()\n total_samples = remote_metrics[\"episode_length\"][\"mean\"] * remote_metrics[\"episode_length\"][\"count\"]\n delta_samples = (total_samples / (time.perf_counter() - self._start_time))\n self._writer.run.log({\"debug/total_samples\": total_samples})\n self._writer.run.log({f\"train_envs/{k.replace('/', '_')}\": v['mean'] for k, v in remote_metrics.items()})\n self._writer.run.log({\"debug/samples_per_second\": delta_samples})\n return total_samples\n\n def eval(self,\n num_episodes: Optional[int] = None,\n keep_training_loops: bool = True) -> Optional[StatsDict]:\n if keep_training_loops:\n self._controller.set_phase(Phase.BOTH)\n else:\n self._controller.set_phase(Phase.EVAL)\n self._controller.reset_phase(Phase.EVAL, limit=num_episodes)\n while self._controller.count(Phase.EVAL) < num_episodes:\n time.sleep(1)\n stats = self._controller.stats(Phase.EVAL)\n self._writer.run.log({f\"eval_envs/{k.replace('/', '_')}\": v['mean'] for k, v in stats.dict().items()})\n return stats\n\n def connect(self):\n self._controller.connect()\n self._learner.connect()\n","repo_name":"d3sm0/impala","sub_path":"agents/distributed_agent.py","file_name":"distributed_agent.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1479523830","text":"# Duck tests - walk like a duck, quack like a duck - it must be a duck (sometime wrong but most time ok)\n# Easier to ask forgiveness than permission (EAFP) - not advised to check all the times for attritutes\n\nimport os\nmy_file = \"/tmp/test.txt\"\n\n# # Race Condition\n# if os.access(my_file, os.R_OK): # sometime pass here but fail below\n# with open(my_file) as f:\n# print(f.read())\n# else:\n# print('File can not be accessed')\n\n\n# No Race-condition\ntry:\n f = open(my_file)\nexcept IOError as e:\n print('File can not be accessed')\nelse:\n with f:\n print(f.read())\n","repo_name":"UncleBob2/MyPythonCookBook","sub_path":"race conditions while checking EAFP.py","file_name":"race conditions while checking EAFP.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8139632793","text":"from __future__ import absolute_import\nfrom django.conf.urls import patterns, url\nfrom .views import cancel_appointment\nfrom .viewers_views import display_date_form,\\\n render_appointment_list, choose_calendar, \\\n calendar_search_view, weekview, overview, \\\n appointment_detail, appointments_by_date, \\\n appointments_made_by, choose_an_employee, wrong_postcode\nfrom .views import appointment_manipulation\nfrom .views import get_available_dates, get_customer, get_candidate_dates\n\n\nurlpatterns = patterns('',\n (r'^get_available_dates/(?P\\w*)/(?P\\d+)/(?P\\d{0,8})/(?P[-]?\\d+)/(?P\\w*)', get_available_dates),\n (r'^get_candidate_dates/(?P\\d{0,8})/(?P\\d+)/(?P[-]?\\w+)/(?P[-]?\\d+)/(?P\\w*)/(?P[-]?\\d+)', get_candidate_dates),\n (r'^get_customer/(?P\\w+)/(?P\\w+)/(?P\\w*)', get_customer),\n url(r'^app/detail/(?P\\d+)$', appointment_detail, name='AppointmentView'),\n url(r'^edit/(?P\\w+)/(?P\\w+)/(?P\\d{0,8})', appointment_manipulation, name='AppointmentEditExtra'),\n (r'^list/choose', display_date_form),\n (r'^list/date_chosen/(?P\\d{8})', choose_calendar),\n (r'^list/appointments/(?P\\d+)', render_appointment_list),\n url(r'^app/cancel/(?P\\d+)', cancel_appointment, name=\"CancelAppointment\"),\n url(r'^overview/(?P\\d{0,8})$', overview, name='Overview'),\n url(r'^search/(?P\\d{0,8})$', calendar_search_view, name='Search'),\n url(r'^week/(?P\\d+)/(?P[-]?\\d+)/(?P\\d{0,8})$', weekview, name='WeekView'),\n url(r'^made_at/(?P\\d{0,8})$', appointments_by_date, name='AppointmentsToday'),\n url(r'^made_by/(?P\\d+)', appointments_made_by, name='AppointmentsMadeBy'),\n url(r'^employee/', choose_an_employee, name='ChooseAnEmployee'),\n url(r'^wrong/', wrong_postcode, name='WrongPostcode'),\n)\n","repo_name":"slspeek/gnudok-planner","sub_path":"src/planner/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4794130979","text":"from django.shortcuts import render, redirect\nimport markdown\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom . import util\nfrom django.http import HttpResponseRedirect\nfrom django import forms\nimport random\n\n\n\n\n# Since we're going to be needing the markdown...a converter is needed\ndef md_converter(variable):\n content = util.get_entry(variable)\n mark_down = markdown.Markdown()\n if content == None:\n return None\n else:\n converted_content = mark_down.convert(content)\n return converted_content\n\n# then we'd need the title showing on the url \ndef entry(request, title):\n approved_content = md_converter(title)\n if approved_content is None:\n return render(request, \"encyclopedia/404.html\", {'message': messages.error(request, 'Does not Exist'), 'title': title}) \n else:\n return render(request, \"encyclopedia/entry.html\",{'title': title, 'approved_content': approved_content})\n\ndef index(request):\n if request.method == 'POST':\n title_form = request.POST.get('form_title')\n form_text = request.POST.get('text_form')\n if title_form and form_text:\n if util.get_entry(title_form):\n error_message = f\"'{title_form}' already exists.\"\n return render(request, 'encyclopedia/index.html', {'entries': util.list_entries(), 'error_message': error_message})\n new_saves = util.save_entry(title_form, form_text)\n if new_saves:\n request.session['new_saves'] = new_saves\n return redirect('encyclopedia:new_entry', title=title_form) \n return render(request, 'encyclopedia/index.html', {'entries': util.list_entries()})\n \ndef new_entry(request, title):\n entryy = util.get_entry(title)\n if entryy is None:\n return render(request, 'encyclopedia/404.html', {'error_message': f\"'{title}' not found.\"})\n return render(request, 'encyclopedia/new_entry.html', {'title': title, 'entry': entryy})\n\n\ndef search(request):\n if request.method == 'POST':\n result = request.POST['q']\n \n if result is not None:\n entry = md_converter(result) \n if entry is None:\n all_entries = util.list_entries()\n partial_matches = [entry for entry in all_entries if result.lower() in entry.lower()]# check for the partial_match to the entry\n if partial_matches:\n return render(request, 'encyclopedia/partial_matches.html', {'partial_matches': partial_matches})\n return render(request, 'encyclopedia/search.html', {'entry': entry})\n return render(request, 'encyclopedia/404.html')\n \n# new_page\n\nclass NewEntryForm(forms.Form):\n text_form = forms.CharField(widget=forms.Textarea)\n form_title = forms.CharField(label=\"form_title\")\n \ndef create(request):\n if request.method == 'POST':\n entry_form = NewEntryForm(request.POST)\n if entry_form.is_valid():\n print(entry_form.cleaned_data)\n form_title = entry_form.cleaned_data[\"form_title\"]\n text_form = entry_form.cleaned_data[\"text_form\"]\n approved_contents = util.save_entry(form_title,text_form)\n if approved_contents:\n request.session['approved_contents'] = True\n return redirect(reverse('encyclopedia:index') + f'?title_form={form_title}')\n else:\n return render(request, 'encyclopedia/404.html')\n # If not approved, redirect to the newly created entry's page \n entry_form = NewEntryForm() \n return render(request, 'encyclopedia/create.html', {'form': entry_form})\n\n\n\ndef edit_entry(request, title):\n entry_content = util.get_entry(title)\n print(title)\n if entry_content is None:\n return render(request, 'encyclopedia/404.html', {'error_message': f\"'{title}' not found.\"})\n \n if request.method == 'POST':\n edit_contents = request.POST.get('edit_contents')\n util.save_entry(title,edit_contents)\n if edit_contents:\n request.session['edit_success'] = True\n return redirect('encyclopedia:title', title=title)\n return redirect('encyclopedia:index', title=title)\n\n return render(request, 'encyclopedia/edit.html', {\"title\": title, 'entry_content':entry_content})\n\ndef random_page(request):\n entries = util.list_entries()\n if entries:\n random_title = random.choice(entries)\n return redirect('encyclopedia:title', title = random_title)\n return render(request,'encyclopedia/404.html')\n \n\n\n\n \n \n \n \n \n \n\n \n \n\n ","repo_name":"JYDE1-dev/Encyclopedia","sub_path":"encyclopedia/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34150975146","text":"class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n cur=[]\n ans=[]\n sum=0\n n=len(candidates)\n def dfs(idx, cur, ans, sum):\n if(sum==target):\n ans.append(cur.copy())\n return \n if(sum>=target):\n return;\n \n for i in range(idx,n):\n ele=candidates[i]\n cur.append(ele)\n dfs(i, cur, ans, sum+ele)\n cur.pop()\n dfs(0,cur,ans, sum)\n return ans","repo_name":"apoc146/LeetCode","sub_path":"0039-combination-sum/0039-combination-sum.py","file_name":"0039-combination-sum.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5308085162","text":"\"\"\"\nPurpose of the script is to populate the sqlite ansible database.\n\"\"\"\n\nimport json\nfrom lib import ansiblestore\nfrom lib import my_env\nfrom lib.my_env import *\nfrom lib import neostore\n\n\ndef handle_dict(diction, this_table, **table_props):\n \"\"\"\n This function handles a dictionary. First collect all attributes for the table and add values as row in the\n database. Then walk through all linked tables.\n\n :param diction: dictionary to handle\n :param this_table: Unique name of the current table (not the name of the dictionary)\n :param table_props: Properties of the parent table (name and ID of last inserted record).\n :return:\n \"\"\"\n row_dict = {}\n attribs = attribs_table[this_table]\n for attrib in attribs:\n # logging.info(f\"Evaluating {attrib}\")\n try:\n if isinstance(diction[attrib], list):\n # print(f\"Evaluating: {diction[attrib]}\")\n row_dict[clean(attrib)] = \", \".join(str(v) for v in diction[attrib])\n else:\n row_dict[clean(attrib)] = diction[attrib]\n except KeyError:\n pass\n # Now add link to parent table in current record. Field name is in table_attrib, field value is in table_id.\n try:\n row_dict[table_props['table_attrib']] = table_props['table_id']\n except KeyError:\n pass\n table_id = ans.insert_row(this_table, row_dict)\n table_attrib = f\"{this_table}_id\"\n props = dict(table_id=table_id, table=this_table, table_attrib=table_attrib)\n tables = linked_tables[this_table]\n for table in tables:\n unique_tn = table[\"unique_tn\"]\n attrib = table['table']\n try:\n if isinstance(diction[attrib], dict):\n handle_dict(diction[attrib], unique_tn, **props)\n elif isinstance(diction[attrib], list):\n for elem in diction[attrib]:\n if isinstance(elem, dict):\n handle_dict(elem, unique_tn, **props)\n else:\n logging.debug(f\"Dictionary expected for {attrib}, found {type(diction[attrib])} \"\n f\"containing {diction[attrib]}\")\n except KeyError:\n pass\n return\n\n\ndef get_attributes(sn):\n \"\"\"\n This module will get the attributes from a table and add the attributes as a list to the table.\n\n :param sn: Start node for the table.\n :return:\n \"\"\"\n table_name = ns.get_unique_tn(sn)\n attribs = []\n cursor = ns.get_attribs(sn)\n while cursor.forward():\n rec = cursor.current\n node = rec['end_node']\n attrib = next(iter(node.labels))\n attribs.append(attrib)\n attribs_table[table_name] = attribs\n # Now get child-tables linking to this table.\n get_tables(sn)\n return\n\n\ndef get_tables(sn):\n \"\"\"\n This script will get all tables linked to a parent table.\n\n :param sn: Start node\n :return:\n \"\"\"\n parent_table = ns.get_unique_tn(sn)\n tables = []\n cursor = ns.get_tables(sn)\n while cursor.forward():\n rec = cursor.current\n node = rec['end_node']\n table = next(iter(node.labels))\n unique_tn = ns.get_unique_tn(node)\n props = dict(table=table, unique_tn=unique_tn)\n tables.append(props)\n get_attributes(node)\n linked_tables[parent_table] = tables\n return\n\n\n# Initialize Environment\nprojectname = \"ansible\"\nconfig = my_env.init_env(projectname, __file__)\nlogging.info(\"Start application\")\ncmdb_json = os.getenv('JSONFILE')\nans = ansiblestore.SqliteUtils()\nns = neostore.NeoStore(refresh='No')\n\n# Collect structure first: attributes related to tables, and how tables are linked to each other.\n# Key is the unique table name, value is a list of dictionary attributes\nattribs_table = {}\n# Key is unique table name, value is dictionary with table (dictionary table name) and unique_tn (unique table name)\nlinked_tables = {}\nstart_node = ns.get_nodes('server')[0]\nget_attributes(start_node)\n\nwith open(cmdb_json) as cmdb_file:\n data = json.loads(cmdb_file.read())\n li = my_env.LoopInfo('Servers', 20)\n # Create Server Node\n t_name = 'server'\n for item in data:\n li.info_loop()\n logging.info(f\"Working on server {item}\")\n handle_dict(data[item], t_name)\n li.end_loop()\nlogging.info(\"End Application\")\n","repo_name":"dirkhpe/ansib","sub_path":"populate_sqldb_from_neo.py","file_name":"populate_sqldb_from_neo.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18584660770","text":"from typing import Any\nimport torch\nimport torch.nn as nn\nfrom pytorch_lightning import LightningModule\nfrom torch.nn.functional import mse_loss\nfrom .PDE_NET2.polypde import POLYPDE2D\nfrom .utils import plot\n\nclass PDENet(nn.Module):\n def __init__(self,\n input_dim,\n max_order,\n kernel_size=5,\n constraint='frozen', \n hidden_layers=2, \n scheme='upwind',\n dt=1,\n dx=1):\n super().__init__()\n self.num_channel = input_dim\n channel_names_str = 'u'\n self.pdenet = POLYPDE2D(\n dt=dt,\n dx=dx,\n kernel_size=kernel_size,\n max_order=max_order,\n constraint=constraint,\n channel_names=channel_names_str,\n hidden_layers=hidden_layers,\n scheme=scheme\n ).to(torch.float32)\n\n def forward(self, x, num_steps):\n x = torch.unsqueeze(x, dim=1) # introduces channel dim\n return self.pdenet.multistep(x, num_steps)\n\nclass PDENetModule(LightningModule):\n def __init__(self, net: nn.Module,\n learning_rate: float,\n weight_decay: float,\n plot: bool=False,\n point_wise: bool=False,\n order: int=2,\n N: int=64,\n equation: str='',\n *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.net = net\n self.loss = mse_loss\n self.lr = learning_rate\n self.wd = weight_decay\n self.plot = plot\n self.order = order\n self.N = N\n self.point_wise = point_wise\n self.equation = equation\n\n def step(self, batch: Any, test: bool=False):\n x, y, forecast = batch['x'], batch['y'], batch['forecast'][0]\n x = torch.reshape(x, (x.size()[0], self.N, self.N))\n if test:\n with torch.inference_mode(False):\n y_hat = self.net(x, forecast)\n else:\n y_hat = self.net(x, forecast)\n y_hat = torch.reshape(y_hat, (x.size()[0], forecast, self.N*self.N))\n loss = self.loss(y_hat, y)\n return loss, y_hat, y, x\n\n def training_step(self, batch: Any, batch_idx: int):\n loss, y_hat, y, x = self.step(batch)\n self.log(\"train_loss\", loss)\n return loss\n\n def validation_step(self, batch: Any, batch_idx: int):\n # compare weights with real pde\n real = batch['real']\n dict_coeffs = self.coeffs()\n try:\n self.log_dict(dict_coeffs)\n except:\n pass\n real = self.dict2tensor(real)\n coeffs = self.dict2tensor(dict_coeffs)\n val_loss = self.loss(coeffs, real)\n self.log(\"val_loss\", val_loss, prog_bar=True)\n return val_loss\n\n def test_step(self, batch: Any, batch_idx: int):\n points = batch['points']\n loss, y_hat, y, x = self.step(batch, test=True)\n dict_coeffs = self.coeffs()\n self.printdict(dict_coeffs)\n if self.plot: plot.show_img_irregular(x=x, y_hat=y_hat, y=y, s='forecast_test_PDEnet_'+self.equation, points=points[0])\n self.log(\"test_loss\", loss)\n return loss\n\n def configure_optimizers(self):\n return torch.optim.NAdam(self.net.parameters(), lr=self.lr, weight_decay=self.wd)\n\n def coeffs(self):\n model = self.net.pdenet\n dict_coeffs = None # dictionary for values\n for poly in model.polys:\n try:\n names, values = poly.coeffs()\n names = [f'{i}' for i in names]\n dict_coeffs = dict(zip(names, values))\n except:\n pass\n return dict_coeffs\n \n def dict2tensor(self, d):\n l = []\n for i in range(self.order+1):\n for j in range(self.order+1-i):\n s = f'u{i}{j}'\n try:\n try:\n l.append(d[s][0])\n except:\n l.append(d[s])\n except:\n l.append(0.0)\n return torch.tensor(l, dtype=torch.float32)\n \n def printdict(self, dict):\n s = \"\\n\".join(\"{0}: {1}\".format(k, v) for k,v in dict.items())\n print(s)","repo_name":"LSX-UniWue/TaylorPDENet","sub_path":"models/pde_net_module.py","file_name":"pde_net_module.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"41258482469","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom exam9 import settings\nfrom webapp.models import RegistrationToken, Product, ProductPhoto, Order, Category\nfrom rest_framework import viewsets, status\nfrom api_v1.serializers import UserSerializer, UserRegisterSerializer, RegistrationTokenSerializer, AuthTokenSerializer, \\\n ProductSerializer, ProductPhotoSerializer, OrderSerializer, CategorySerializer\nfrom rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser\nfrom django.contrib.auth.models import User\nfrom rest_framework.generics import CreateAPIView, GenericAPIView\nfrom rest_framework.authtoken.views import ObtainAuthToken, APIView\nfrom rest_framework.response import Response\nfrom rest_framework.authtoken.models import Token\n\n\n\n\nclass LoginView(ObtainAuthToken):\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data,\n context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n token, created = Token.objects.get_or_create(user=user)\n return Response({\n 'token': token.key,\n 'user_id': user.id,\n 'username': user.username,\n 'is_admin': user.is_superuser,\n 'is_staff': user.is_staff\n })\n\n\nclass TokenLoginView(APIView):\n serializer_class = AuthTokenSerializer\n\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data, context={'request': request})\n serializer.is_valid(raise_exception=True)\n token = serializer.validated_data['token']\n user = token.user\n return Response({\n 'token': token.key,\n 'user_id': user.id,\n 'username': user.username,\n 'is_admin': user.is_superuser,\n 'is_staff': user.is_staff\n })\n\n\nclass BaseViewSet(viewsets.ModelViewSet):\n def get_permissions(self):\n permissions = super().get_permissions()\n if self.request.method in [\"POST\", \"DELETE\", \"PUT\", \"PATCH\"]:\n permissions.append(IsAuthenticated()),\n permissions.append(IsAdminUser())\n return permissions\n\n\n\n\nclass UserCreateView(CreateAPIView):\n model = User\n serializer_class = UserRegisterSerializer\n permission_classes = [AllowAny]\n\n def perform_create(self, serializer):\n user = serializer.save()\n token = self.create_token(user)\n self.send_registration_email(user, token)\n\n def create_token(self, user):\n return RegistrationToken.objects.create(user=user)\n\n def send_registration_email(self, user, token):\n url = '%s/register/activate/?token=%s' % (settings.HOST_URL, token)\n email_text = \"Your account was successfully created.\\nPlease, follow the link to activate:\\n\\n%s\" % url\n user.email_user(\"Registration at Cinema-App\", email_text, settings.EMAIL_DEFAULT_FROM)\n\n\nclass UserActivateView(GenericAPIView):\n serializer_class = RegistrationTokenSerializer\n\n def post(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = self.perform_user_activation(serializer)\n auth_token, _ = Token.objects.get_or_create(user=user)\n return Response({\n 'token': auth_token.key,\n 'user_id': user.id,\n 'username': user.username,\n 'is_admin': user.is_superuser,\n 'is_staff': user.is_staff\n })\n\n def perform_user_activation(self, serializer):\n token = serializer.validated_data.get('token')\n user = token.user\n user.is_active = True\n user.save()\n token.delete()\n return user\n\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n serializer_class = UserSerializer\n queryset = User.objects.all()\n\n def get_permissions(self):\n permissions = super().get_permissions()\n if self.request.method in [\"POST\", \"DELETE\", \"PUT\", \"PATCH\"]:\n permissions.append(IsAuthenticated())\n return permissions\n\n def check_object_permissions(self, request, obj):\n super().check_object_permissions(request, obj)\n print(obj, request.user, '===')\n if request.method in ['PUT', 'PATCH', 'DELETE'] and obj != request.user:\n self.permission_denied(request, 'Can not edit other users data!')\n\nclass ProductViewSet(BaseViewSet):\n queryset = Product.objects.active().order_by('-date')\n serializer_class = ProductSerializer\n\n def perform_destroy(self, instance):\n instance.is_deleted = True\n instance.save()\n\n\nclass ProductPhotoViewSet(BaseViewSet):\n queryset = ProductPhoto.objects.active()\n serializer_class = ProductPhotoSerializer\n\n def perform_destroy(self, instance):\n instance.is_deleted = True\n instance.save()\n\nclass OrderViewSet(BaseViewSet):\n queryset = Order.objects.active()\n serializer_class = OrderSerializer\n\n def perform_destroy(self, instance):\n instance.is_deleted = True\n instance.save()\n\n\nclass UserCreateView(CreateAPIView):\n model = User\n serializer_class = UserRegisterSerializer\n permission_classes = [AllowAny]\n\n def perform_create(self, serializer):\n user = serializer.save()\n token = self.create_token()\n self.send_registration_email(user, token)\n\n def create_token(self):\n return RegistrationToken.objects.create(user=user)\n\n def send_registration_email(self, user, token):\n url = '%s/register/activate/?token=%s' % (settings.HOST_URL, token)\n email_text = \"Your account was successfully created.\\nPlease, follow the link to activate:\\n\\n%s\" % url\n user.email_user(\"Registration at Cinema-App\", email_text, settings.EMAIL_DEFAULT_FROM)\n\n\nclass CategoryViewSet(BaseViewSet):\n queryset = Category.objects.active().order_by('-name')\n serializer_class = CategorySerializer\n\n def perform_destroy(self, instance):\n instance.is_deleted = True\n instance.save()\n","repo_name":"kadyrkulove/python_group_1_exam_9_ermek_kadyrkulov","sub_path":"exam9/api_v1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39302459819","text":"# the body control module is a intergration module of DCU(drive control unit)\n# and steering control unit, which get the throttle and steering angle instruction\n# from CAN BUS and transfer these instruction of electrical signal to control\n# throttle percentage and pressure of steering pump\n\nfrom socket import *\n# child process\nimport multiprocessing\n# transfer dictionary using json\nimport json\nimport can\n\n# child process function to listen message on CANBUS, once it get message, send\n# data to parent process through pipe\ndef CANBUS_connection(conn):\n channel = 'vcan0'\n bustype = 'socketcan'\n bus = can.interface.Bus(channel=channel, bustype=bustype)\n print(\"CANBUS CONNECTION SUCCESS\")\n\n while True:\n message = bus.recv()\n # throttle data from CANBUS\n if message.arbitration_id==0x6ce:\n print(\"get throttle data from CANBUS\")\n throttle = 0\n for i in range(8):\n throttle += message.data[i]*10**(-i)\n m_dict['throttle'] = throttle-1\n print(throttle)\n conn.send(1)\n continue\n # steering angle data from CANBUS\n if message.arbitration_id==0x6ca:\n print(\"get steering angle data from CANBUS\")\n steering_angle = 0\n for i in range(8):\n steering_angle += message.data[i]*10**(-i)\n m_dict['steering_angle'] = steering_angle-1\n print(steering_angle)\n conn.send(1)\n continue\n\n\n\nif __name__ == '__main__':\n manager = multiprocessing.Manager()\n m_dict = manager.dict()\n m_dict['throttle'] = 0\n m_dict['steering_angle'] = 0\n parent_conn, child_conn = multiprocessing.Pipe()\n # create a child process to listen message from CANBUS\n p = multiprocessing.Process(target=CANBUS_connection, args=(child_conn, ))\n p.start()\n\n # initial connection between body control module to mechanism module to simulate\n # the hard instruction wire connecting body control to throttle motor, steering pump\n HOST = '10.183.27.73'\n PORT = 12345\n BUFSIZ =40960\n ADDR = (HOST,PORT)\n\n tcpCliSock = socket(AF_INET,SOCK_STREAM)\n tcpCliSock.connect(ADDR)\n print(\"MECHANISM CONNECTION SUCCESS\")\n\n while True:\n # asyn\n data = parent_conn.recv()\n # treat throttle and steering_angle instruction\n throttle = m_dict['throttle']\n steering_angle = m_dict['steering_angle']\n dict = {\"steering_angle\":steering_angle, \"throttle\":throttle}\n data = json.dumps(dict)\n print(data)\n tcpCliSock.send(data.encode())\n","repo_name":"Oakwoo/Car_simulater","sub_path":"body_control.py","file_name":"body_control.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1428887269","text":"#!/usr/bin/env python3\n\nimport rclpy\nfrom rclpy.node import Node \nfrom example_interfaces.msg import String\n\nclass new_server(Node):\n\n def __init__(self,node_name):\n super().__init__(node_name)\n self.get_logger().info(\"receiver_node has started\")\n self.obj_sub=self.create_subscription(String,\"topic\",self.call_back_subscription,10)\n\n\n\n def call_back_subscription(self,msg):\n self.get_logger().info(\"i head : \" + msg.data)\n\n\n\ndef main (args=None):\n rclpy.init(args = args)\n node=new_server(\"receiver_node\")\n\n rclpy.spin(node)\n\n rclpy.shutdown() \n\nif __name__==\"__main__\":\n main()","repo_name":"Alihamdy2496/ITI_intensive_course_Low_speed_self_driving_vehicles_track","sub_path":"ROS_LABS/iti_lab_8/iti_lab_8/receiver_node.py","file_name":"receiver_node.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10295901893","text":"# coding: utf-8\n# Author: Leo BRUNEL\n# Contact: contact@leobrunel.com\n\n# Python modules\nfrom PyQt5 import QtWidgets, QtCore, QtGui\nimport logging\n\n# Wizard modules\nfrom wizard.core import project\nfrom wizard.core import assets\nfrom wizard.vars import assets_vars\nfrom wizard.vars import ressources\n\n# Wizard gui modules\nfrom wizard.gui import gui_utils\n\nlogger = logging.getLogger(__name__)\n\nclass video_settings_widget(QtWidgets.QDialog):\n def __init__(self, work_env_id, parent=None):\n super(video_settings_widget, self).__init__()\n\n self.setWindowIcon(QtGui.QIcon(ressources._wizard_ico_))\n self.setWindowTitle(f\"Wizard - Video settings\")\n\n self.work_env_id = work_env_id\n\n self.build_ui()\n self.get_frames()\n self.fill_ui()\n self.connect_functions()\n self.refresh()\n self.cam_list_changed()\n\n def apply(self):\n self.frange = [self.inrollframe_spinBox.value(), self.outrollframe_spinBox.value()]\n self.refresh_assets = self.refresh_assets_checkbox.isChecked()\n self.nspace_list = self.get_selected_nspaces()\n self.comment = self.comment_textEdit.toPlainText()\n self.accept()\n\n def get_selected_nspaces(self):\n selected_nspaces = []\n for item in self.assets_list.selectedItems():\n selected_nspaces.append(item.text())\n return selected_nspaces\n\n def get_frames(self):\n asset_row = assets.get_asset_data_from_work_env_id(self.work_env_id)\n self.preroll = asset_row['preroll']\n self.postroll = asset_row['postroll']\n\n def connect_functions(self):\n self.inframe_spinBox.valueChanged.connect(self.refresh)\n self.outframe_spinBox.valueChanged.connect(self.refresh)\n self.rolls_checkbox.stateChanged.connect(self.refresh)\n self.batch_button.clicked.connect(self.apply)\n self.reject_button.clicked.connect(self.reject)\n self.assets_list.itemSelectionChanged.connect(self.cam_list_changed)\n\n def cam_list_changed(self):\n selected_nspaces = self.get_selected_nspaces()\n if len(selected_nspaces) == 0:\n text = \"Warning, if you don't select at least one camera, the video will be created with the default camera, you may want to select a camera.\"\n elif len(selected_nspaces) > 1:\n text = \"Warning, if you select multiple cameras, wizard will create a video for each selected camera.\"\n else:\n text = ''\n self.warning_label.setText(text)\n\n def fill_ui(self):\n self.video_icon_label.setPixmap(QtGui.QIcon(ressources._videos_icon_).pixmap(22))\n self.header_text.setText(f\"Please set the video settings\")\n\n asset_row = assets.get_asset_data_from_work_env_id(self.work_env_id)\n self.inframe_spinBox.setValue(asset_row['inframe'])\n self.outframe_spinBox.setValue(asset_row['outframe'])\n\n references = []\n all_references = assets.get_references_files(self.work_env_id)\n for stage in all_references.keys():\n if stage in ['camrig', 'camera']:\n for reference_row in all_references[stage]:\n item = QtWidgets.QListWidgetItem(QtGui.QIcon(ressources._stage_icons_dic_[stage]),\n reference_row['namespace'])\n self.assets_list.addItem(item)\n\n def refresh(self):\n inrollframe = self.inframe_spinBox.value()\n outrollframe = self.outframe_spinBox.value()\n if self.rolls_checkbox.isChecked():\n inrollframe = inrollframe-self.preroll\n outrollframe = outrollframe-self.postroll\n self.inrollframe_spinBox.setValue(inrollframe)\n self.outrollframe_spinBox.setValue(outrollframe)\n\n def build_ui(self):\n self.setMinimumWidth(400)\n self.main_layout = QtWidgets.QVBoxLayout()\n self.main_layout.setSpacing(12)\n self.setLayout(self.main_layout)\n\n self.header_widget = QtWidgets.QWidget()\n self.header_widget.setObjectName('transparent_widget')\n self.header_layout = QtWidgets.QHBoxLayout()\n self.header_layout.setContentsMargins(0,0,0,0)\n self.header_layout.setSpacing(8)\n self.header_widget.setLayout(self.header_layout)\n self.main_layout.addWidget(self.header_widget)\n\n self.video_icon_label = QtWidgets.QLabel()\n self.header_layout.addWidget(self.video_icon_label)\n\n self.header_text = QtWidgets.QLabel()\n self.header_layout.addWidget(self.header_text)\n\n self.header_layout.addSpacerItem(QtWidgets.QSpacerItem(0,0,QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed))\n\n # Refresh assets section\n\n self.refresh_assets_label = QtWidgets.QLabel('References settings')\n self.refresh_assets_label.setObjectName('gray_label')\n self.main_layout.addWidget(self.refresh_assets_label)\n \n self.refresh_assets_checkbox = QtWidgets.QCheckBox('Refresh assets in scene')\n self.refresh_assets_checkbox.setObjectName('transparent_widget')\n self.main_layout.addWidget(self.refresh_assets_checkbox)\n\n # Frame range section\n\n self.range_setup_widget = QtWidgets.QWidget()\n self.range_setup_widget.setObjectName('transparent_widget')\n self.range_setup_layout = QtWidgets.QVBoxLayout()\n self.range_setup_layout.setContentsMargins(0,0,0,0)\n self.range_setup_layout.setSpacing(8)\n self.range_setup_widget.setLayout(self.range_setup_layout)\n self.main_layout.addWidget(self.range_setup_widget)\n\n self.frame_range_label = QtWidgets.QLabel('Frame range')\n self.frame_range_label.setObjectName('gray_label')\n self.range_setup_layout.addWidget(self.frame_range_label)\n\n self.rolls_checkbox = QtWidgets.QCheckBox('Create video with prerolls and postrolls')\n self.rolls_checkbox.setObjectName('transparent_widget')\n self.range_setup_layout.addWidget(self.rolls_checkbox)\n self.range_widget = QtWidgets.QWidget()\n self.range_widget.setObjectName('transparent_widget')\n self.range_layout = QtWidgets.QHBoxLayout()\n self.range_layout.setContentsMargins(0,0,0,0)\n self.range_layout.setSpacing(8)\n self.range_widget.setLayout(self.range_layout)\n self.range_setup_layout.addWidget(self.range_widget)\n\n self.inrollframe_spinBox = QtWidgets.QSpinBox()\n self.inrollframe_spinBox.setEnabled(False)\n self.inrollframe_spinBox.setObjectName('gray_label')\n self.inrollframe_spinBox.setRange(-1000000, 1000000)\n self.inrollframe_spinBox.setButtonSymbols(2)\n self.range_layout.addWidget(self.inrollframe_spinBox)\n\n self.inframe_spinBox = QtWidgets.QSpinBox()\n self.inframe_spinBox.setRange(-1000000, 1000000)\n self.inframe_spinBox.setButtonSymbols(2)\n self.range_layout.addWidget(self.inframe_spinBox)\n\n self.outframe_spinBox = QtWidgets.QSpinBox()\n self.outframe_spinBox.setRange(-1000000, 1000000)\n self.outframe_spinBox.setButtonSymbols(2)\n self.range_layout.addWidget(self.outframe_spinBox)\n\n self.outrollframe_spinBox = QtWidgets.QSpinBox()\n self.outrollframe_spinBox.setEnabled(False)\n self.outrollframe_spinBox.setObjectName('gray_label')\n self.outrollframe_spinBox.setRange(-1000000, 1000000)\n self.outrollframe_spinBox.setButtonSymbols(2)\n self.range_layout.addWidget(self.outrollframe_spinBox)\n\n # Camera namespaces selection section\n\n self.nspace_list_widget = QtWidgets.QWidget()\n self.nspace_list_widget.setObjectName('transparent_widget')\n self.nspace_list_layout = QtWidgets.QVBoxLayout()\n self.nspace_list_layout.setContentsMargins(0,0,0,0)\n self.nspace_list_layout.setSpacing(8)\n self.nspace_list_widget.setLayout(self.nspace_list_layout)\n self.main_layout.addWidget(self.nspace_list_widget)\n\n self.infos_label = QtWidgets.QLabel('Select the camera(s)')\n self.infos_label.setObjectName('gray_label')\n self.nspace_list_layout.addWidget(self.infos_label)\n\n self.assets_list = QtWidgets.QListWidget()\n self.assets_list.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)\n self.nspace_list_layout.addWidget(self.assets_list)\n\n self.warning_label = QtWidgets.QLabel('')\n self.warning_label.setWordWrap(True)\n self.warning_label.setStyleSheet('color:#ffad4d;')\n self.nspace_list_layout.addWidget(self.warning_label)\n\n # Comment section\n\n self.comment_textEdit = QtWidgets.QTextEdit('')\n self.comment_textEdit.setPlaceholderText(\"Your comment\")\n self.main_layout.addWidget(self.comment_textEdit)\n\n # Buttons sections\n\n self.buttons_widget = QtWidgets.QWidget()\n self.buttons_widget.setObjectName('transparent_widget')\n self.buttons_layout = QtWidgets.QHBoxLayout()\n self.buttons_layout.setContentsMargins(0,0,0,0)\n self.buttons_layout.setSpacing(4)\n self.buttons_widget.setLayout(self.buttons_layout)\n self.main_layout.addWidget(self.buttons_widget)\n\n self.buttons_layout.addSpacerItem(QtWidgets.QSpacerItem(0,0,QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed))\n\n self.reject_button = QtWidgets.QPushButton('Cancel')\n self.reject_button.setDefault(False)\n self.reject_button.setAutoDefault(False)\n self.buttons_layout.addWidget(self.reject_button)\n\n self.batch_button = QtWidgets.QPushButton('Create video')\n self.batch_button.setObjectName('blue_button')\n self.batch_button.setDefault(True)\n self.batch_button.setAutoDefault(True)\n self.buttons_layout.addWidget(self.batch_button)\n","repo_name":"Wizard-collab/wizard_2","sub_path":"wizard/gui/video_settings_widget.py","file_name":"video_settings_widget.py","file_ext":"py","file_size_in_byte":9809,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"70084368918","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nwith open('requirements.txt') as open_file:\n install_requires = open_file.read()\n\nsetuptools.setup(\n name=\"jOpMRI\",\n version=\"0.0.4\",\n author=\"Chaithya G R\",\n author_email=\"chaithyagr@gmail.com\",\n description=\"Tools to benchmark and jointly optimize sampling and recon networks on the fastMRI dataset\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/chaithyagr/joint_optimization_mri\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=install_requires,\n tests_require=['pytest>=5.0.1', 'pytest-cov>=2.7.1', 'pytest-pep8', 'pytest-runner', 'pytest-xdist'],\n python_requires='>=3.6',\n)\n","repo_name":"CEA-COSMIC/joint_optimization_mri","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"39867510460","text":"from tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom PIL import Image, ImageTk\r\nimport cLogin\r\nimport cIPDataBase\r\n\r\nNUM_PHOTOS=6\r\n\r\nclass PanouControl(tk.Frame):\r\n\r\n def menubar(self, root):\r\n menubar = tk.Menu(root, bd=2)\r\n pageMenu = tk.Menu(menubar, tearoff=0)\r\n menubar.add_cascade(label=\"Meniu\", menu=pageMenu)\r\n pageMenu.add_command(label=\"Selectare algoritm\",command=lambda: root.SettingsPage(0))\r\n pageMenu.add_command(label=\"Securitate\",command=lambda:root.SecurityPage() )\r\n pageMenu.add_separator()\r\n pageMenu.add_cascade(label=\"Exit\", command=quit)\r\n return menubar\r\n\r\n def __init__(self,parent,controller):\r\n '''Ar trebui mutata pe butonul de selectare tip de algoritm'''\r\n tk.Frame.__init__(self, parent)\r\n\r\n #create DB Object\r\n\r\n def info(username):\r\n mydb = cIPDataBase.myDataBase()\r\n print(\"IBAN : %s --- SOLD : %s --- NAME : %s --- EMAIL : %s\" % mydb.showInfo(username))\r\n\r\n def sold(username):\r\n mydb = cIPDataBase.myDataBase()\r\n print(\"SOLD : %s\" % mydb.showSold(username))\r\n\r\n\r\n #buton vezi informatii\r\n imageInfo=PhotoImage(file=\"GUIPhotos/034.png\")\r\n butonVeziInformatii = tk.Button(self,relief=RIDGE,image=imageInfo,anchor=CENTER,compound=CENTER,\r\n cursor=\"hand2\", command=lambda: info(cLogin.LoginFrame.user))\r\n butonVeziInformatii.place(relx=0.1, rely=0.27, height=40, width=266)\r\n butonVeziInformatii.image=imageInfo\r\n\r\n #buton vezi informatii\r\n imageInfo=PhotoImage(file=\"GUIPhotos/037.png\")\r\n butonVeziInformatii = tk.Button(self,relief=RIDGE,image=imageInfo,anchor=CENTER,compound=CENTER,\r\n cursor=\"hand2\", command=lambda: sold(cLogin.LoginFrame.user))\r\n butonVeziInformatii.place(relx=0.1, rely=0.47, height=40, width=240)\r\n butonVeziInformatii.image=imageInfo\r\n\r\n\r\n #buton deschidere bariera\r\n\r\n # imageDeschide=PhotoImage(file=\"GUIPhotos/033.png\")\r\n # butonDeschideBariera=tk.Button(self,relief=RIDGE,image=imageDeschide,\r\n # cursor=\"hand2\",compound=CENTER,anchor=CENTER)\r\n # butonDeschideBariera.place(relx=0.1,rely=0.27,height=30,width=266)\r\n # butonDeschideBariera.image=imageDeschide\r\n #\r\n\r\n #label cu stare curenta\r\n # labelStare = tk.Label(self, text=\"LPR functioneaza normal\", anchor=CENTER,\r\n # bg=\"white\")\r\n # labelStare.place(relx=0.1, rely=0.66, height=30, width=266)\r\n #\r\n\r\n #Afisarea ultimului numar recunoscut\r\n\r\n\r\n","repo_name":"irinacovrescu/ip","sub_path":"cPanouControl.py","file_name":"cPanouControl.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21564368483","text":"# dp\nimport sys\nsys.stdin = open('input.txt')\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n M = 1 << N # 2^N\n dp = [[0.0 for _ in range(M)] for _ in range(N)]\n G = []\n for i in range(N):\n G.append(list(map(float, input().split())))\n for j in range(N):\n G[i][j] = G[i][j] / 100\n\n for i in range(N):\n dp[0][1 << i] = G[0][i]\n\n for i in range(1, N):\n for cur in range(1, M):\n if dp[i-1][cur] == 0:\n continue\n\n for j in range(N):\n if cur & (1 << j) != 0 or G[i][j] == 0:\n continue\n next = cur | (1 << j)\n\n dp[i][next] = max(dp[i][next], dp[i-1][cur] * G[i][j])\n\n print('#{} {:.6f}'.format(tc, dp[N-1][M-1] * 100))","repo_name":"SPlCYWOLF/algorithm-practices","sub_path":"python/SWEA/211219/1007_review/1865_동철이의일분배/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18626043818","text":"# CENG 487 Assignment7 by\n# Gazi Özgen\n# StudentId: 250201051\n# 1 2022\n\nimport random\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom PIL import Image\n\nimport matrix\nfrom boundingbox import *\nfrom defs import DrawStyle\n\n__all__ = ['_Shape', 'DrawStyle']\n\n\nclass _Shape:\n def __init__(self, name, vertices, faces, normals, tex_coordinates, shader):\n self.position = Point3f(0, 0, 0)\n self.vertices = vertices\n # self.edges = []\n self.faces = faces\n self.normals = normals\n self.tex_coordinates = tex_coordinates\n self.colors = []\n self.obj2World = Matrix()\n self.drawStyle = DrawStyle.NODRAW\n self.wireOnShaded = False\n self.wireWidth = 2\n self.name = name\n self.fixedDrawStyle = False\n self.wireColor = ColorRGBA(0.7, 1.0, 0.0, 1.0)\n self.wireOnShadedColor = ColorRGBA(1.0, 1.0, 1.0, 1.0)\n self.bboxObj = BoundingBox()\n self.bboxWorld = BoundingBox()\n self.calcBboxObj()\n self.VBO = -1\n self.VAO = -1\n self.VBOData = None\n self.programID = -1\n self.vertexDim = 4\n self.nVertices = len(faces) * self.vertexDim\n self.tex1ID = -1\n self.tex2ID = -1\n self.initColors()\n self.init(shader)\n\n def initColors(self):\n for i in range(0, len(self.faces) + 1):\n r = random.uniform(0, 1)\n g = random.uniform(0, 1)\n b = random.uniform(0, 1)\n self.colors.append(ColorRGBA(1, 1, 1, 1.0))\n\n def calcBboxObj(self):\n for vertex in self.vertices:\n self.bboxObj.expand(vertex)\n\n def setDrawStyle(self, style):\n self.drawStyle = style\n\n def setWireColor(self, r, g, b, a):\n self.wireColor = ColorRGBA(r, g, b, a)\n\n def setWireWidth(self, width):\n self.wireWidth = width\n\n def Translate(self, x, y, z):\n self.position += Point3f(x, y, z)\n\n # Function that accepts a list of shaders, compiles them, and returns a handle to the compiled program\n def createProgram(self, shaderList):\n programID = glCreateProgram()\n\n for shader in shaderList:\n glAttachShader(programID, shader)\n\n glLinkProgram(programID)\n\n status = glGetProgramiv(programID, GL_LINK_STATUS)\n if status == GL_FALSE:\n strInfoLog = glGetProgramInfoLog(programID)\n print(b\"Linker failure: \\n\" + strInfoLog)\n\n # important for cleanup\n for shaderID in shaderList:\n glDetachShader(programID, shaderID)\n\n return programID\n\n # Function that creates and compiles shaders according to the given type (a GL enum value) and\n # shader program (a string containing a GLSL program).\n def createShader(self, shaderType, shaderCode):\n shaderID = glCreateShader(shaderType)\n glShaderSource(shaderID, shaderCode)\n glCompileShader(shaderID)\n\n status = None\n glGetShaderiv(shaderID, GL_COMPILE_STATUS, status)\n if status == GL_FALSE:\n # Note that getting the error log is much simpler in Python than in C/C++\n # and does not require explicit handling of the string buffer\n strInfoLog = glGetShaderInfoLog(shaderID)\n strShaderType = \"\"\n if shaderType is GL_VERTEX_SHADER:\n strShaderType = \"vertex\"\n elif shaderType is GL_GEOMETRY_SHADER:\n strShaderType = \"geometry\"\n elif shaderType is GL_FRAGMENT_SHADER:\n strShaderType = \"fragment\"\n\n print(b\"Compilation failure for \" + strShaderType + b\" shader:\\n\" + strInfoLog)\n\n return shaderID\n\n # Set up the list of shaders, and call functions to compile them\n def initProgram(self, shader):\n shaderList = []\n\n shaderList.append(self.createShader(GL_VERTEX_SHADER, shader.vertexShader))\n shaderList.append(self.createShader(GL_FRAGMENT_SHADER, shader.fragmentShader))\n\n self.programID = self.createProgram(shaderList)\n\n for shader in shaderList:\n glDeleteShader(shader)\n\n # Initialize the OpenGL environment\n def init(self, shader):\n self.initProgram(shader)\n self.initVertexBufferData()\n self.initVertexBuffer()\n self.initTextures(\"textures/texture1.png\", \"textures/texture2.png\")\n\n def initVertexBufferData(self):\n\n finalVertexPositions = []\n finalVertexColors = []\n finalVertexUvs = []\n finalVertexNormals = []\n\n # go over faces and assemble an array for all vertex data\n for face in self.faces:\n for i in range(len(face)):\n finalVertexPositions.extend(self.vertices[face[i][0]].toArray())\n finalVertexColors.extend(self.colors[i].toArray())\n finalVertexUvs.extend(self.tex_coordinates[face[i][1]])\n finalVertexNormals.extend(self.normals[face[i][2]].toArray())\n\n self.VBOData = numpy.array(finalVertexPositions + finalVertexColors + finalVertexUvs + finalVertexNormals,\n dtype='float32')\n\n # Set up the vertex buffer that will store our vertex coordinates for OpenGL's access\n def initVertexBuffer(self):\n self.VAO = glGenVertexArrays(1)\n self.VBO = glGenBuffers(1)\n\n # bind to our VAO\n glBindVertexArray(self.VAO)\n\n # now change the state - it will be recorded in the VAO\n # set array buffer to our ID\n glBindBuffer(GL_ARRAY_BUFFER, self.VBO)\n\n # set data\n elementSize = numpy.dtype(numpy.float32).itemsize\n\n # third argument is criptic - in c_types if you multiply a data type with an integer you create an array of that type\n glBufferData(GL_ARRAY_BUFFER,\n len(self.VBOData) * elementSize,\n self.VBOData,\n GL_STATIC_DRAW\n )\n\n # setup vertex attributes\n offset = 0\n\n # location 0\n glVertexAttribPointer(0, self.vertexDim, GL_FLOAT, GL_FALSE, elementSize * self.vertexDim,\n ctypes.c_void_p(offset))\n glEnableVertexAttribArray(0)\n\n # define colors which are passed in location 1 - they start after all positions and has four floats consecutively\n offset += elementSize * self.vertexDim * self.nVertices\n glVertexAttribPointer(1, self.vertexDim, GL_FLOAT, GL_FALSE, elementSize * self.vertexDim,\n ctypes.c_void_p(offset))\n glEnableVertexAttribArray(1)\n\n # define uvs which are passed in location 2 - they start after all positions and colors and has two floats per vertex\n offset += elementSize * self.vertexDim * self.nVertices\n glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, elementSize * 2, ctypes.c_void_p(offset))\n glEnableVertexAttribArray(2)\n\n # define normals which are passed in location 3 - they start after all positions, colors and uvs and has four floats per vertex\n offset += elementSize * 2 * self.nVertices\n glVertexAttribPointer(3, self.vertexDim, GL_FLOAT, GL_FALSE, elementSize * self.vertexDim, ctypes.c_void_p(offset))\n glEnableVertexAttribArray(3)\n\n # reset array buffers\n glBindBuffer(GL_ARRAY_BUFFER, 0)\n glBindVertexArray(0)\n\n # texture stuff\n def initTextures(self, texFilename1, texFilename2):\n # we need to bind to the program to set texture related params\n glUseProgram(self.programID)\n\n self.tex1ID = self.loadTexture(texFilename1)\n self.tex2ID = self.loadTexture(texFilename2)\n\n # set shader stuff\n tex1Location = glGetUniformLocation(self.programID, \"tex1\")\n glUniform1i(tex1Location, self.tex1ID)\n\n tex2Location = glGetUniformLocation(self.programID, \"tex2\")\n glUniform1i(tex2Location, self.tex2ID)\n\n # now activate texture units\n glActiveTexture(GL_TEXTURE0 + self.tex1ID)\n glBindTexture(GL_TEXTURE_2D, self.tex1ID)\n\n glActiveTexture(GL_TEXTURE0 + self.tex2ID)\n glBindTexture(GL_TEXTURE_2D, self.tex2ID)\n\n ratioLocation = glGetUniformLocation(self.programID, \"ratio\")\n glUniform1f(ratioLocation, 0)\n\n glUseProgram(0)\n\n def loadTexture(self, texFilename):\n # load texture - flip int verticallt to convert from pillow to OpenGL orientation\n image = Image.open(texFilename).transpose(Image.FLIP_TOP_BOTTOM)\n\n # create a new id\n texID = glGenTextures(1)\n # bind to the new id for state\n glBindTexture(GL_TEXTURE_2D, texID)\n\n # set texture params\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER)\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n\n # copy texture data\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.size[0], image.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE,\n numpy.frombuffer(image.tobytes(), dtype=numpy.uint8))\n glGenerateMipmap(GL_TEXTURE_2D)\n\n return texID\n\n def draw(self, camera):\n # use our program\n programID = self.programID\n glUseProgram(programID)\n\n viewPosition = glGetUniformLocation(programID, \"viewPosition\")\n glUniform3f(viewPosition, camera.center.x, camera.center.y, camera.center.z)\n\n # get matrices and bind them to vertex shader locations\n modelLocation = glGetUniformLocation(programID, \"model\")\n glUniformMatrix4fv(modelLocation, 1, GL_FALSE, matrix.Matrix.getModelMatrix(self.position))\n viewLocation = glGetUniformLocation(programID, \"view\")\n glUniformMatrix4fv(viewLocation, 1, GL_FALSE, matrix.Matrix.getViewMatrix(camera))\n projLocation = glGetUniformLocation(programID, \"proj\")\n glUniformMatrix4fv(projLocation, 1, GL_FALSE,\n matrix.Matrix.getProjMatrix(camera.near, camera.far, camera.aspect, camera.fov))\n\n # bind to our VAO\n glBindVertexArray(self.VAO)\n\n # draw stuff\n glDrawArrays(GL_QUADS, 0, self.nVertices)\n\n # reset to defaults\n glBindVertexArray(0)\n glUseProgram(0)\n","repo_name":"gaziozgen/Lightning-and-texture-in-core-profile-mode-of-OpenGL","sub_path":"shapes.py","file_name":"shapes.py","file_ext":"py","file_size_in_byte":10319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10379563677","text":"\"\"\" \nAuthor: Aarya\nDescription: Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray\n whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.\nTime Complexity: O(n), where n is the size of the nums list\nSpace Complexity: O(1), The algorithm uses a few variables that don't grow with the input\n\"\"\"\nclass Solution:\n def minSubArrayLen(self, target: int, nums: List[int]) -> int:\n \"\"\"\n Initialize output as the length of the nums + 1, as that can never be the length of a subarray for the nums list\n This information will be used at the end to return the output or 0\n \"\"\"\n output = len(nums) + 1\n # Initialize a left pointer at the start of the nums list\n l = 0\n # Initialize current_sum as 0\n current_sum = 0\n # loop through the nums list using a right pointer\n for r in range(len(nums)):\n # Add the current value at the right pointer to the current sum\n current_sum += nums[r]\n \"\"\"\n While the current_sum is greater than or equal to the target value, then:\n Update the output value to be smaller of current length of the window or the output itself\n (r - l + 1) is used to find the length of the current window\n Subtract the value at the left pointer from the current sum\n Increment the left pointer\n \"\"\"\n while current_sum >= target:\n output = min(output, r - l + 1)\n current_sum -= nums[l]\n l += 1\n # Return 0 if the output is the same length as when it was initialized, else return the value of the output\n return 0 if output == len(nums) + 1 else output","repo_name":"ViperFangs/LeetCode","sub_path":"209_minimum_size_subarray_sum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32744914842","text":"import numpy as np\nfrom LoRa import LoRa\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.preprocessing import minmax_scale\n# from scipy.fftpack import fft\nfrom matplotlib.font_manager import FontProperties\nfrom cmath import phase\n\nfont = FontProperties()\nfont.set_size(20)\nfont.set_name('Times New Roman')\nfont.set_weight('regular')\n\n# Generate FFT bins\nsf = 7\nlora_bw = 125e3\ndecim_factor = 1\n\nlora = LoRa(sf)\n\nlora_symbol = [124]\nchirp_cnt = len(lora_symbol)\nlora_samples = lora.mod(lora_symbol)\nlora_phases = []\nlora_freqs = []\nlora_avg_freqs = []\nlora_binarys = []\nlora_avg_binarys = []\nnoise = np.random.normal(0, 0.15, (2, lora.mod_len))\n# lora_samples = np.add(lora_samples, noise)\n\nlora_result, lora_fft, lora_multi = lora.de_mod(lora_samples)\n\nlora_mean = np.mean(lora_fft)\nlora_var = np.var(lora_fft)\n\nlora_fft = np.divide(np.subtract(lora_fft, lora_mean), lora_var)\n\nfor i in range(chirp_cnt):\n lora_phases.append([phase(sample) for sample in lora_samples[i]])\n\n lora_freqs.append(lora.get_freq(lora_samples, i))\n lora_freqs[i].append(0) # append 0 as freqs are calculated from adjacent samples\n\n # index = (1 << sf) - lora_symbol[i] - 1\n # lora_freqs[i][index+1] = 0.0545\n # lora_freqs[i].append(lora_freqs[i][-1])\n # tmp = lora_freqs[i][index-1]\n # lora_freqs[i][index-1] = lora_freqs[i][index]\n # lora_freqs[i][index] = tmp\n\n lora.show_samples(lora_phases, i)\n lora.show_samples(lora_freqs, i)\n lora.show_samples(lora_fft, i)\n\nfor i in range(chirp_cnt):\n if decim_factor == 1:\n break\n\n lora_avg_freq = []\n for j in range((1 << sf) // decim_factor):\n lora_avg_freq.append((lora_freqs[i][decim_factor*j]+lora_freqs[i][decim_factor*j+1])/2)\n lora_avg_freqs.append(lora_avg_freq)\n\n# plot phase shift + binary\n# for i in range(chirp_cnt):\n# lora_binary = [1 if j > 0 else 0 for j in lora_freqs[i]]\n# lora_binarys.append(lora_binary)\n#\n# lora_avg_binary = [1 if j > 0 else 0 for j in lora_avg_freqs[i]]\n# lora_avg_binarys.append(lora_avg_binary)\n#\n# fig = plt.figure(figsize=(4, 2))\n# axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])\n# x = [j for j in range(len(lora_freqs[i]))]\n# axes.plot(x, lora_freqs[i], '.', color='#000000', linewidth=0.5)\n# x_tick = (1 << (sf - 2))\n# axes.set_xlabel('Index', fontproperties=font)\n# axes.set_xticks([tmp for tmp in range(0, (1 << sf) + x_tick, x_tick)])\n# axes.set_xticklabels([tmp for tmp in range(0, (1 << sf) + x_tick, x_tick)], fontproperties=font)\n# axes.set_ylabel('Phase shift', fontproperties=font)\n# axes.set_ylim(-2.2, 2.2)\n# plt.savefig('freq_os_' + str(lora_symbol[i]) + '.svg', bbox_inches='tight', format='svg')\n#\n# fig = plt.figure(figsize=(4, 2))\n# axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])\n# x = [j for j in range(len(lora_binarys[i]))]\n# axes.plot(x, lora_binarys[i], '.', color='#000000', linewidth=0.5)\n# axes.set_xlabel('Index', fontproperties=font)\n# x_tick = (1 << (sf - 2))\n# axes.set_xticks([tmp for tmp in range(0, (1 << sf) + x_tick, x_tick)])\n# axes.set_xticklabels([tmp for tmp in range(0, (1 << sf) + x_tick, x_tick)], fontproperties=font)\n# axes.set_ylabel('Chip value', fontproperties=font)\n# axes.set_yticks([0, 1])\n# axes.set_yticklabels([0, 1])\n# axes.set_yticklabels(['0', '1'], fontproperties=font)\n# plt.savefig('binary_os_' + str(lora_symbol[i]) + '.svg', bbox_inches='tight', format='svg')\n#\n#\n# fig = plt.figure(figsize=(4, 2))\n# axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])\n# x = [j for j in range(len(lora_avg_binarys[i]))]\n# axes.plot(x, lora_avg_binarys[i], '.', color='#000000', linewidth=0.5)\n# axes.set_xlabel('Index', fontproperties=font)\n# x_tick = (1 << (sf - 2)) // decim_factor\n# axes.set_xticks([tmp for tmp in range(0, (1 << sf) // decim_factor + x_tick, x_tick)])\n# axes.set_xticklabels([tmp for tmp in range(0, (1 << sf) // decim_factor + x_tick, x_tick)], fontproperties=font)\n# axes.set_ylabel('Chip value', fontproperties=font)\n# axes.set_yticks([0, 1])\n# axes.set_yticklabels([0, 1])\n# axes.set_yticklabels(['0', '1'], fontproperties=font)\n# plt.savefig('binary_avg_os_' + str(lora_symbol[i]) + '.svg', bbox_inches='tight', format='svg')","repo_name":"wwwzrb/ligbee-artifact","sub_path":"ligbee-usrp/gr-lobee-encoder/analysis/PlotOversample.py","file_name":"PlotOversample.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"75134250196","text":"from tkinter import *\n# check\n\nwindow = Tk()\nwindow.title(\"Mile to KM converter\")\nwindow.minsize(width=500, height=500)\nwindow.config(padx=20, pady=20) # adds space around edges\n\n\nmiles_input = Entry(width=10)\nmiles_input.grid(column=1, row=0)\n\nmiles_label = Label()\nmiles_label.config(text=\"Miles\", padx=10, pady=10)\nmiles_label.grid(column=2, row=0)\n\ntext_l = Label()\ntext_l.config(text=\"is equal to\", padx=10, pady=10)\ntext_l.grid(column=0, row=1)\n\nresult_l = Label()\nresult_l.config(text=\"\", padx=10, pady=10)\nresult_l.grid(column=1, row=1)\n\nkm_l = Label()\nkm_l.config(text=\"Km\", padx=10, pady=10)\nkm_l.grid(column=2, row=1)\n\n\ndef calculate_clicked():\n # Converts miles to KM\n miles = miles_input.get()\n km = float(miles)*1.609344\n result_l.config(text=f\"{km}\")\n\n\ncalculate_button = Button(text=\"Calculate\", command=calculate_clicked)\ncalculate_button.grid(column=2, row=3)\n\nwindow.mainloop()\n","repo_name":"UlianaO/100Days-Of-Code-Python","sub_path":"converter-tkinter/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38686369024","text":"#Fitting The Array\r\ndef fit(a,b):\r\n t=0\r\n a.sort()\r\n b.sort()\r\n for i in range(len(a)):\r\n for j in range(len(b)):\r\n if a[i]>b[i]:\r\n t=0\r\n break\r\n else:\r\n t=1\r\n break\r\n if t:\r\n print('YES')\r\n else:\r\n print('NO')\r\nn=int(input(\"Size: \"))\r\nm=int(input(\"Size: \"))\r\narr=[]\r\nbrr=[]\r\nfor i in range(n):\r\n arr.append(int(input(\"Value: \")))\r\nfor j in range(m):\r\n brr.append(int(input(\"Value: \")))\r\nans=fit(arr,brr)\r\n","repo_name":"2Abhi000/-GFG-Practice-logical-thinking-2022","sub_path":"Fitting The Array.py","file_name":"Fitting The Array.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30843515318","text":"from PyQt5 import QtWidgets \nfrom PyQt5.QtWidgets import QApplication, QMainWindow \nimport sys \n\ndef add_label():\n\tprint(\"aboba\")\n\n\n\ndef application():\n\tapp = QApplication(sys.argv)\n\twindow = QMainWindow()\n\twindow.setGeometry(300, 250, 350, 200)\n\twindow.setWindowTitle(\"adc\")\n\taboba = QtWidgets.QLabel(window)\n\taboba.setText(\"ABOBA BLЯ\")\t\n\taboba.move(100, 100,)\n\taboba.adjustSize()\n\tbtn = QtWidgets.QPushButton\n\tbtn.move(70, 150)\n\tbtn.setText(\"ASS\")\n\tbtn.setFixedWidth(200)\n\tbtn.clicked.connect(add_label)\n\n\n\twindow.show()\n\tsys.exit(app.exec_())\nif __name__ == \"__QT__\":\n application() \n\n\n\n\n\n\n","repo_name":"Pavlentiy-Coderskiy/Python","sub_path":"QT.py","file_name":"QT.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4422655351","text":"import sqlite3\n\ndef create_table(db, create_table_sql):\n try:\n c = db.cursor()\n c.execute(create_table_sql)\n except Error as e:\n print(e)\n\n# Table create statements\nroles = \"\"\"CREATE TABLE IF NOT EXISTS roles (\n role\tTEXT UNIQUE,\n roleid\tINTEGER UNIQUE,\n emoji\tTEXT UNIQUE,\n emojiid\tINTEGER,\n PRIMARY KEY(roleid)\n )\"\"\"\n\nepicGames = \"\"\"CREATE TABLE IF NOT EXISTS epicGames (\n game\tTEXT,\n slug\tTEXT,\n url\tTEXT,\n end_date\tTEXT\n )\"\"\"\n\ndef main():\n con = sqlite3.connect('bot.db')\n create_table(con, roles)\n create_table(con,epicGames)\n\nif __name__ == '__main__':\n main()","repo_name":"BinaryZeph/jerk-bot","sub_path":"setupdb.py","file_name":"setupdb.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41033913122","text":"import rclpy\nfrom rclpy.node import Node\nfrom std_msgs.msg import String\nimport serial\n\n# Serial\nmotor1 = serial.Serial(\"/dev/ttyUSB0\")\nmotor2 = serial.Serial(\"/dev/ttyUSB1\")\n\nclass Control(Node):\n def __init__(self):\n super().__init__(\"killb6_control\")\n \n self.subscription = self.create_subscription(\n String,\n \"motor/motor_speed_rpm\",\n self.listener_callback,\n 10)\n self.subscription # prevent unused variable warning\n\n def listener_callback(self, msg):\n motor1_rpm, motor2_rpm = msg.data.split(\",\")\n\n print(f\"MOTOR 1 RPM: {motor1_rpm}\")\n print(f\"MOTOR 2 RPM: {motor2_rpm}\")\n\n motor1.write(f\"{motor1_rpm}\\n\".encode())\n motor2.write(f\"{motor2_rpm}\\n\".encode())\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n control = Control()\n\n rclpy.spin(control)\n\n control.destroy_node()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()\n","repo_name":"borlum/killb6","sub_path":"killb6/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"1199478522","text":"import pandas as pd\n\ndef cleaning():\n df = pd.read_csv('./data/merged_data.csv')\n\n '''Holds the code to clean and pre-process our scraped data before training our ML model on it.'''\n\n # Filling NaN values with 0.\n df['landplot'] = df['landplot'].fillna(0)\n df['facades'] = df['facades'].fillna(0)\n df['living_area'] = df['living_area'].fillna(0)\n #df = df.fillna(0)\n # Reduces zip codes to 2 digits for broader scope.\n df['zip'] = (df['zip']/100).astype(int)\n\n # Creating dummy columns from categorical data.\n df = pd.get_dummies(df, columns=['building_state', 'province', 'zip', 'subtype'], dtype=int)\n # Removing features that we won't be using.\n df = df.drop(['city', 'kitchen', 'terrace', 'terrace_area', 'type'], axis=1)\n\n # Because 'get_dummies()' creates boolean values, we re-define our dataframe to be integers only.\n df.to_csv('./data/processed_data.csv')\n\ndef cleanup(df, predict):\n df = pd.concat([df, pd.DataFrame(predict, index=[0])],ignore_index=True)\n df = df.fillna(0)\n df = cleaning(df)\n return df\n\ncleaning()","repo_name":"danielbauwens/Airflow-Immo-Project","sub_path":"dags/src/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3618396539","text":"\"\"\"\nURL configuration for salon_project project.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom rest_framework.decorators import api_view\n\n\n@api_view(['GET'])\ndef api_root(request):\n return Response({\n 'Authentication': reverse('generate-otp', request=request),\n 'User': reverse('user', request=request),\n 'Service': reverse('service', request=request),\n 'Subservice': reverse('subservice', request=request),\n 'Slot': reverse('slot', request=request),\n 'Order': reverse('order', request=request),\n })\n\nurlpatterns = [\n path('', api_root),\n path('api/v1/', include('book.urls')),\n path('api/v1/', include('auth_api.urls')),\n path('admin/', admin.site.urls),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"Avnitt/Salon-API","sub_path":"salon_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30977071122","text":"from collections import Counter\nfrom copy import deepcopy\nimport random\n\n\nINIT_HEALTH = 2\n\nCONSTRAINTS = {}\nGRAPH_FUNCTIONS = {}\n\n\ndef rm(d, val):\n if val in d:\n del d[val]\n\n\ndef format_observation(\n self, graph, viewing_agent, action, telling_agent=None, is_constraint=False\n):\n \"\"\"Return the observation text to display for an action\"\"\"\n use_actors = action['actors']\n if is_constraint:\n use_actors = use_actors[1:]\n descs = [\n graph.node_to_desc(a, from_id=action['room_id'], use_the=True)\n for a in use_actors\n ]\n try:\n # Replace viewer with you\n i = use_actors.index(viewing_agent)\n descs[i] = 'you'\n except BaseException:\n pass\n\n if telling_agent is not None:\n try:\n # Replace telling agent with me or I depending\n i = use_actors.index(telling_agent)\n if i == 0:\n descs[0] = 'I'\n else:\n descs[i] = 'me'\n except BaseException:\n pass\n\n # Package descriptions and determine the format\n descs[0] = descs[0].capitalize()\n if 'add_descs' in action:\n descs += action['add_descs']\n if is_constraint:\n descs = [action['actors'][0]] + descs\n return self.get_action_observation_format(action, descs).format(*descs)\n\n\n# Useful constraint sets\ndef is_held_item(item_idx):\n return [\n {'type': 'is_type', 'in_args': [item_idx], 'args': [['object']]},\n {'type': 'no_prop', 'in_args': [item_idx], 'args': ['equipped']},\n ]\n\n\ndef is_equipped_item(item_idx):\n return [\n {'type': 'is_type', 'in_args': [item_idx], 'args': [['object']]},\n {'type': 'has_prop', 'in_args': [item_idx], 'args': ['equipped']},\n ]\n\n\n# Functions\nclass GraphFunction(object):\n \"\"\"Initial description of function should only contain what the arguments\n are as set up by init, establishing a number to type relationship like:\n [Actor, item actor is carrying, container in same room as actor]\n \"\"\"\n\n def __init__(\n self,\n function_name,\n possible_arg_nums,\n arg_split_words,\n arg_find_type,\n arg_constraints,\n func_constraints,\n callback_triggers,\n ):\n \"\"\"Create a new graph function\n args:\n function name - name or array of aliases for the function\n possible_arg_nums - number or array of valid arg numbers for\n determining if given args are valid or for breaking text into\n a valid number of arguments before they're parsed into descs\n arg_split_words - array of words to be used to split input args\n arg_find_type - array of args for desc_to_nodes to use to find the\n argument at the given index, following the form\n {'type': , 'from': }. If a\n list is given for each argument use the same element for each\n arg_constraints - constraints on whether or not found arguments are\n valid to be matched during the parsing step. Form is array of\n arrays of constraint types\n func_constraints - constraints on whether a function will pass with\n the given args, format is array of constraint types\n callback_triggers - callback hook names and argument idxs for making\n calls to callback functions upon completion of this function call\n \"\"\"\n self.name = function_name\n self.possible_arg_nums = possible_arg_nums\n self.arg_split_words = arg_split_words\n self.arg_find_type = arg_find_type\n self.arg_constraints = arg_constraints\n self.func_constraints = func_constraints\n self.callback_triggers = callback_triggers\n self.formats = {'failed': '{1} couldn\\'t do that'}\n\n format_observation = format_observation\n\n def valid_args(self, graph, args):\n if 'ALL' in self.possible_arg_nums and len(args) >= 2:\n return True\n if len(args) not in self.possible_arg_nums:\n return False\n args = [a.lower() for a in args]\n loc = graph.location(args[0])\n # convert the arguments supplied to text form\n text_args = [graph.node_to_desc_raw(i, from_id=loc).lower() for i in args]\n # ensure that those are valid from the parser perspective\n valid, args, _args = self.parse_descs_to_args(graph, text_args)\n if not valid:\n return False\n # ensure that they pass the function constraints\n valid, _cons_passed, _failure = self.evaluate_constraint_set(\n graph, args, self.func_constraints\n )\n return valid\n\n def handle(self, graph, args):\n # if Callbacks.try_overrides(self, graph, args):\n # return True\n is_constrained, _cons_passed, failure_action = self.evaluate_constraint_set(\n graph, args, self.func_constraints\n )\n if not is_constrained:\n func_failure_action = self.get_failure_action(graph, args)\n # What failed?\n graph.send_action(args[0], func_failure_action)\n # Why it failed\n graph.send_action(args[0], failure_action)\n return False\n # callback_args = deepcopy(args)\n is_successful = self.func(graph, args)\n # if is_successful:\n # Callbacks.handle_callbacks(self, graph, args)\n # # TODO move callbacks call functionality elsewhere so other things\n # # can call callbacks\n # for trigger in self.callback_triggers:\n # for arg in trigger['args']:\n # if arg >= len(callback_args):\n # break # Don't have enough args for this callback\n # acting_agent = callback_args[arg]\n # callbacks = graph.get_prop(acting_agent, 'callbacks', {})\n # if trigger['action'] in callbacks:\n # use_args = [callback_args[i] for i in trigger['args']]\n # Callbacks.handle(graph, callbacks[trigger['action']],\n # use_args)\n return is_successful\n\n def func(self, graph, args):\n \"\"\"\n Execute action on the given graph\n Notation for documentation should be in the form of an action with <>'s\n around the incoming arguments in the order they are passed in. Optional\n arguments can be denoted by putting the clause in []'s.\n ex:\n does thing with [and other ]\n \"\"\"\n raise NotImplementedError\n\n def get_action_observation_format(self, action, descs):\n \"\"\"Given the action, return text to be filled by the parsed args\n Allowed to alter the descriptions if necessary\n Allowed to use the descriptions to determine the correct format as well\n \"\"\"\n if action['name'] in self.formats:\n return self.formats[action['name']]\n raise NotImplementedError\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n \"\"\"Returns an action for if the resolution of this function fails\"\"\"\n return {\n 'caller': self.get_name(),\n 'name': spec_fail,\n 'actors': args,\n 'room_id': graph.location(args[0]),\n }\n\n def get_find_fail_text(self, arg_idx):\n \"\"\"Text displayed when an arg find during parse_text_to_args call\n fails to find valid targets for the function.\n Can be overridden to provide different messages for different failed\n arguments.\n \"\"\"\n return 'That isn\\'t here'\n\n def get_improper_args_text(self, num_args):\n return 'Couldn\\'t understand that. Try help for help with commands'\n\n def evaluate_constraint_set(self, graph, args, constraints):\n \"\"\"Check a particular set of arguments against the given constraints\n returns (True, cons_passed, None) if the constraints all pass\n returns (False, cons_passed, failure_action) if any constraint fails\n \"\"\"\n cons_passed = 0\n failure_action = None\n for constraint in constraints:\n con_args = [args[i] for i in ([0] + constraint['in_args'])]\n con_args += constraint['args']\n con_obj = CONSTRAINTS[constraint['type']]\n if con_obj.evaluate_constraint(graph, con_args):\n cons_passed += 1\n else:\n spec_fail = constraint.get('spec_fail', 'failed')\n failure_action = con_obj.get_failure_action(graph, con_args, spec_fail)\n break\n if failure_action is None:\n return True, cons_passed, None\n else:\n return False, cons_passed, failure_action\n\n def check_possibilites_vs_constraints(\n self, graph, output_args, arg_idx, possible_ids\n ):\n \"\"\"Iterate through the given possible ids for a particular arg index\n and see if any match all the constraints for that argument\n\n Returns (True, valid_ID) on success\n Returns (False, violator_action) on failure\n \"\"\"\n constraints = self.arg_constraints[arg_idx]\n most_constraints = -1\n final_failure_action = None\n for pos_id in possible_ids:\n output_args[arg_idx] = pos_id\n success, cons_passed, failure_action = self.evaluate_constraint_set(\n graph, output_args, constraints\n )\n if success:\n return True, pos_id\n else:\n output_args[arg_idx] = None\n if cons_passed > most_constraints:\n most_constraints = cons_passed\n final_failure_action = failure_action\n return False, final_failure_action\n\n def parse_text_to_args(self, graph, actor_id, text):\n \"\"\"Breaks text into function arguments based on this function's\n delimiters\n Returns:\n (None, display text, None) if parsing failed to find valid candidates\n (True, arg_ids, canonical_text_args) if parsing and constraints succeed\n (False, Failure action, matched_args)\n if parsing succeeds but constraints fail\n \"\"\"\n actor_id = actor_id.lower()\n c_arg = []\n descs = [actor_id]\n for word in text:\n if word.lower() in self.arg_split_words:\n descs.append(' '.join(c_arg))\n c_arg = []\n else:\n c_arg.append(word)\n if len(c_arg) != 0:\n descs.append(' '.join(c_arg))\n if (\n len(descs) not in self.possible_arg_nums\n and 'ALL' not in self.possible_arg_nums\n ):\n return (None, self.get_improper_args_text(len(descs)), None)\n return self.parse_descs_to_args(graph, descs)\n\n def try_callback_override_args(self, graph, args):\n output_args = [None] * (len(args))\n output_args[0] = args[0]\n args = [arg.lower() for arg in args]\n # While there are still arguments to fill\n while None in output_args:\n for arg_idx, arg_id in enumerate(output_args):\n if arg_id is not None: # This was processed in an earlier pass\n continue\n nearbyid = output_args[0]\n\n # Get the possible IDs from the graph in the area\n arg_text = args[arg_idx]\n possible_ids = graph.desc_to_nodes(arg_text, nearbyid, 'all+here')\n # can't have reflexive actions with the same arg\n for had_id in output_args:\n if had_id in possible_ids:\n possible_ids.remove(had_id)\n if len(possible_ids) == 0:\n return None, None, None\n\n output_args[arg_idx] = possible_ids[0]\n\n # Determine canonical arguments\n # if Callbacks.has_valid_override(self, graph, output_args):\n # loc = graph.location(output_args[0])\n # text_args = \\\n # [graph.node_to_desc_raw(i, from_id=loc) for i in output_args]\n # return True, output_args, text_args\n return None, None, None\n\n def parse_descs_to_args_helper(self, graph, args, output_args, arg_find_idx=None):\n args = [a.lower() for a in args]\n for arg_idx, arg_id in enumerate(output_args):\n if arg_id is not None: # This was processed in an earlier pass\n continue\n arg_find_type = self.arg_find_type[arg_idx]\n if arg_find_idx is not None:\n arg_find_type = arg_find_type[arg_find_idx]\n nearby_idx = arg_find_type['from']\n # we cant process a from when the nearby hasn't been found\n if output_args[nearby_idx] is None:\n continue\n nearbyid = output_args[nearby_idx]\n\n # Make sure we have all the constraints filled\n constraints = self.arg_constraints[arg_idx]\n have_all_args = True\n for constraint in constraints:\n for alt_id_idx in constraint['in_args']:\n if arg_idx == alt_id_idx:\n continue # We plan to fill this slot with a guess\n if output_args[alt_id_idx] is None:\n # We don't have all the constraints for this\n have_all_args = False\n if not have_all_args:\n continue\n\n # Get the possible IDs from the graph in the area\n arg_text = args[arg_idx]\n possible_ids = graph.desc_to_nodes(\n arg_text, nearbyid, arg_find_type['type']\n )\n # can't have reflexive actions with the same arg\n for had_id in output_args:\n if had_id in possible_ids:\n possible_ids.remove(had_id)\n res = None\n while len(possible_ids) > 0:\n # See if any match the constraints\n success, res = self.check_possibilites_vs_constraints(\n graph, output_args, arg_idx, possible_ids\n )\n if success:\n output_args[arg_idx] = res\n possible_ids.remove(res)\n success_again, res, _args = self.parse_descs_to_args_helper(\n graph, args, output_args, arg_find_idx\n )\n if success_again:\n return True, None, output_args # success!\n elif res is not None:\n return False, res, args # failure case, no matching option\n else:\n break\n if res is not None:\n return False, res, args # failure case, no matching option\n return None, self.get_find_fail_text(arg_idx), None # failed find\n return True, '', output_args # base case, all filled\n\n def parse_descs_to_args(self, graph, args):\n \"\"\"iterates through the args and the constraints, solving dependency\n order on the fly.\n \"\"\"\n # TODO improve performance by instead constructing a dependency graph\n # at runtime to avoid repeat passes through the loop and to prevent\n # circular dependencies\n args = [a.lower() for a in args]\n success, output_args, text_args = self.try_callback_override_args(graph, args)\n if success:\n return success, output_args, text_args\n output_args = [None] * (len(args))\n output_args[0] = args[0]\n if 'ALL' in self.possible_arg_nums:\n output_args[1] = ' '.join(args[1:])\n return True, output_args, output_args\n args = [arg.lower() for arg in args]\n\n # While there are still arguments to fill\n if type(self.arg_find_type[0]) is list:\n arg_find_idx = 0\n success = False\n while arg_find_idx < len(self.arg_find_type[0]) and not success:\n output_args = [None] * (len(args))\n output_args[0] = args[0]\n success, res, output_args = self.parse_descs_to_args_helper(\n graph, args, output_args, arg_find_idx\n )\n arg_find_idx += 1\n else:\n success, res, output_args = self.parse_descs_to_args_helper(\n graph, args, output_args\n )\n\n if success:\n # Determine canonical arguments\n loc = graph.location(output_args[0])\n text_args = [graph.node_to_desc_raw(i, from_id=loc) for i in output_args]\n return True, output_args, text_args\n else:\n return success, res, output_args\n\n def get_name(self):\n \"\"\"Get the canonical name of this function\"\"\"\n name = self.name\n if type(name) is list:\n name = name[0]\n return name\n\n def get_canonical_form(self, graph, args):\n \"\"\"Get canonical form for the given args on this function\"\"\"\n if 'ALL' in self.possible_arg_nums:\n # All is reserved for functions that take all arguments\n return ' '.join(args)\n loc = graph.location(args[0])\n text_args = [graph.node_to_desc_raw(i, from_id=loc) for i in args]\n if len(args) == 1:\n return self.get_name()\n if len(self.arg_split_words) == 0 or len(args) == 2:\n return self.get_name() + ' ' + text_args[1]\n return (\n self.get_name()\n + ' '\n + (' ' + self.arg_split_words[0] + ' ').join(text_args[1:])\n )\n\n def get_reverse(self, graph, args):\n \"\"\"Function to parse the graph and args and return the reverse\n function and args\"\"\"\n return None, []\n\n\nclass SayFunction(GraphFunction):\n \"\"\"Output all the following arguments [Actor, raw text]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='say',\n possible_arg_nums=['ALL'],\n arg_split_words=[],\n arg_find_type=[{}],\n arg_constraints=[[]], # no constraints on the actor\n func_constraints=[],\n callback_triggers=[{'action': 'said', 'args': [0, 1]}],\n )\n\n def func(self, graph, args):\n \"\"\" sends message history to room [or specified ]\"\"\"\n actor = args[0]\n words = args[1].strip()\n if words.startswith('\"') and words.endswith('\"'):\n words = words[1:-1]\n room_id = graph.location(actor)\n agent_ids = graph.get_room_agents(room_id)\n said_action = {\n 'caller': self.get_name(),\n 'name': 'said',\n 'room_id': room_id,\n 'actors': [actor],\n 'present_agent_ids': agent_ids,\n 'content': words,\n }\n graph.broadcast_to_room(said_action, exclude_agents=[actor])\n return True\n\n def format_observation(self, graph, viewing_agent, action, telling_agent=None):\n \"\"\"Parse the observations to recount, then return them\"\"\"\n actor = action['actors'][0]\n content = action['content']\n if viewing_agent == actor:\n actor_text = 'You'\n else:\n actor_text = graph.node_to_desc(actor, use_the=True).capitalize()\n if content[-1] not in ['.', '?', '!']:\n content += '.'\n return '{} said \"{}\"\\n'.format(actor_text, content)\n\n\nclass TellFunction(GraphFunction):\n \"\"\"Output all the following arguments [Actor, Target, raw text]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='tell',\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'sameloc+players', 'from': 0}],\n arg_constraints=[[], []],\n func_constraints=[],\n callback_triggers=[{'action': 'told', 'args': [0, 1, 2]}],\n )\n\n def func(self, graph, args):\n \"\"\" sends message history to room [or specified ]\"\"\"\n actor = args[0]\n words = args[2]\n room_id = graph.location(actor)\n agent_ids = graph.get_room_agents(room_id)\n said_action = {\n 'caller': self.get_name(),\n 'name': 'said',\n 'room_id': room_id,\n 'actors': args[:2],\n 'present_agent_ids': agent_ids,\n 'content': words,\n }\n graph.broadcast_to_room(said_action, exclude_agents=[actor])\n graph._last_tell_target[actor] = args[1]\n return True\n\n def format_observation(self, graph, viewing_agent, action, telling_agent=None):\n \"\"\"Parse the observations to recount, then return them\"\"\"\n actor = action['actors'][0]\n target = action['actors'][1]\n content = action['content']\n involved = False\n if viewing_agent == actor:\n actor_text = 'You'\n involved = True\n else:\n actor_text = graph.node_to_desc(actor, use_the=True).capitalize()\n if viewing_agent == target:\n target_text = 'you'\n involved = True\n else:\n target_text = graph.node_to_desc(target, use_the=True)\n if involved:\n if content[-1] not in ['.', '?', '!']:\n content += '.'\n return '{} told {} \"{}\"\\n'.format(actor_text, target_text, content)\n return '{} whispered something to {}.'.format(actor_text, target_text)\n\n def valid_args(self, graph, args):\n args = [a.lower() for a in args]\n loc = graph.location(args[0])\n try:\n # convert the arguments supplied to text form\n text_args = [\n graph.node_to_desc_raw(i, from_id=loc).lower() for i in args[:2]\n ]\n # ensure that those are valid from the parser perspective\n valid, args, _args = self.parse_descs_to_args(graph, text_args)\n if not valid:\n return False\n # ensure that they pass the function constraints\n valid, _cons_passed, _failure = self.evaluate_constraint_set(\n graph, args, self.func_constraints\n )\n return valid\n except BaseException:\n return False\n\n def evaluate_constraint_set(self, graph, args, constraints):\n \"\"\"Can't talk to yourself, only constraint\"\"\"\n if args[0] == args[1]:\n return (\n False,\n 0,\n {\n 'caller': None,\n 'room_id': self.location(args[0]),\n 'txt': 'If you talk to yourself, you might seem crazy...',\n },\n )\n return True, 0, None\n\n def parse_text_to_args(self, graph, actor_id, text):\n \"\"\"Breaks text into function arguments based on tell target \"something\"\n Returns:\n (None, display text, None) if parsing failed to find valid candidates\n (True, arg_ids, canonical_text_args) if parsing and constraints succeed\n (False, Failure action, matched_args)\n if parsing succeeds but constraints fail\n \"\"\"\n actor_id = actor_id.lower()\n descs = [actor_id]\n text = ' '.join(text)\n text = text.lower()\n if '\"' not in text or not text.endswith('\"'):\n return None, 'Be sure to use quotes to speak (\").', None\n try:\n target = text.split('\"')[0].strip()\n content = text.split('\"')[1:]\n content = '\"'.join(content).strip('\"')\n descs = [actor_id, target]\n valid, arg_ids, c_args = self.parse_descs_to_args(graph, descs)\n if not valid:\n return None, \"You don't know what you're talking to\", None\n arg_ids.append(content)\n c_args.append(content)\n return valid, arg_ids, c_args\n except Exception:\n # import sys, traceback\n # exc_type, exc_value, exc_traceback = sys.exc_info()\n # traceback.print_tb(exc_traceback)\n # print(repr(e))\n # TODO the above in debug mode? would be useful\n return None, \"You couldn't talk to that now\", None\n\n def get_name(self):\n \"\"\"Get the canonical name of this function\"\"\"\n name = self.name\n if type(name) is list:\n name = name[0]\n return name\n\n def get_canonical_form(self, graph, args):\n \"\"\"Get canonical form for the given args on this function\"\"\"\n loc = graph.location(args[0])\n target_text = graph.node_to_desc_raw(args[1], from_id=loc)\n return 'tell {} \"{}\"'.format(target_text, args[2])\n\n\nclass UseFunction(GraphFunction):\n def __init__(self):\n super().__init__(\n function_name='use',\n possible_arg_nums=[3],\n arg_split_words=['with'],\n arg_find_type=[\n {}, # no constraints on the actor\n {'type': 'carrying', 'from': 0},\n {'type': 'all+here', 'from': 0},\n ],\n arg_constraints=[\n [], # no constraints on the actor\n is_held_item(1),\n [\n {\n 'type': 'is_type',\n 'in_args': [2],\n 'args': [['object'], 'Both have to be objects. '],\n }\n ],\n ],\n func_constraints=[],\n callback_triggers=[{'action': 'agent_used_with', 'args': [0, 1, 2]}],\n )\n self.formats = {\n 'cant_use_with': \"{0} couldn't find out how to \" \"use {1} with {2}. \",\n 'failed': '{0} couldn\\'t do that. ',\n }\n\n def get_find_fail_text(self, arg_idx):\n if arg_idx == 1:\n return \"You don't seem to have that. \"\n return 'That isn\\'t here. '\n\n def func(self, graph, args):\n \"\"\" uses with \"\"\"\n # held_obj = args[1]\n # callbacks = graph.get_prop(held_obj, 'callbacks', {})\n # if 'use_with' in callbacks:\n # rets = Callbacks.handle(graph, callbacks['use_with'], args)\n # if False in rets:\n # return False # This action was unsuccessfully handled\n # if True in rets:\n # return True # This action was successfully handled\n\n # other_obj = args[2]\n # callbacks = graph.get_prop(other_obj, 'callbacks', {})\n # if 'use_with' in callbacks:\n # rets = Callbacks.handle(graph, callbacks['use_with'], args)\n # if False in rets:\n # return False # This action was unsuccessfully handled\n # if True in rets:\n # return True # This action was successfully handled\n\n agent_id = args[0]\n room_id = graph.location(agent_id)\n cant_use_action = {\n 'caller': self.get_name(),\n 'name': 'cant_use_with',\n 'room_id': room_id,\n 'actors': args,\n }\n graph.send_action(args[0], cant_use_action)\n return False\n\n def get_action_observation_format(self, action, descs):\n if action['name'] == 'used_with':\n return '{0} {1} '\n return super().get_action_observation_format(action, descs)\n\n\nclass MoveAgentFunction(GraphFunction):\n \"\"\"[actor, destination room or path name from actor's room]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='go',\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[\n {}, # no constraints on the actor\n {'type': 'path', 'from': 0},\n ],\n arg_constraints=[\n [], # no constraints on the actor\n [\n {'type': 'is_type', 'in_args': [1], 'args': ['room']},\n {'type': 'is_locked', 'in_args': [1], 'args': [False]},\n {'type': 'not_location_of', 'in_args': [1], 'args': []},\n ],\n ],\n func_constraints=[{'type': 'fits_in', 'in_args': [0, 1], 'args': []}],\n callback_triggers=[\n {'action': 'moved_to', 'args': [0, 1]},\n {'action': 'agent_entered', 'args': [0, 1]},\n ],\n )\n self.formats = {\n 'left': '{0} left towards {1}. ',\n 'arrived': '{0} arrived from {1}. ',\n 'failed': '{0} can\\'t do that. ',\n 'follow': '{0} follow. ',\n 'followed': '{0} followed {1} here.',\n }\n\n def follow_agent(self, graph, args, followed):\n \"\"\"handler for all following actions\"\"\"\n agent_id = args[0]\n old_room_id = graph.location(agent_id)\n followers = graph.get_followers(agent_id)\n room_id = args[1]\n leave_action = {\n 'caller': self.get_name(),\n 'name': 'left',\n 'room_id': old_room_id,\n 'actors': [agent_id, room_id],\n }\n graph.broadcast_to_room(leave_action)\n graph.move_object(agent_id, room_id)\n\n # Prepare and send action for listing room contents\n is_return = room_id in graph._visited_rooms[agent_id]\n if is_return or not graph.has_prop(room_id, 'first_desc'):\n if not graph.has_prop(room_id, 'short_desc'):\n room_desc = graph.get_classed_prop(room_id, 'desc', agent_id, None)\n else:\n room_desc = graph.get_classed_prop(room_id, 'short_desc', agent_id)\n else:\n room_desc = graph.get_classed_prop(room_id, 'first_desc', agent_id)\n if is_return:\n agent_ids, agent_descs = graph.get_nondescribed_room_agents(room_id)\n object_ids, object_descs = graph.get_nondescribed_room_objects(room_id)\n _room_ids, room_descs = graph.get_room_edges(room_id)\n else:\n agent_ids, agent_descs = [], []\n object_ids, object_descs = [], []\n room_descs = []\n list_room_action = {\n 'caller': 'look',\n 'name': 'list_room',\n 'room_id': room_id,\n 'actors': [args[0]],\n 'agent_ids': agent_ids,\n 'present_agent_ids': agent_ids,\n 'object_ids': object_ids,\n 'agent_descs': agent_descs,\n 'object_descs': object_descs,\n 'room_descs': room_descs,\n 'room_desc': room_desc,\n 'returned': is_return,\n }\n graph.send_action(args[0], list_room_action)\n graph._last_rooms[agent_id] = old_room_id\n graph._visited_rooms[agent_id].add(old_room_id)\n graph._visited_rooms[agent_id].add(room_id)\n\n # Handle follows\n for other_agent in list(followers):\n room2 = graph.location(other_agent)\n if old_room_id == room2:\n follow_action = {\n 'caller': self.get_name(),\n 'name': 'follow',\n 'room_id': old_room_id,\n 'actors': [other_agent],\n }\n graph.send_msg(other_agent, 'You follow.\\n', follow_action)\n new_args = args.copy()\n new_args[0] = other_agent\n self.follow_agent(graph, new_args, agent_id)\n\n # Now that everyone is here, handle arrivals\n arrive_action = {\n 'caller': self.get_name(),\n 'name': 'followed',\n 'room_id': room_id,\n 'actors': [agent_id, followed],\n }\n graph.broadcast_to_room(arrive_action, exclude_agents=followers)\n # Callbacks.handle_callbacks(self, graph, args)\n return True\n\n def func(self, graph, args):\n \"\"\" moves to \"\"\"\n agent_id = args[0]\n old_room_id = graph.location(agent_id)\n followers = graph.get_followers(agent_id)\n room_id = args[1]\n leave_action = {\n 'caller': self.get_name(),\n 'name': 'left',\n 'room_id': old_room_id,\n 'actors': [agent_id, room_id],\n }\n graph.broadcast_to_room(leave_action)\n graph.move_object(agent_id, room_id)\n\n # Prepare and send action for listing room contents\n is_return = room_id in graph._visited_rooms[agent_id]\n if is_return or not graph.has_prop(room_id, 'first_desc'):\n if not graph.has_prop(room_id, 'short_desc'):\n room_desc = graph.get_classed_prop(room_id, 'desc', agent_id, None)\n else:\n room_desc = graph.get_classed_prop(room_id, 'short_desc', agent_id)\n else:\n room_desc = graph.get_classed_prop(room_id, 'first_desc', agent_id)\n if is_return or not graph.has_prop(room_id, 'first_desc'):\n agent_ids, agent_descs = graph.get_nondescribed_room_agents(room_id)\n object_ids, object_descs = graph.get_nondescribed_room_objects(room_id)\n _room_ids, room_descs = graph.get_room_edges(room_id)\n else:\n agent_ids, agent_descs = [], []\n object_ids, object_descs = [], []\n room_descs = []\n list_room_action = {\n 'caller': 'look',\n 'name': 'list_room',\n 'room_id': room_id,\n 'actors': [args[0]],\n 'agent_ids': agent_ids,\n 'present_agent_ids': agent_ids,\n 'object_ids': object_ids,\n 'agent_descs': agent_descs,\n 'object_descs': object_descs,\n 'room_descs': room_descs,\n 'room_desc': room_desc,\n 'returned': is_return,\n }\n graph.send_action(args[0], list_room_action)\n graph._last_rooms[agent_id] = old_room_id\n graph._visited_rooms[agent_id].add(old_room_id)\n graph._visited_rooms[agent_id].add(room_id)\n\n # Handle follows\n for other_agent in list(followers):\n room2 = graph.location(other_agent)\n if old_room_id == room2:\n follow_action = {\n 'caller': self.get_name(),\n 'name': 'follow',\n 'room_id': old_room_id,\n 'actors': [other_agent],\n }\n graph.send_msg(other_agent, 'You follow.\\n', follow_action)\n new_args = args.copy()\n new_args[0] = other_agent\n self.follow_agent(graph, new_args, agent_id)\n\n # Now that everyone is here, handle arrivals\n arrive_action = {\n 'caller': self.get_name(),\n 'name': 'arrived',\n 'room_id': room_id,\n 'actors': [agent_id, old_room_id],\n }\n graph.broadcast_to_room(arrive_action, exclude_agents=followers)\n return True\n\n def parse_text_to_args(self, graph, actor_id, text):\n \"\"\"Wraps the super parse_text_to_args to be able to handle the special\n case of \"go back\"\n \"\"\"\n actor_id = actor_id.lower()\n if len(text) == 0:\n return super().parse_text_to_args(graph, actor_id, text)\n elif text[-1].lower() == 'back':\n if graph._last_rooms[actor_id] is None:\n return None, 'Back where exactly? You\\'ve just started!', None\n text[-1] = graph.node_to_desc_raw(\n graph._last_rooms[actor_id], from_id=graph.location(actor_id)\n )\n return super().parse_text_to_args(graph, actor_id, text)\n\n def get_find_fail_text(self, arg_idx):\n return 'Where is that? You don\\'t see it'\n\n def get_action_observation_format(self, action, descs):\n if 'past' not in action:\n if descs[0] == 'You':\n return '' # Don't tell someone where they just went\n return super().get_action_observation_format(action, descs)\n\n REPLACEMENTS = {\n 'e': 'east',\n 'w': 'west',\n 'n': 'north',\n 's': 'south',\n 'u': 'up',\n 'd': 'down',\n }\n\n def parse_descs_to_args(self, graph, args):\n # Replace shortcuts with full words for better matching\n if args[1] in self.REPLACEMENTS:\n args[1] = self.REPLACEMENTS[args[1]]\n return super().parse_descs_to_args(graph, args)\n\n # TODO implement reverse for go\n\n\nclass FollowFunction(GraphFunction):\n \"\"\"[Actor, agent actor should follow in same room]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name=['follow'],\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'sameloc', 'from': 0}],\n arg_constraints=[\n [], # no constraints on the actor\n [\n {\n 'type': 'is_type',\n 'in_args': [1],\n 'args': [['agent'], 'You can\\'t follow that.'],\n }\n ],\n ],\n func_constraints=[],\n callback_triggers=[{'action': 'followed', 'args': [0, 1]}],\n )\n self.formats = {\n 'followed': '{0} started following {1}. ',\n 'failed': '{0} couldn\\'t follow that. ',\n }\n\n def func(self, graph, args):\n \"\"\" start following [] (unfollow if no agent supplied)\"\"\"\n agent_id = args[0]\n room_id = graph.location(args[0])\n following = graph.get_following(agent_id)\n\n if len(args) > 1 and following == args[1]:\n graph.send_msg(agent_id, 'You are already following them.\\n')\n return True\n\n # Have to unfollow if currently following someone\n if following is not None:\n GRAPH_FUNCTIONS['unfollow'].handle(graph, [args[0]])\n\n graph.set_follow(agent_id, args[1])\n follow_action = {\n 'caller': self.get_name(),\n 'name': 'followed',\n 'room_id': room_id,\n 'actors': args,\n }\n graph.broadcast_to_room(follow_action)\n return True\n\n def get_reverse(self, graph, args):\n return 'unfollow', [args[0]]\n\n\nclass HitFunction(GraphFunction):\n \"\"\"[Actor, victim in same room]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name=['hit'],\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'sameloc', 'from': 0}],\n arg_constraints=[\n [], # no constraints on the actor\n [\n {\n 'type': 'is_type',\n 'in_args': [1],\n 'args': [['agent'], 'You can\\'t hit that.'],\n },\n {\n 'type': 'not_type',\n 'in_args': [1],\n 'args': [['described'], 'You decide against attacking.'],\n },\n ],\n ],\n func_constraints=[],\n callback_triggers=[{'action': 'hit', 'args': [0, 1]}],\n )\n self.formats = {\n 'attacked': '{0} attacked {1}. ',\n 'missed': '{0} attacked {1}, but missed. ',\n 'blocked': '{0} attacked {1}, but ' '{1} blocked the attack. ',\n 'failed': '{0} couldn\\'t hit that. ',\n }\n\n def handle(self, graph, args):\n # if Callbacks.try_overrides(self, graph, args):\n # return True\n is_constrained, _cons_passed, failure_action = self.evaluate_constraint_set(\n graph, args, self.func_constraints\n )\n if not is_constrained:\n func_failure_action = self.get_failure_action(graph, args)\n # What failed?\n graph.send_action(args[0], func_failure_action)\n # Why it failed\n graph.send_action(args[0], failure_action)\n return False\n is_successful = self.func(graph, args)\n return is_successful\n\n def func(self, graph, args):\n \"\"\" attempts attack on \"\"\"\n agent_id = args[0]\n room_id = graph.location(args[0])\n victim_id = args[1]\n damage = graph.get_prop(agent_id, 'damage', 0)\n armor = graph.get_prop(victim_id, 'defense', 0)\n attack = random.randint(0, damage + 1)\n defend = random.randint(0, armor)\n action = {'caller': self.get_name(), 'room_id': room_id, 'actors': args}\n did_hit = False\n if damage == -1: # It's not a very physical class\n if random.randint(0, 1):\n did_hit = True\n action['name'] = 'attacked'\n attack = 0\n defend = 0\n else:\n action['name'] = 'missed'\n elif (attack == 0 or attack - defend < 1) and not graph.freeze():\n action['name'] = 'missed' if attack == 0 else 'blocked'\n else:\n did_hit = True\n action['name'] = 'attacked'\n\n graph.broadcast_to_room(action)\n\n if did_hit:\n # Callbacks.handle_callbacks(self, graph, args)\n # TODO move energy updates to a shared function\n energy = graph.get_prop(victim_id, 'health')\n energy = max(0, energy - (attack - defend))\n if energy <= 0:\n graph.die(victim_id)\n elif energy < 4 and energy > 0:\n # TODO move getting a health action to the health function\n health_text = graph.health(victim_id)\n my_health_action = {\n 'caller': 'health',\n 'actors': [victim_id],\n 'name': 'display_health',\n 'room_id': room_id,\n 'add_descs': [health_text],\n }\n graph.send_action(victim_id, my_health_action)\n graph.set_prop(victim_id, 'health', energy)\n # else:\n # Callbacks.handle_miss_callbacks(self, graph, args)\n return True\n\n def get_find_fail_text(self, arg_idx):\n return 'Where are they? You don\\'t see them'\n\n\nclass HugFunction(GraphFunction):\n \"\"\"[Actor, target in same room]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name=['hug'],\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'sameloc', 'from': 0}],\n arg_constraints=[\n [], # no constraints on the actor\n [\n {\n 'type': 'is_type',\n 'in_args': [1],\n 'args': [['agent'], 'You can\\'t hug that.'],\n }\n ],\n ],\n func_constraints=[],\n callback_triggers=[{'action': 'hug', 'args': [0, 1]}],\n )\n self.formats = {'hug': '{0} hugged {1}. ', 'failed': '{0} couldn\\'t hug that. '}\n\n def func(self, graph, args):\n \"\"\" hugs \"\"\"\n room_id = graph.location(args[0])\n action = {\n 'caller': self.get_name(),\n 'room_id': room_id,\n 'actors': args,\n 'name': 'hug',\n }\n graph.broadcast_to_room(action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n return 'Where are they? You don\\'t see them'\n\n def get_reverse(self, graph, args):\n return False, []\n\n\nclass GetObjectFunction(GraphFunction):\n \"\"\"[Actor, object attainable by actor, optional container for object]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name=['get', 'take'],\n possible_arg_nums=[2, 3],\n arg_split_words=['from'],\n arg_find_type=[\n [{}, {}], # no constraints on the actor\n [{'type': 'all+here', 'from': 0}, {'type': 'carrying', 'from': 2}],\n [{'type': 'contains', 'from': 1}, {'type': 'all+here', 'from': 0}],\n ],\n arg_constraints=[\n [], # no constraints on the actor\n [\n {'type': 'is_type', 'in_args': [1], 'args': ['object']},\n {\n 'type': 'not_type',\n 'in_args': [1],\n 'args': [['not_gettable'], \"That isn't something you can get\"],\n },\n {\n 'type': 'not_type',\n 'in_args': [1],\n 'args': [\n ['described'],\n \"You choose not to take that and ruin \"\n \"this room's description\",\n ],\n },\n ],\n [\n {\n 'type': 'is_type',\n 'in_args': [2],\n 'args': [['container', 'room'], 'That\\'s not a container.'],\n },\n {'type': 'is_locked', 'in_args': [2], 'args': [False]},\n ],\n ],\n func_constraints=[\n {\n 'type': 'fits_in',\n 'in_args': [1, 0],\n 'args': [],\n 'spec_fail': 'cant_carry',\n }\n ],\n callback_triggers=[\n {'action': 'moved_to', 'args': [1, 0]},\n {'action': 'agent_got', 'args': [0, 1]},\n ],\n )\n self.formats = {\n 'got': '{0} got {1}. ',\n 'got_from': '{0} got {1} from {2}. ',\n 'failed': '{0} couldn\\'t get {1}. ',\n }\n\n def func(self, graph, args):\n \"\"\" gets [from ]\"\"\"\n agent_id, object_id = args[0], args[1]\n container_id = graph.location(object_id)\n room_id = graph.location(agent_id)\n graph.move_object(object_id, agent_id)\n if 'room' in graph.get_prop(container_id, 'classes'):\n get_action = {\n 'caller': self.get_name(),\n 'name': 'got',\n 'room_id': room_id,\n 'actors': [agent_id, object_id],\n }\n else:\n get_action = {\n 'caller': self.get_name(),\n 'name': 'got_from',\n 'room_id': room_id,\n 'actors': [agent_id, object_id, container_id],\n }\n graph.broadcast_to_room(get_action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n if arg_idx == 2:\n return 'That isn\\'t there. '\n else:\n return 'That isn\\'t here. '\n\n def parse_descs_to_args(self, graph, args):\n # Append a location for the object, defaulting to the room if the\n # immediate container of something can't be found\n args = [a.lower() for a in args]\n if len(args) < 3:\n try:\n object_ids = graph.desc_to_nodes(args[1], args[0], 'all+here')\n i = 0\n container_id = args[0]\n # avoid reflexive matches!\n while container_id == args[0]:\n container_id = graph.location(object_ids[i])\n i += 1\n container_name = graph.node_to_desc_raw(container_id)\n args.append(container_name)\n except Exception:\n args.append(graph.node_to_desc_raw(graph.location(args[0])))\n return super().parse_descs_to_args(graph, args)\n\n def get_canonical_form(self, graph, args):\n \"\"\"Get canonical form for the given args on this function\"\"\"\n if len(args) == 3 and graph.get_prop(args[2], 'container') is True:\n return super().get_canonical_form(graph, args)\n else:\n return super().get_canonical_form(graph, args[:2])\n\n def get_reverse(self, graph, args):\n if graph.get_prop(args[2], 'container') is True:\n return 'put', args\n else:\n return 'drop', args[:2]\n\n\n# TODO override get_canonical_form for on/in\nclass PutObjectInFunction(GraphFunction):\n \"\"\"[Actor, object actor is carrying, container]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='put',\n possible_arg_nums=[3],\n arg_split_words=['in', 'into', 'on', 'onto'],\n arg_find_type=[\n {}, # no constraints on the actor\n {'type': 'carrying', 'from': 0},\n {'type': 'all+here', 'from': 0},\n ],\n arg_constraints=[\n [], # no constraints on the actor\n is_held_item(1),\n [\n {\n 'type': 'is_type',\n 'in_args': [2],\n 'args': [['container'], 'That\\'s not a container.'],\n }\n ],\n ],\n func_constraints=[{'type': 'fits_in', 'in_args': [1, 2], 'args': []}],\n callback_triggers=[\n {'action': 'moved_to', 'args': [1, 2]},\n {'action': 'agent_put_in', 'args': [0, 1, 2]},\n ],\n )\n self.formats = {\n 'put_in': '{0} put {1} into {2}. ',\n 'put_on': '{0} put {1} onto {2}. ',\n 'failed': '{0} couldn\\'t put that. ',\n }\n\n def func(self, graph, args):\n \"\"\" puts in or on \"\"\"\n agent_id, object_id, container_id = args[0], args[1], args[2]\n graph.move_object(object_id, container_id)\n act_name = 'put_' + graph.get_prop(container_id, 'surface_type', 'in')\n room_id = graph.location(agent_id)\n put_action = {\n 'caller': self.get_name(),\n 'name': act_name,\n 'room_id': room_id,\n 'actors': [agent_id, object_id, container_id],\n }\n graph.broadcast_to_room(put_action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n if arg_idx == 1:\n return 'You don\\'t have that. '\n else:\n return 'That isn\\'t here. '\n\n def get_reverse(self, graph, args):\n return 'get', args\n\n\nclass DropObjectFunction(GraphFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='drop',\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[\n {}, # no constraints on the actor\n {'type': 'carrying', 'from': 0},\n {'type': 'all+here', 'from': 0},\n ],\n arg_constraints=[[], is_held_item(1), []],\n func_constraints=[{'type': 'fits_in', 'in_args': [1, 2], 'args': []}],\n callback_triggers=[\n {'action': 'moved_to', 'args': [1, 2]},\n {'action': 'agent_dropped', 'args': [0, 1]},\n ],\n )\n self.formats = {\n 'dropped': '{0} dropped {1}. ',\n 'failed': '{0} couldn\\'t drop that. ',\n }\n\n def func(self, graph, args):\n \"\"\" drops \"\"\"\n agent_id, object_id, room_id = args[0], args[1], args[2]\n graph.move_object(object_id, room_id)\n put_action = {\n 'caller': self.get_name(),\n 'name': 'dropped',\n 'room_id': room_id,\n 'actors': [agent_id, object_id],\n }\n graph.broadcast_to_room(put_action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n return 'You don\\'t have that. '\n\n def parse_descs_to_args(self, graph, args):\n # appends the room as the target of the move\n args.append(graph.node_to_desc_raw(graph.location(args[0])))\n return super().parse_descs_to_args(graph, args)\n\n def get_reverse(self, graph, args):\n return 'get', args\n\n\nclass GiveObjectFunction(GraphFunction):\n \"\"\"[Actor, object actor is carrying, other agent in same room]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='give',\n possible_arg_nums=[3],\n arg_split_words=['to'],\n arg_find_type=[\n {}, # no constraints on the actor\n {'type': 'carrying', 'from': 0},\n {'type': 'sameloc', 'from': 0},\n ],\n arg_constraints=[\n [], # no constraints on the actor\n is_held_item(1),\n [\n {\n 'type': 'is_type',\n 'in_args': [2],\n 'args': [['agent'], 'The recipient is a thing.'],\n }\n ],\n ],\n func_constraints=[\n {\n 'type': 'fits_in',\n 'in_args': [1, 2],\n 'args': [],\n 'spec_fail': 'cant_carry',\n }\n ],\n callback_triggers=[\n {'action': 'moved_to', 'args': [1, 2]},\n {'action': 'agent_received_from', 'args': [2, 1, 0]},\n ],\n )\n self.formats = {\n 'gave': '{0} gave {2} {1}. ',\n 'failed': '{0} couldn\\'t give that. ',\n }\n\n def func(self, graph, args):\n \"\"\" gives to \"\"\"\n agent_id, object_id, receiver_id = args[0], args[1], args[2]\n graph.move_object(object_id, receiver_id)\n room_id = graph.location(agent_id)\n give_action = {\n 'caller': self.get_name(),\n 'name': 'gave',\n 'room_id': room_id,\n 'actors': [agent_id, object_id, receiver_id],\n }\n graph.broadcast_to_room(give_action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n if arg_idx == 1:\n return 'You don\\'t have that. '\n else:\n return 'They aren\\'t here. '\n\n def get_reverse(self, graph, args):\n return 'steal', args\n\n\nclass StealObjectFunction(GraphFunction):\n \"\"\"[Actor, object other agent is carrying, other agent in same room]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='steal',\n possible_arg_nums=[2, 3],\n arg_split_words=['from'],\n arg_find_type=[\n [{}, {}], # no constraints on the actor\n [{'type': 'all+here', 'from': 0}, {'type': 'carrying', 'from': 2}],\n [{'type': 'contains', 'from': 1}, {'type': 'all+here', 'from': 0}],\n ],\n arg_constraints=[\n [], # no constraints on the actor\n is_held_item(1),\n [\n {\n 'type': 'is_type',\n 'in_args': [2],\n 'args': [['agent'], 'You can\\'t steal from that.'],\n }\n ],\n ],\n func_constraints=[\n {\n 'type': 'fits_in',\n 'in_args': [1, 0],\n 'args': [],\n 'spec_fail': 'cant_carry',\n }\n ],\n callback_triggers=[\n {'action': 'moved_to', 'args': [1, 0]},\n {'action': 'agent_stole_from', 'args': [0, 1, 2]},\n ],\n )\n self.formats = {\n 'stole': '{0} stole {1} from {2}. ',\n 'failed': '{0} couldn\\'t give that. ',\n }\n\n def func(self, graph, args):\n \"\"\" steals from \"\"\"\n agent_id, object_id, victim_id = args[0], args[1], args[2]\n graph.move_object(object_id, agent_id)\n room_id = graph.location(agent_id)\n give_action = {\n 'caller': self.get_name(),\n 'name': 'stole',\n 'room_id': room_id,\n 'actors': [agent_id, object_id, victim_id],\n }\n graph.broadcast_to_room(give_action)\n return True\n\n def parse_descs_to_args(self, graph, args):\n # Append a location for the object, defaulting to the room if the\n # immediate container of something can't be found\n args = [a.lower() for a in args]\n if len(args) < 3:\n try:\n object_ids = graph.desc_to_nodes(args[1], args[0], 'all+here')\n i = 0\n container_id = args[0]\n # avoid reflexive matches!\n while container_id == args[0]:\n container_id = graph.location(object_ids[i])\n i += 1\n container_name = graph.node_to_desc_raw(container_id)\n args.append(container_name)\n except Exception:\n args.append(graph.node_to_desc_raw(graph.location(args[0])))\n return super().parse_descs_to_args(graph, args)\n\n def get_find_fail_text(self, arg_idx):\n if arg_idx == 1:\n return 'They don\\'t have that. '\n else:\n return 'They aren\\'t here. '\n\n def get_reverse(self, graph, args):\n return 'give', args\n\n\nclass EquipObjectFunction(GraphFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(\n self, function_name='equip', action='equipped', additional_constraints=None\n ):\n if additional_constraints is None:\n additional_constraints = []\n super().__init__(\n function_name=function_name,\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'carrying', 'from': 0}],\n arg_constraints=[[], is_held_item(1) + additional_constraints],\n func_constraints=[],\n callback_triggers=[\n {'action': 'agent_' + action, 'args': [0, 1]},\n {'action': action + '_by', 'args': [1, 0]},\n ],\n )\n self.formats = {\n action: '{0} ' + action + ' {1}. ',\n 'failed': '{0} couldn\\'t ' + function_name + ' that. ',\n }\n self.action = action\n\n def func(self, graph, args):\n \"\"\" equips \"\"\"\n agent_id, object_id = args[0], args[1]\n graph.set_prop(object_id, 'equipped', self.name)\n for n, s in graph.get_prop(object_id, 'stats', {'defense': 1}).items():\n graph.inc_prop(agent_id, n, s)\n room_id = graph.location(agent_id)\n equip_action = {\n 'caller': self.get_name(),\n 'name': self.action,\n 'room_id': room_id,\n 'actors': [agent_id, object_id],\n }\n graph.broadcast_to_room(equip_action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n return 'You don\\'t have that.'\n\n def get_reverse(self, graph, args):\n return 'remove', args\n\n\nclass WearObjectFunction(EquipObjectFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='wear',\n action='wore',\n additional_constraints=[\n {\n 'type': 'is_type',\n 'in_args': [1],\n 'args': [['wearable'], 'That isn\\'t wearable.'],\n }\n ],\n )\n\n\nclass WieldObjectFunction(EquipObjectFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='wield',\n action='wielded',\n additional_constraints=[\n {\n 'type': 'is_type',\n 'in_args': [1],\n 'args': [['weapon'], 'That isn\\'t wieldable.'],\n }\n ],\n )\n\n\nclass RemoveObjectFunction(GraphFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name=['remove', 'unwield'],\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'carrying', 'from': 0}],\n arg_constraints=[[], is_equipped_item(1)],\n func_constraints=[],\n callback_triggers=[\n {'action': 'agent_removed', 'args': [0, 1]},\n {'action': 'removed_by', 'args': [1, 0]},\n ],\n )\n self.formats = {\n 'removed': '{0} put {1} away. ',\n 'failed': '{0} couldn\\'t remove that. ',\n }\n\n def func(self, graph, args):\n \"\"\" unequips \"\"\"\n agent_id, object_id = args[0], args[1]\n graph.set_prop(object_id, 'equipped', None)\n for n, s in graph.get_prop(object_id, 'stats', {'defense': 1}).items():\n graph.inc_prop(agent_id, n, -s)\n room_id = graph.location(agent_id)\n put_action = {\n 'caller': self.get_name(),\n 'name': 'removed',\n 'room_id': room_id,\n 'actors': [agent_id, object_id],\n }\n graph.broadcast_to_room(put_action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n return 'You don\\'t have that equipped.'\n\n def get_reverse(self, graph, args):\n return 'equip', args\n\n\nclass IngestFunction(GraphFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(\n self, function_name='ingest', action='ingested', additional_constraints=None\n ):\n if additional_constraints is None:\n additional_constraints = []\n super().__init__(\n function_name=function_name,\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'carrying', 'from': 0}],\n arg_constraints=[[], is_held_item(1) + additional_constraints],\n func_constraints=[],\n callback_triggers=[\n {'action': 'agent_' + action, 'args': [0, 1]},\n {'action': action + '_by', 'args': [1, 0]},\n ],\n )\n self.formats = {\n action: '{0} ' + action + ' {1}. ',\n 'failed': '{0} couldn\\'t ' + function_name + ' that. ',\n }\n self.action = action\n\n def func(self, graph, args):\n \"\"\" consumes \"\"\"\n agent_id, object_id = args[0], args[1]\n fe = graph.get_prop(object_id, 'food_energy')\n thing_desc = graph.node_to_desc(object_id, use_the=True)\n room_id = graph.location(agent_id)\n graph.delete_node(object_id)\n ingest_action = {\n 'caller': self.get_name(),\n 'name': self.action,\n 'room_id': room_id,\n 'actors': [agent_id],\n 'add_descs': [thing_desc],\n }\n graph.broadcast_to_room(ingest_action)\n if fe >= 0:\n graph.send_msg(agent_id, \"Yum.\\n\")\n else:\n graph.send_msg(agent_id, \"Gross!\\n\")\n\n energy = graph.get_prop(agent_id, 'health')\n if energy < 8:\n prev_health = graph.health(agent_id)\n energy = energy + fe\n graph.set_prop(agent_id, 'health', energy)\n new_health = graph.health(agent_id)\n if energy <= 0:\n self.die(agent_id)\n elif prev_health != new_health:\n health_action = {\n 'caller': 'health',\n 'name': 'changed',\n 'room_id': room_id,\n 'actors': [args[0]],\n 'add_descs': [prev_health, new_health],\n }\n graph.broadcast_to_room(health_action)\n return True\n\n def get_find_fail_text(self, arg_idx):\n return 'You don\\'t have that.'\n\n\nclass EatFunction(IngestFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='eat',\n action='ate',\n additional_constraints=[\n {\n 'type': 'is_type',\n 'in_args': [1],\n 'args': [['food'], 'That isn\\'t food.'],\n }\n ],\n )\n\n\nclass DrinkFunction(IngestFunction):\n \"\"\"[Actor, object actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='drink',\n action='drank',\n additional_constraints=[\n {\n 'type': 'is_type',\n 'in_args': [1],\n 'args': [['drink'], 'That isn\\'t a drink.'],\n }\n ],\n )\n\n\nclass LockFunction(GraphFunction):\n \"\"\"[Actor, lockable thing in same location, key actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='lock',\n possible_arg_nums=[3],\n arg_split_words=['with'],\n arg_find_type=[\n {}, # no constraints on the actor\n {'type': 'all+here', 'from': 0},\n {'type': 'carrying', 'from': 0},\n ],\n arg_constraints=[\n [], # no constraints on the actor\n [{'type': 'is_lockable', 'in_args': [1], 'args': [True]}],\n [\n {\n 'type': 'is_type',\n 'in_args': [2],\n 'args': [['key'], 'That isn\\'t a key.'],\n }\n ],\n ],\n func_constraints=[\n {'type': 'is_locked', 'in_args': [1], 'args': [False]},\n {'type': 'locked_with', 'in_args': [1, 2], 'args': []},\n ],\n callback_triggers=[{'action': 'agent_unlocked', 'args': [0, 1]}],\n )\n self.formats = {\n 'locked': '{0} locked {1}. ',\n 'failed': '{0} couldn\\'t lock that. ',\n }\n\n def get_improper_args_text(self, num_args):\n if num_args == 2:\n return 'Lock that with what?'\n else:\n return 'Lock is used with \"lock with \"'\n\n def func(self, graph, args):\n \"\"\" locks using \"\"\"\n actor_id, target_id, key_id = args[0], args[1], args[2]\n room_id = graph.location(actor_id)\n if 'room' in graph.get_prop(target_id, 'classes'):\n graph.lock_path(graph.location(actor_id), target_id, key_id)\n else:\n # TODO implement lock_object\n graph.lock_object(target_id, key_id)\n lock_action = {\n 'caller': self.get_name(),\n 'name': 'locked',\n 'room_id': room_id,\n 'actors': [actor_id, target_id],\n }\n graph.broadcast_to_room(lock_action)\n return True\n\n def get_reverse(self, graph, args):\n return 'lock', args\n\n\nclass UnlockFunction(GraphFunction):\n \"\"\"[Actor, lockable thing in same location, key actor is carrying]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name='unlock',\n possible_arg_nums=[3],\n arg_split_words=['with'],\n arg_find_type=[\n {}, # no constraints on the actor\n {'type': 'all+here', 'from': 0},\n {'type': 'carrying', 'from': 0},\n ],\n arg_constraints=[\n [], # no constraints on the actor\n [{'type': 'is_lockable', 'in_args': [1], 'args': [True]}],\n [\n {\n 'type': 'is_type',\n 'in_args': [2],\n 'args': [['key'], 'That isn\\'t a key.'],\n }\n ],\n ],\n func_constraints=[\n {'type': 'is_locked', 'in_args': [1], 'args': [True]},\n {'type': 'locked_with', 'in_args': [1, 2], 'args': []},\n ],\n callback_triggers=[{'action': 'agent_unlocked', 'args': [0, 1]}],\n )\n self.formats = {\n 'unlocked': '{0} unlocked {1}. ',\n 'failed': '{0} couldn\\'t unlock that. ',\n }\n\n def func(self, graph, args):\n \"\"\" unlocks using \"\"\"\n actor_id, target_id, key_id = args[0], args[1], args[2]\n room_id = graph.location(actor_id)\n if 'room' in graph.get_prop(target_id, 'classes'):\n graph.unlock_path(graph.location(actor_id), target_id, key_id)\n else:\n # TODO implement unlock_object\n graph.unlock_object(target_id, key_id)\n lock_action = {\n 'caller': self.get_name(),\n 'name': 'unlocked',\n 'room_id': room_id,\n 'actors': [actor_id, target_id],\n }\n graph.broadcast_to_room(lock_action)\n return True\n\n def get_improper_args_text(self, num_args):\n if num_args == 2:\n return 'Unlock that with what?'\n else:\n return 'Unlock is used with \"unlock with \"'\n\n def get_reverse(self, graph, args):\n return 'lock', args\n\n\nclass ExamineFunction(GraphFunction):\n \"\"\"[Actor, anything accessible to the actor]\"\"\"\n\n def __init__(self):\n super().__init__(\n function_name=['examine', 'ex'],\n possible_arg_nums=[2],\n arg_split_words=[],\n arg_find_type=[{}, {'type': 'all+here', 'from': 0}],\n arg_constraints=[[], []],\n func_constraints=[],\n callback_triggers=[{'action': 'agent_examined', 'args': [0, 1]}],\n )\n\n def func(self, graph, args):\n \"\"\" examines \"\"\"\n agent_id, object_id = args[0], args[1]\n room_id = graph.location(agent_id)\n examine_action = {\n 'caller': self.get_name(),\n 'name': 'witnessed',\n 'room_id': room_id,\n 'actors': [agent_id, object_id],\n }\n graph.broadcast_to_room(examine_action, [agent_id])\n\n if 'room' in graph.get_prop(object_id, 'classes'):\n object_type = 'room'\n add_descs = [graph.get_path_ex_desc(room_id, object_id, agent_id)]\n elif 'container' in graph.get_prop(object_id, 'classes'):\n # Mark containers as being examined so that they can be added\n # to the pool of all+here\n graph.set_prop(object_id, 'examined', True)\n object_type = 'container'\n add_descs = []\n add_descs.append(graph.get_classed_prop(object_id, 'desc', agent_id))\n if len(graph.node_contains(object_id)) > 0:\n add_descs.append(graph.display_node(object_id))\n elif 'agent' in graph.get_prop(object_id, 'classes'):\n graph.set_prop(object_id, 'examined', True)\n object_type = 'agent'\n add_descs = []\n inv_txt = graph.get_inventory_text_for(object_id, give_empty=False)\n if graph.has_prop(object_id, 'desc'):\n add_descs.append(graph.get_classed_prop(object_id, 'desc', agent_id))\n if inv_txt != '':\n object_desc = graph.node_to_desc(object_id, use_the=True).capitalize()\n add_descs.append(object_desc + ' is ' + inv_txt)\n else:\n object_type = 'object'\n add_descs = [graph.get_classed_prop(object_id, 'desc', agent_id)]\n if len(add_descs) == 0 or add_descs[0] is None:\n add_descs = ['There is nothing special about it. ']\n add_descs = ['\\n'.join(add_descs)] # Compress the descriptions to one\n examine_object_action = {\n 'caller': self.get_name(),\n 'name': 'examine_object',\n 'room_id': room_id,\n 'actors': args,\n 'add_descs': add_descs,\n 'object_type': object_type,\n }\n graph.send_action(agent_id, examine_object_action)\n return True\n\n def get_action_observation_format(self, action, descs):\n if action['name'] == 'witnessed':\n return '{0} looked at {1}. '\n elif action['name'] == 'examine_object':\n if 'past' in action:\n return '{0} examined {1}.\\n{2}'\n else:\n return '{2}'\n return super().get_action_observation_format(action, descs)\n\n def get_find_fail_text(self, arg_idx):\n return 'That isn\\'t here. '\n\n def get_improper_args_text(self, num_args):\n if num_args == 1:\n return 'Examine what?'\n else:\n return 'Examine is used as \"examine \"'\n\n def get_reverse(self, graph, args):\n return False, args\n\n\nclass SoloFunction(GraphFunction):\n \"\"\"[Actor]\"\"\"\n\n def __init__(self, function_name, callback_triggers):\n super().__init__(\n function_name=function_name,\n possible_arg_nums=[1],\n arg_split_words=[],\n arg_find_type=[{}],\n arg_constraints=[[]],\n func_constraints=[],\n callback_triggers=callback_triggers,\n )\n\n def get_reverse(self, graph, args):\n return False, args\n\n\nclass WaitFunction(SoloFunction):\n def __init__(self):\n super().__init__(\n function_name='wait',\n callback_triggers=[{'action': 'agent_waited', 'args': [0]}],\n )\n self.formats = {'waited': '{0} waited. '}\n\n def func(self, graph, args):\n room_id = graph.location(args[0])\n graph.send_action(\n args[0],\n {\n 'caller': self.get_name(),\n 'name': 'waited',\n 'room_id': room_id,\n 'actors': [args[0]],\n },\n )\n return True\n\n\nclass InventoryFunction(SoloFunction):\n def __init__(self):\n super().__init__(\n function_name=['inventory', 'inv', 'i'],\n callback_triggers=[{'action': 'check_inventory', 'args': [0]}],\n )\n\n def get_action_observation_format(self, action, descs):\n if action['name'] == 'check_inventory':\n if descs[0] == 'You':\n return 'You checked your inventory. '\n elif descs[0] == 'I':\n return 'I checked my inventory'\n else:\n return '{0} checked their inventory. '\n elif action['name'] == 'list_inventory':\n if 'past' in action:\n if descs[0] == 'You':\n return '{0} were {1}'\n else:\n return '{0} was {1}'\n else:\n return '{0} are {1}'\n\n def func(self, graph, args):\n room_id = graph.location(args[0])\n inv_text = graph.get_inventory_text_for(args[0])\n my_inv_action = {\n 'caller': self.get_name(),\n 'name': 'list_inventory',\n 'room_id': room_id,\n 'actors': [args[0]],\n 'add_descs': [inv_text],\n }\n graph.send_action(args[0], my_inv_action)\n return True\n\n\nclass HealthFunction(SoloFunction):\n def __init__(self):\n super().__init__(\n function_name=['health', 'status'],\n callback_triggers=[{'action': 'check_health', 'args': [0]}],\n )\n\n def get_action_observation_format(self, action, descs):\n if action['name'] == 'check_health':\n if descs[0] == 'You':\n return 'You checked your health. '\n elif descs[0] == 'I':\n return 'I checked my health. '\n else:\n return '{0} checked their health. '\n elif action['name'] == 'display_health':\n if 'past' in action:\n if descs[0] == 'You':\n return '{0} were feeling {1}. '\n else:\n return '{0} was feeling {1}. '\n else:\n if descs[0] == 'You':\n return '{0} are feeling {1}. '\n else:\n return '{0} is feeling {1}. '\n elif action['name'] == 'changed':\n return '{0} went from feeling {1} to feeling {2}. \\n'\n return super().get_action_observation_format(action, descs)\n\n def func(self, graph, args):\n room_id = graph.location(args[0])\n health_text = graph.health(args[0])\n my_health_action = {\n 'caller': self.get_name(),\n 'name': 'display_health',\n 'room_id': room_id,\n 'actors': [args[0]],\n 'add_descs': [health_text],\n }\n graph.send_action(args[0], my_health_action)\n return True\n\n\nclass LookFunction(SoloFunction):\n def __init__(self):\n super().__init__(\n function_name=['look', 'l'],\n callback_triggers=[{'action': 'looked', 'args': [0]}],\n )\n self.formats = {'looked': '{0} looked around. '}\n\n def func(self, graph, args):\n room_id = graph.location(args[0])\n\n # Prepare and send action for listing room contents\n is_return = room_id in graph._visited_rooms[args[0]]\n if is_return or not graph.has_prop(room_id, 'first_desc'):\n room_desc = graph.get_classed_prop(room_id, 'desc', args[0], None)\n else:\n room_desc = graph.get_classed_prop(room_id, 'first_desc', args[0])\n graph._visited_rooms[args[0]].add(room_id)\n if is_return or not graph.has_prop(room_id, 'first_desc'):\n agent_ids, agent_descs = graph.get_nondescribed_room_agents(room_id)\n object_ids, object_descs = graph.get_nondescribed_room_objects(room_id)\n _room_ids, room_descs = graph.get_room_edges(room_id)\n else:\n agent_ids, agent_descs = [], []\n object_ids, object_descs = [], []\n room_descs = []\n list_room_action = {\n 'caller': self.get_name(),\n 'name': 'list_room',\n 'room_id': room_id,\n 'actors': [args[0]],\n 'agent_ids': agent_ids,\n 'present_agent_ids': agent_ids,\n 'object_ids': object_ids,\n 'agent_descs': agent_descs,\n 'object_descs': object_descs,\n 'room_descs': room_descs,\n 'room_desc': room_desc,\n 'returned': False,\n }\n graph.send_action(args[0], list_room_action)\n return True\n\n def format_observation(\n self, graph, viewing_agent, action, telling_agent=None, is_constraint=False\n ):\n \"\"\"Return the observation text to display for an action for the case\n of look. Look is a special case, as the description can change more\n than just tense based on who or what was seen and who you tell it to.\n \"\"\"\n if action['name'] != 'list_room':\n return super().format_observation(\n graph, viewing_agent, action, telling_agent, is_constraint\n )\n room_desc = action['room_desc']\n object_descs = action['object_descs']\n object_ids = action['object_ids']\n ents = {object_descs[i]: object_ids[i] for i in range(len(object_ids))}\n agent_descs = action['agent_descs'][:]\n agent_ids = action['agent_ids']\n room_descs = action['room_descs']\n room = action['room_id']\n actor_id = action['actors'][0]\n returned = action['returned']\n\n if telling_agent is None:\n # Override for first description to set it to EXACTLY what was\n # given.\n has_actors = len(agent_ids) > 0\n if not has_actors:\n return room_desc\n\n try:\n # Remove viewing agent from the list (it's implied)\n i = agent_ids.index(viewing_agent)\n del agent_descs[i]\n except BaseException:\n pass\n if returned:\n s = 'You are back '\n else:\n s = 'You are '\n s += 'in {}.\\n'.format(graph.node_to_desc(room))\n if room_desc is not None:\n s += room_desc + '\\n'\n if len(object_ids) > 0:\n s += graph.get_room_object_text(object_descs, ents)\n if len(agent_descs) > 0:\n s += graph.get_room_agent_text(agent_descs)\n if len(room_descs) > 0:\n s += graph.get_room_edge_text(room_descs)\n return s\n else:\n is_present = room == graph.location(actor_id)\n\n if telling_agent in agent_ids:\n # Remove telling agent from descriptions (its implied)\n i = agent_ids.index(telling_agent)\n del agent_descs[i]\n del agent_ids[i]\n if telling_agent in agent_ids:\n # Replace telling agent with I (I was there)\n i = agent_ids.index(telling_agent)\n if i < len(agent_descs):\n agent_descs[i] = 'I'\n actor_desc = graph.node_to_desc(actor_id) + ' was'\n if actor_id == telling_agent:\n actor_desc = 'I am' if is_present else 'I was'\n elif actor_id == viewing_agent:\n actor_desc = 'You are' if is_present else 'You were'\n\n s = '{} in {}.\\n'.format(actor_desc, graph.node_to_desc(room))\n if room_desc is not None:\n s += room_desc + '\\n'\n s += graph.get_room_object_text(\n object_descs, ents, past=not is_present, give_empty=False\n )\n if viewing_agent in agent_ids:\n # Replace viewing agent with you were\n i = agent_ids.index(viewing_agent)\n del agent_descs[i]\n del agent_ids[i]\n s += 'You are here.\\n' if is_present else 'You were there.\\n'\n s += graph.get_room_agent_text(agent_descs, past=not is_present)\n s += graph.get_room_edge_text(room_descs, past=not is_present)\n return s\n\n\nclass UnfollowFunction(SoloFunction):\n def __init__(self):\n super().__init__(\n function_name=['unfollow'],\n callback_triggers=[{'action': 'stopped_following', 'args': [0]}],\n )\n self.formats = {\n 'unfollowed': '{0} stopped following {1}. ',\n 'failed': '{0} couldn\\'t follow that. ',\n }\n\n def func(self, graph, args):\n agent_id = args[0]\n room_id = graph.location(args[0])\n following = graph.get_following(agent_id)\n if following is None:\n graph.send_msg(agent_id, 'You are not following anyone.\\n')\n else:\n graph.set_follow(agent_id, None)\n unfollow_action = {\n 'caller': self.get_name(),\n 'name': 'unfollowed',\n 'room_id': room_id,\n 'actors': [args[0], following],\n }\n graph.broadcast_to_room(unfollow_action)\n return True\n\n\n# Constraints\nclass GraphConstraint(object):\n \"\"\"Stub class to define standard for graph constraints, implements shared\n code for executing them\n \"\"\"\n\n def format_observation(self, graph, viewing_agent, action, telling_agent=None):\n return format_observation(\n self, graph, viewing_agent, action, telling_agent, is_constraint=True\n )\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n \"\"\"Given the args, return an action to represent the failure of\n meeting this constraint\n \"\"\"\n raise NotImplementedError\n\n def get_action_observation_format(self, action, descs):\n \"\"\"Given the action, return text to be filled by the parsed args\"\"\"\n raise NotImplementedError\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Evaluates a constraint, returns true or false for if it is met\"\"\"\n raise NotImplementedError\n\n\nclass FitsConstraint(GraphConstraint):\n \"\"\"Determining if one object will fit into another\n\n args are:\n 0 => actor_id\n 1 => object_id\n 2 => container_id\n \"\"\"\n\n name = 'fits_in'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n # Special case for being unable to lift room objects\n if graph.get_prop(args[1], 'size') >= 150:\n return {\n 'caller': self.name,\n 'name': 'cant_lift',\n 'room_id': graph.location(args[0]),\n 'actors': args,\n }\n return {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args,\n }\n\n def get_action_observation_format(self, action, descs):\n if action['name'] == 'cant_carry':\n descs[2] = descs[2].capitalize()\n if 'past' in action:\n return '{2} couldn\\'t carry that much more'\n return '{2} can\\'t carry that much more. '\n if action['name'] == 'cant_lift':\n return '{1} isn\\'t something you can pick up'\n if 'past' in action:\n return '{1} didn\\'t fit. '\n elif descs[1] in ['You', 'I']:\n return '{1} do not fit. '\n else:\n return '{1} does not fit. '\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object would fit in the\n container\n \"\"\"\n return graph.obj_fits(args[1], args[2])\n\n\nclass IsTypeConstraint(GraphConstraint):\n \"\"\"Determining if an object has inherited a particular type\"\"\"\n\n name = 'is_type'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n action = {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args[:2],\n }\n if len(args) == 4:\n action['add_descs'] = [args[3]]\n return action\n\n def get_action_observation_format(self, action, descs):\n if len(descs) == 3:\n return descs[2]\n if 'past' in action:\n return 'I couldn\\'t find that. '\n else:\n return 'You couldn\\'t find that. '\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object has any wanted class\n\n args are:\n 0 => actor_id\n 1 => found_id\n 2 => expected_class/es\n 3 => alternate failure text\n \"\"\"\n found_id = args[1]\n expected_classes = args[2]\n if type(expected_classes) is not list:\n expected_classes = [expected_classes]\n obj_classes = graph.get_prop(found_id, 'classes')\n for want_class in expected_classes:\n if want_class in obj_classes:\n return True\n return False\n\n\nclass NotTypeConstraint(GraphConstraint):\n \"\"\"Determining if an object has inherited a particular type\"\"\"\n\n name = 'not_type'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n action = {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args[:2],\n }\n if len(args) == 4:\n action['add_descs'] = [args[3]]\n return action\n\n def get_action_observation_format(self, action, descs):\n if len(descs) == 3:\n return descs[2]\n if 'past' in action:\n return 'I couldn\\'t find that. '\n else:\n return 'You couldn\\'t find that. '\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object has any wanted class\n\n args are:\n 0 => actor_id\n 1 => found_id\n 2 => expected_class/es\n 3 => alternate failure text\n \"\"\"\n found_id = args[1]\n expected_classes = args[2]\n if type(expected_classes) is not list:\n expected_classes = [expected_classes]\n obj_classes = graph.get_prop(found_id, 'classes')\n for want_class in expected_classes:\n if want_class in obj_classes:\n return False\n return True\n\n\nclass HasPropConstraint(GraphConstraint):\n \"\"\"Determining if an object doesn't have a prop it should have\"\"\"\n\n name = 'has_prop'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n return {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args[:2],\n 'add_descs': [args[2]],\n }\n\n spec_attribute_map = {\n 'equipped': ['{1} had to be equipped first. ', '{1} has to be equipped first. ']\n }\n\n def get_action_observation_format(self, action, descs):\n if 'past' in action:\n if descs[2] in self.spec_attribute_map:\n return self.spec_attribute_map[descs[2]][0]\n return '{1} wasn\\'t {2}'\n else:\n if descs[2] in self.spec_attribute_map:\n return self.spec_attribute_map[descs[2]][1]\n return '{1} isn\\'t {2}'\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object doesn't have a prop\n\n args are:\n 0 => viewer\n 1 => prop_id\n 2 => bad_prop\n \"\"\"\n return graph.has_prop(args[1], args[2])\n\n\nclass NoPropConstraint(GraphConstraint):\n \"\"\"Determining if an object has a prop it shouldn't have\"\"\"\n\n name = 'no_prop'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n return {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args[:2],\n 'add_descs': [args[2]],\n }\n\n spec_attribute_map = {\n 'equipped': ['{1} had to be put away first. ', '{1} has to be put away first. ']\n }\n\n def get_action_observation_format(self, action, descs):\n if 'past' in action:\n if descs[2] in self.spec_attribute_map:\n return self.spec_attribute_map[descs[2]][0]\n return '{1} was {2}'\n else:\n if descs[2] in self.spec_attribute_map:\n return self.spec_attribute_map[descs[2]][1]\n return '{1} is {2}'\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object doesn't have a prop\n\n args are:\n 0 => viewer\n 1 => prop_id\n 2 => bad_prop\n \"\"\"\n return not graph.has_prop(args[1], args[2])\n\n\nclass LockableConstraint(GraphConstraint):\n \"\"\"Determining if a path has a particular status\n\n args are:\n 0 => actor_id\n 1 => target_id\n 2 => should be lockable\n \"\"\"\n\n name = 'is_lockable'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n return {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args[:2],\n 'add_descs': [args[2]],\n }\n\n def get_action_observation_format(self, action, descs):\n if descs[2]: # Failed when it was supposed to be lockable\n return '{1} can\\'t be locked! '\n else:\n return '{1} is lockable. '\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object would fit in the\n container\n \"\"\"\n actor_id, target_id, want_lockable = args[0], args[1], args[2]\n if 'room' in graph.get_prop(target_id, 'classes'):\n room_id = graph.location(actor_id)\n is_lockable = graph.get_path_locked_with(room_id, target_id) is not None\n else:\n is_lockable = graph.get_prop(target_id, 'lockable', False)\n return want_lockable == is_lockable\n\n\nclass LockedConstraint(GraphConstraint):\n \"\"\"Determining if a path has a particular status\n\n args are:\n 0 => actor_id\n 1 => target_id\n 2 => should be locked\n \"\"\"\n\n name = 'is_locked'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n return {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args[:2],\n 'add_descs': [args[2]],\n }\n\n def get_action_observation_format(self, action, descs):\n if descs[2]: # Failed when it was supposed to be locked\n return '{1} is unlocked. '\n else:\n return '{1} is locked. '\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object would fit in the\n container\n \"\"\"\n actor_id, target_id, want_locked = args[0], args[1], args[2]\n if 'room' in graph.get_prop(target_id, 'classes'):\n room_id = graph.location(actor_id)\n if room_id == target_id:\n return True\n is_locked = graph.path_is_locked(room_id, target_id)\n else:\n is_locked = graph.get_prop(target_id, 'locked', False)\n return want_locked == is_locked\n\n\nclass LockedWithConstraint(GraphConstraint):\n \"\"\"Determining if a path has a particular status\n\n args are:\n 0 => actor_id\n 1 => target_id\n 2 => key_id\n \"\"\"\n\n name = 'locked_with'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n item_desc = graph.node_to_desc(args[2])\n return {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args[:2],\n 'add_descs': [item_desc],\n }\n\n def get_action_observation_format(self, action, descs):\n descs[2] = descs[2].capitalize()\n return '{2} doesn\\'t work with that. '\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object would fit in the\n container\n \"\"\"\n actor_id, target_id, key_id = args[0], args[1], args[2]\n if 'room' in graph.get_prop(target_id, 'classes'):\n room_id = graph.location(actor_id)\n locked_with = graph.get_path_locked_with(room_id, target_id)\n else:\n locked_with = graph.get_prop(target_id, 'locked_with', False)\n return locked_with == key_id\n\n\nclass NotLocationOfConstraint(GraphConstraint):\n \"\"\"Ensuring a location isn't the same one as the actor\n\n args are:\n 0 => actor_id\n 1 => target_id\n \"\"\"\n\n name = 'not_location_of'\n\n def get_failure_action(self, graph, args, spec_fail='failed'):\n return {\n 'caller': self.name,\n 'name': spec_fail,\n 'room_id': graph.location(args[0]),\n 'actors': args,\n 'add_descs': [],\n }\n\n def get_action_observation_format(self, action, descs):\n return \"You're already in that location. \"\n\n def evaluate_constraint(self, graph, args):\n \"\"\"Return true or false for whether the object would fit in the\n container\n \"\"\"\n actor_id, target_id = args[0], args[1]\n return graph.location(actor_id) != target_id\n\n\ncon_list = [\n FitsConstraint(),\n IsTypeConstraint(),\n HasPropConstraint(),\n NoPropConstraint(),\n LockableConstraint(),\n LockedConstraint(),\n LockedWithConstraint(),\n NotLocationOfConstraint(),\n NotTypeConstraint(),\n]\nfunc_list = [\n MoveAgentFunction(),\n GetObjectFunction(),\n PutObjectInFunction(),\n DropObjectFunction(),\n GiveObjectFunction(),\n StealObjectFunction(),\n WearObjectFunction(),\n WieldObjectFunction(),\n RemoveObjectFunction(),\n WaitFunction(),\n InventoryFunction(),\n HealthFunction(),\n EatFunction(),\n DrinkFunction(),\n LookFunction(),\n LockFunction(),\n UnlockFunction(),\n ExamineFunction(),\n FollowFunction(),\n UnfollowFunction(),\n HitFunction(),\n TellFunction(),\n HugFunction(),\n # UseFunction(),\n SayFunction(),\n]\nCONSTRAINTS = {c.name: c for c in con_list}\n\n# Construct list of graph functions by usable names\nCANNONICAL_GRAPH_FUNCTIONS = {}\nfor f in func_list:\n names = f.name\n if type(names) is str:\n names = [names]\n for name in names:\n GRAPH_FUNCTIONS[name] = f\n CANNONICAL_GRAPH_FUNCTIONS[names[0]] = f\n\n# Functions for the possible action parser to ignore\nFUNC_IGNORE_LIST = ['tell', 'say']\n\n\nclass Graph(object):\n def __init__(self, opt):\n \"\"\"\n Initialize a graph for the game to run on. Creates all of the\n required bookkeeping members and initializes them to empty. Most\n members of the graph are keyed by a node's unique ids.\n\n Development of this graph is very much still a work in progress,\n and it is only provided in this form to be used for the light_dialog\n task as collected in the 'Learning to Speak and Act in a Fantasy\n Text Adventure Game' paper\n \"\"\"\n\n # callbacks hold custom registered functions for the graph to execute\n # under predefined constraints\n self.callbacks = {}\n # Variables can be tied to custom callbacks to track custom variables\n # that are parts of the graph state\n self.variables = {}\n\n # ParlAI opt\n self._opt = opt\n\n # Dict of edges from a given node, in the format of\n # (edge_type, target) -> dict of options for that pair. This format\n # is subject to change, but new versions will include conversion\n # functions\n self._node_to_edges = {}\n # Dict of properties from a given node, in the format of\n # prop_name -> value\n self._node_to_prop = {}\n # dict of node -> node for what nodes are contained in what\n self._node_contained_in = {}\n # dict of node -> node list for what nodes a node contains\n self._node_contains = {}\n # dict of node -> node for what nodes a node is following\n self._node_follows = {}\n # dict of node -> node list for what nodes a node is following\n self._node_followed_by = {}\n # dict of node -> string description for that node\n self._node_to_desc = {}\n\n # dict of node -> set of room ids that that agent has visited so far\n self._visited_rooms = {}\n # dict of node -> immediately previous room id the agent has been in.\n # to enable \"go back\"\n self._last_rooms = {}\n # dict of node -> agent for the last agent that an actor used a tell\n # command on. Useful for trying to determine who an agent is talking\n # to once they start using say rather than tell.\n self._last_tell_target = {}\n\n # non-player characters that we move during update_world func.\n self._node_npcs = set()\n # flag for if the graph is to be frozen, stopping time steps\n self._node_freeze = False\n # count of nodes in the graph\n self._cnt = 0\n\n # buffers for holding actions until an agent is able to observe them\n self._node_to_text_buffer = {}\n self._node_to_observations = {}\n\n # node ids that can be associated with an agent\n self._player_ids = []\n # node ids of the player_ids that have already been registered to by\n # an agent\n self._used_player_ids = []\n\n # special member function to register callback events to\n # _node_to_text_buffer and _node_to_observations for cases where\n # polling the graph is not appropriate\n self.__message_callbacks = {}\n\n # global variable for if NPCs should respond to Says or only Tells\n self.npc_say_respond = True\n\n # -- Graph properties -- #\n\n def copy(self):\n \"\"\"return a copy of this graph\"\"\"\n return deepcopy(self)\n\n def __deepcopy__(self, memo):\n cls = self.__class__\n result = cls.__new__(cls)\n memo[id(self)] = result\n for k, v in self.__dict__.items():\n if '__message_callbacks' not in k: # we cant copy callback anchors\n setattr(result, k, deepcopy(v, memo))\n else:\n setattr(result, k, {})\n return result\n\n def populate_ids(self):\n self.object_ids = self.get_all_by_prop('object')\n self.container_ids = self.get_all_by_prop('container')\n self.agent_ids = self.get_all_by_prop('agent')\n\n def unique_hash(self):\n # TODO: make it independent of specific world settings\n # TODO: Improve everything about this, it's really old\n # object_ids, agent_ids, and container_ids are set by construct_graph\n self.populate_ids()\n s = ''\n apple_s = []\n for id in self.object_ids + self.container_ids + self.agent_ids:\n cur_s = ''\n if not self.node_exists(id):\n cur_s += 'eaten'\n else:\n cur_s += self._node_contained_in[id]\n for prop in ['wielding', 'wearing', 'dead']:\n if prop in self._node_to_prop[id]:\n cur_s += prop\n if self.node_to_desc_raw(id) == 'apple':\n apple_s.append(cur_s)\n else:\n s += cur_s\n s += ''.join(sorted(apple_s))\n return s\n\n def __eq__(self, other):\n return self.unique_hash() == other.unique_hash()\n\n def all_node_ids(self):\n \"\"\"return a list of all the node ids in the graph\"\"\"\n return list(self._node_to_prop.keys())\n\n def freeze(self, freeze=None):\n if freeze is not None:\n self._node_freeze = freeze\n return self._node_freeze\n\n def version(self):\n return 3\n\n def add_message_callback(self, id, func):\n \"\"\"\n Register a message callback to a given agent by their node id. This\n function will be called on the graph and an action when the subscribed\n actor is the subject of an action\n \"\"\"\n self.__message_callbacks[id] = func\n\n def has_remaining_player_slots(self):\n \"\"\"Note if the graph has any space for new players to play a role\"\"\"\n return len(self._player_ids) != 0\n\n def get_unused_player_id(self):\n \"\"\"\n Return one of the unused player ids randomly and mark it as registered\n \"\"\"\n player_id = random.choice(self._player_ids)\n self._player_ids.remove(player_id)\n self._used_player_ids.append(player_id)\n return player_id\n\n # -- Callbacks and variables -- #\n\n def register_callbacks(self, callbacks, variables):\n \"\"\" Documentation not yet available\"\"\"\n self.callbacks = callbacks\n self.variables = variables\n\n # -- Full node editors/creators/getters/deleters -- #\n\n def get_player(self, id):\n \"\"\"Get the state of a player (along with everything they carry) from\n the graph\n \"\"\"\n state = {}\n state['id'] = id\n if id in self._node_to_text_buffer:\n state['node_to_text_buffer'] = self._node_to_text_buffer[id]\n if id in self._node_contains:\n state['node_contains'] = self._node_contains[id]\n state['contained_nodes'] = []\n for obj_id in self._node_contains[id]:\n props = self._node_to_prop[obj_id]\n if 'persistent' in props and props['persistent'] == 'level':\n continue # Leave level-based items behind\n state['contained_nodes'].append(self.get_obj(obj_id))\n if id in self._node_to_prop:\n state['node_to_prop'] = self._node_to_prop[id]\n if id in self._node_to_desc:\n state['node_to_desc'] = self._node_to_desc[id]\n return state\n\n def get_obj(self, id):\n \"\"\"Get the state of an object from the graph\"\"\"\n state = {}\n state['id'] = id\n if id in self._node_contains:\n state['node_contains'] = self._node_contains[id]\n state['contained_nodes'] = []\n for obj_id in self._node_contains[id]:\n state['contained_nodes'].append(self.get_obj(obj_id))\n if id in self._node_to_prop:\n state['node_to_prop'] = self._node_to_prop[id]\n if id in self._node_contained_in:\n state['node_contained_in'] = self._node_contained_in[id]\n if id in self._node_to_desc:\n state['node_to_desc'] = self._node_to_desc[id]\n return state\n\n def set_player(self, state):\n \"\"\"Instantiate a player into the graph with the given state\"\"\"\n id = state['id']\n if 'node_to_text_buffer' in state:\n self._node_to_text_buffer[id] = (\n state['node_to_text_buffer'] + self._node_to_text_buffer[id]\n )\n if 'node_contains' in state:\n self._node_contains[id] = state['node_contains']\n for obj_state in state['contained_nodes']:\n self.set_obj(obj_state)\n if 'node_to_prop' in state:\n self._node_to_prop[id] = state['node_to_prop']\n\n def set_obj(self, state):\n \"\"\"Instantiate an object into the graph with the given state\"\"\"\n id = state['id']\n self._node_to_edges[id] = []\n self._node_to_prop[id] = state['node_to_prop']\n self._node_contains[id] = state['node_contains']\n for obj_state in state['contained_nodes']:\n self.set_obj(obj_state)\n self._node_to_desc[id] = state['node_to_desc']\n self._node_contained_in[id] = state['node_contained_in']\n\n def add_node(self, desc, props, is_player=False, uid=''):\n id = desc.lower()\n if id != 'dragon' and not is_player:\n id = \"{}_{}\".format(id, self._cnt)\n if uid != '':\n id += '_{}'.format(uid)\n self._cnt = self._cnt + 1\n if id in self._node_to_edges:\n return False\n self._node_to_edges[id] = {}\n if type(props) == str:\n self._node_to_prop[id] = {}\n self._node_to_prop[id][props] = True\n self.set_prop(id, 'classes', [props])\n elif type(props) == dict:\n self._node_to_prop[id] = {}\n for p in props:\n self._node_to_prop[id][p] = props[p]\n else:\n self._node_to_prop[id] = {}\n for p in props:\n self._node_to_prop[id][p] = True\n if self._node_to_prop[id].get('names') is None:\n self._node_to_prop[id]['names'] = [desc]\n self._node_to_prop[id]['is_player'] = is_player\n self._node_contains[id] = set()\n self._node_to_desc[id] = desc\n if 'agent' in self._node_to_prop[id]['classes'] or is_player:\n if not self.has_prop(id, 'health'):\n self.set_prop(id, 'health', 2)\n self.new_agent(id)\n if is_player:\n self._player_ids.append(id)\n return id\n\n def new_agent(self, id):\n \"\"\"\n Initialize special state for the given agent\n \"\"\"\n self._node_to_text_buffer[id] = '' # clear buffer\n self._node_to_observations[id] = [] # clear buffer\n self._visited_rooms[id] = set()\n self._last_rooms[id] = None\n self._last_tell_target[id] = None\n\n def delete_node(self, id):\n \"\"\"Remove a node from the graph, keeping the reference for printing\"\"\"\n # Remove from the container\n loc = self.location(id)\n if loc is not None and id in self._node_contains[loc]:\n self._node_contains[self.location(id)].remove(id)\n # remove size from above object, then remove contained in edge\n above_id = self.node_contained_in(id)\n if above_id is not None:\n size = self.get_prop(id, 'size')\n omax_size = self.get_prop(above_id, 'contain_size')\n omax_size = omax_size + size\n self.set_prop(above_id, 'contain_size', omax_size)\n rm(self._node_contained_in, id)\n # all things inside this are zapped too\n if id in self._node_contains:\n objs = deepcopy(self._node_contains[id])\n for o in objs:\n self.delete_node(o)\n # now remove edges from other rooms\n for r in self._node_to_edges[id]:\n if r[0] == 'path_to':\n self._node_to_edges[r[1]].remove(['path_to', id])\n # stop all agents from following this one\n if id in self._node_followed_by:\n ags = deepcopy(self._node_followed_by[id])\n for a in ags:\n self.set_follow(a, None)\n rm(self._node_follows, id)\n # Remove from npc list\n if id in self._node_npcs:\n self._node_npcs.remove(id)\n\n # -- Node-in-graph properties -- #\n\n def add_edge(\n self,\n id1,\n edge,\n id2,\n edge_label=None,\n locked_with=None,\n edge_desc=None,\n full_label=False,\n ):\n \"\"\"Add an edge of the given type from id1 to id2. Optionally can set\n a label for that edge\n \"\"\"\n if edge_desc is None:\n edge_desc = self.get_props_from_either(id2, id1, 'path_desc')[0]\n if (edge, id2) not in self._node_to_edges[id1]:\n self._node_to_edges[id1][(edge, id2)] = {\n 'label': edge_label,\n 'examine_desc': edge_desc,\n # TODO get these from the lock or something idk\n 'locked_desc': edge_desc,\n 'unlocked_desc': edge_desc,\n 'locked_with': locked_with,\n 'is_locked': False,\n 'full_label': full_label,\n }\n\n def add_one_path_to(\n self, id1, id2, label=None, locked_with=None, desc=None, full_label=False\n ):\n if id1 == id2:\n return False\n self.add_edge(id1, 'path_to', id2, label, locked_with, desc, full_label)\n return True\n\n def add_path_to(\n self,\n id1,\n id2,\n desc1=None,\n desc2=None,\n locked_with=None,\n examine1=None,\n examine2=None,\n ):\n \"\"\"Create a path between two rooms\"\"\"\n if id1 == id2:\n return False\n self.add_edge(id1, 'path_to', id2, desc1, locked_with, examine1)\n self.add_edge(id2, 'path_to', id1, desc2, locked_with, examine2)\n return True\n\n def is_path_to(self, id1, id2):\n \"\"\"determine if there is a path from id1 to id2\"\"\"\n return ('path_to', id2) in self._node_to_edges[id1]\n\n def node_contains(self, loc):\n \"\"\"Get the set of all things that a node contains\"\"\"\n if loc in self._node_contains:\n return set(self._node_contains[loc])\n else:\n return set()\n\n def add_contained_in(self, id1, id2):\n if id1 in self._node_contained_in:\n i_am_in = self._node_contained_in[id1]\n self._node_contains[i_am_in].remove(id1)\n self._node_contained_in[id1] = id2\n self._node_contains[id2].add(id1)\n return True\n\n def node_contained_in(self, id):\n if id not in self._node_contained_in:\n return None\n return self._node_contained_in[id]\n\n def set_follow(self, id1, id2):\n \"\"\"Set id1 to be following id2, unfollowing whatever id1 followed\n before if necessary\n \"\"\"\n if id1 in self._node_follows:\n i_follow = self._node_follows[id1]\n self._node_followed_by[i_follow].remove(id1)\n if id2 is not None:\n self._node_follows[id1] = id2\n if id2 not in self._node_followed_by:\n self._node_followed_by[id2] = set()\n self._node_followed_by[id2].add(id1)\n return True\n else:\n if id1 in self._node_follows:\n self._node_follows.pop(id1)\n\n def get_followers(self, agent_id):\n \"\"\"Get the nodes following the given agent\"\"\"\n if agent_id in self._node_followed_by:\n return self._node_followed_by[agent_id]\n return []\n\n def get_following(self, agent_id):\n \"\"\"get the node that the given agent is following, if any\"\"\"\n if agent_id in self._node_follows:\n return self._node_follows[agent_id]\n return None\n\n def combine_classed_descs(descs):\n adj_descs = [{'default': d} if type(d) is str else d for d in descs]\n last_round_descs = {'default': ''}\n for desc_set in [adj_descs]:\n round_descs = {}\n for class_name in desc_set:\n if class_name not in last_round_descs:\n old_d = last_round_descs['default'].strip()\n new_d = desc_set[class_name].strip()\n round_descs[class_name] = (old_d + ' ' + new_d).strip()\n else:\n old_d = last_round_descs[class_name].strip()\n new_d = desc_set[class_name].strip()\n round_descs[class_name] = (old_d + ' ' + new_d).strip()\n last_round_descs = round_descs\n return last_round_descs\n\n def lock_path(self, id1, id2, key_id):\n \"\"\"lock the edge from id1 to id2 using the given key\"\"\"\n self._node_to_edges[id1][('path_to', id2)]['is_locked'] = True\n self._node_to_edges[id1][('path_to', id2)][\n 'examine_desc'\n ] = self._node_to_edges[id1][('path_to', id2)]['locked_desc']\n self._node_to_edges[id2][('path_to', id1)]['is_locked'] = True\n self._node_to_edges[id2][('path_to', id1)][\n 'examine_desc'\n ] = self._node_to_edges[id2][('path_to', id1)]['locked_desc']\n\n def unlock_path(self, id1, id2, key_id):\n \"\"\"unlock the edge from id1 to id2 using the given key\"\"\"\n self._node_to_edges[id1][('path_to', id2)]['is_locked'] = False\n self._node_to_edges[id1][('path_to', id2)][\n 'examine_desc'\n ] = self._node_to_edges[id1][('path_to', id2)]['unlocked_desc']\n self._node_to_edges[id2][('path_to', id1)]['is_locked'] = False\n self._node_to_edges[id2][('path_to', id1)][\n 'examine_desc'\n ] = self._node_to_edges[id2][('path_to', id1)]['unlocked_desc']\n\n def path_is_locked(self, id1, id2):\n return self._node_to_edges[id1][('path_to', id2)]['is_locked']\n\n def get_path_locked_with(self, id1, id2):\n if id1 == id2:\n # TODO get the locked_with of a room when the path is to itself\n # as this function shouldn't be called like this\n return None\n return self._node_to_edges[id1][('path_to', id2)]['locked_with']\n\n def set_desc(self, id, desc):\n self._node_to_desc[id] = desc\n\n def node_exists(self, id):\n return id in self._node_contained_in\n\n # -- Prop accessors -- #\n\n def get_prop(self, id, prop, default=None):\n \"\"\"Get the given prop, return None if it doesn't exist\"\"\"\n if id in self._node_to_prop:\n if prop in self._node_to_prop[id]:\n return self._node_to_prop[id][prop]\n return default\n\n def extract_classed_from_dict(self, prop_d, viewer=None, default=None):\n if type(prop_d) is not dict:\n if prop_d is None:\n return default\n return prop_d\n if viewer is not None:\n viewer_class = self.get_prop(viewer, 'class')\n if viewer_class in prop_d:\n return prop_d[viewer_class]\n for viewer_class in self.get_prop(viewer, 'classes'):\n if viewer_class in prop_d:\n return prop_d[viewer_class]\n if 'default' not in prop_d:\n return default\n return prop_d['default']\n\n def get_classed_prop(self, id, prop, viewer, default=None):\n prop_d = self.get_prop(id, prop)\n val = self.extract_classed_from_dict(prop_d, viewer, default)\n if type(val) is dict and 'iter' in val:\n i = val['iter']\n val['iter'] = (i + 1) % len(val['data'])\n return val['data'][i]\n return val\n\n def get_props_from_either(self, id1, id2, prop):\n \"\"\"Try to get ones own prop, fallback to other's prop. Do this for\n both provided ids symmetrically\"\"\"\n resp1 = self.get_prop(id1, prop, self.get_prop(id2, prop))\n resp2 = self.get_prop(id2, prop, self.get_prop(id1, prop))\n return resp1, resp2\n\n def set_prop(self, id, prop, val=True):\n \"\"\"Set a prop to a given value, True otherwise\"\"\"\n if id in self._node_to_prop:\n self._node_to_prop[id][prop] = val\n\n def has_prop(self, id, prop):\n \"\"\"Return whether or not id has the given prop\"\"\"\n if self.get_prop(id, prop) is not None:\n return True\n return False\n\n def inc_prop(self, id, prop, val=1):\n \"\"\"Increment a given prop by the given value\"\"\"\n if id in self._node_to_prop:\n if prop not in self._node_to_prop[id]:\n self.set_prop(id, prop, 0)\n if type(self._node_to_prop[id][prop]) != int:\n self.set_prop(id, prop, 0)\n self._node_to_prop[id][prop] += val\n\n def delete_prop(self, id, prop):\n \"\"\"Remove a prop from the node_to_prop map\"\"\"\n if id in self._node_to_prop:\n if prop in self._node_to_prop[id]:\n del self._node_to_prop[id][prop]\n\n def add_class(self, object_id, class_name):\n curr_classes = self.get_prop(object_id, 'classes')\n curr_classes.append(class_name)\n\n def remove_class(self, object_id, class_name):\n curr_classes = self.get_prop(object_id, 'classes')\n curr_classes.remove(class_name)\n\n # -- Graph locators -- #\n\n def location(self, thing):\n \"\"\"Get whatever the immediate container of a node is\"\"\"\n if thing in self._node_contained_in:\n return self._node_contained_in[thing]\n else:\n return None\n\n def room(self, thing):\n \"\"\"Get the room that contains a given node\"\"\"\n if thing not in self._node_contained_in:\n return None\n id = self._node_contained_in[thing]\n while not self.get_prop(id, 'room'):\n id = self._node_contained_in[id]\n return id\n\n def desc_to_nodes(self, desc, nearbyid=None, nearbytype=None):\n \"\"\"Get nodes nearby to a given node from that node's perspective\"\"\"\n from_id = self.location(nearbyid)\n if nearbyid is not None:\n o = set()\n if 'all' in nearbytype and 'here' in nearbytype:\n o = self.get_local_ids(nearbyid)\n else:\n if 'path' in nearbytype:\n o1 = self.node_path_to(from_id)\n o = set(o).union(o1).union([from_id])\n if 'carrying' in nearbytype:\n o = set(o).union(set(self.node_contains(nearbyid)))\n if 'sameloc' in nearbytype:\n o1 = set(self.node_contains(from_id))\n o = o.union(o1)\n if 'all' in nearbytype:\n o1 = self.node_contains(nearbyid)\n o2 = self.node_contains(from_id)\n o3 = self.node_path_to(from_id)\n o = o.union(o1).union(o2).union(o3)\n if 'contains' in nearbytype:\n o = o.union({self.location(nearbyid)})\n if 'players' in nearbytype:\n o = o.union(self._used_player_ids)\n if 'others' in nearbytype:\n for item in o:\n if self.get_prop(item, 'agent') or self.get_prop(\n item, 'container'\n ):\n o = o.union(self.node_contains(item))\n # if len(o) == 0:\n # o1 = self.node_contains(nearbyid)\n # o2 = self.node_contains(self.location(nearbyid))\n # o = o1.union(o2)\n else:\n o = set(self._node_to_desc.keys())\n # Go through official in-game names\n if nearbyid is not None and self.room(nearbyid) in o and desc == 'room':\n return [self.room(nearbyid)]\n\n found_pairs = [(id, self.node_to_desc(id, from_id=from_id).lower()) for id in o]\n valid_ids_1 = [\n (id, name) for (id, name) in found_pairs if desc.lower() in name + 's'\n ]\n\n # Check the parent name trees for names that also could match in the\n # case that nothing could be found\n all_subnames = [(id, self.get_prop(id, 'names')) for id in o]\n all_pairs = [\n (id, name) for (id, name_list) in all_subnames for name in name_list\n ]\n valid_ids_2 = [\n (id, name) for (id, name) in all_pairs if desc.lower() in name + 's'\n ]\n\n valid_ids_1.sort(key=lambda x: len(x[0]))\n valid_ids_2.sort(key=lambda x: len(x[1]))\n valid_ids = valid_ids_1 + valid_ids_2\n valid_ids = [id for (id, _name) in valid_ids]\n return valid_ids\n\n def get_all_by_prop(self, prop):\n objects = self.all_node_ids()\n return [id for id in objects if self.get_prop(id, prop)]\n\n def node_path_to(self, id):\n if id is None:\n return []\n rooms = self._node_to_edges[id]\n rooms = [r[1] for r in rooms if r[0] == 'path_to']\n return rooms\n\n def get_actionable_ids(self, actor_id):\n o = self.get_local_ids(actor_id)\n new_o = set(o)\n for obj in o:\n if self.get_prop(obj, 'container') or self.get_prop(obj, 'agent'):\n new_o = new_o.union(self.node_contains(obj))\n return new_o\n\n def get_local_ids(self, actor_id):\n \"\"\"Return all accessible ids for an actor given the current area\"\"\"\n loc = self.location(actor_id)\n o1 = self.node_contains(actor_id)\n o2 = self.node_contains(loc)\n o3 = self.node_path_to(loc)\n o4 = [loc]\n local_ids = o1.union(o2).union(o3).union(o4)\n check_local_ids = list(local_ids)\n for pos_id in check_local_ids:\n if self.get_prop(pos_id, 'examined'):\n local_ids = local_ids.union(self.node_contains(pos_id))\n return local_ids\n\n # -- Text creators -- #\n\n def get_inventory_text_for(self, id, give_empty=True):\n \"\"\"Get a description of what id is carrying or equipped with\"\"\"\n s = ''\n carry_ids = []\n wear_ids = []\n wield_ids = []\n for o in self.node_contains(id):\n if self.get_prop(o, 'equipped'):\n if 'wearable' in self.get_prop(o, 'classes'):\n wear_ids.append(o)\n elif 'weapon' in self.get_prop(o, 'classes'):\n wield_ids.append(o)\n else:\n carry_ids.append(o)\n if len(carry_ids) == 0:\n if not give_empty:\n return ''\n s += 'carrying nothing'\n else:\n s += 'carrying ' + self.display_node_list(carry_ids)\n if len(wear_ids) > 0:\n s += ',\\n'\n if len(wield_ids) == 0:\n s += 'and '\n s += 'wearing ' + self.display_node_list(wear_ids)\n if len(wield_ids) > 0:\n s += ',\\nand wielding ' + self.display_node_list(wield_ids)\n return s + '.'\n\n def health(self, id):\n \"\"\"Return the text description of someone's numeric health\"\"\"\n health = self.get_prop(id, 'health')\n if health is None or health is False:\n health = 1\n if health > 8:\n health = 8\n f = [\n 'dead',\n 'on the verge of death',\n 'very weak',\n 'weak',\n 'ok',\n 'good',\n 'strong',\n 'very strong',\n 'nigh on invincible',\n ]\n return f[int(health)]\n\n # -- Text accessors -- #\n\n def get_action_history(self, agent_id):\n observations = self._node_to_observations[agent_id]\n self._node_to_observations[agent_id] = []\n return observations\n\n def node_to_desc(self, id, from_id=False, use_the=False):\n if from_id:\n # A description of something (right now, a location)\n # from another location.\n # This gets the description from the path edge.\n path_desc = self.path_to_desc(id, from_id)\n if path_desc is not False:\n if path_desc.startswith('the') or path_desc.startswith('a'):\n return path_desc\n return 'the ' + path_desc\n\n if id in self._node_to_desc:\n ent = self._node_to_desc[id]\n if self.get_prop(id, 'capitalize', False) is True:\n ent = ent.capitalize()\n if self.has_prop(id, 'dead'):\n ent = 'dead ' + ent\n if self.has_prop(id, 'player_name'):\n ent = self.get_prop(id, 'player_name')\n elif self.has_prop(id, 'agent') or self.has_prop(id, 'object'):\n prefix = self.name_prefix(id, ent, use_the)\n if prefix != '':\n ent = prefix + ' ' + ent\n elif self.has_prop(id, 'room'):\n prefix = self.name_prefix(id, ent, use_the)\n if prefix != '':\n ent = prefix + ' ' + ent\n else:\n ent = 'the ' + ent\n return ent\n else:\n return id\n\n def get_path_ex_desc(self, id1, id2, looker_id=None):\n \"\"\"Return a path description. If both ids are the same return the\n room description instead.\n \"\"\"\n if id1 == id2:\n if looker_id is not None:\n desc = self.get_classed_prop(id1, 'desc', looker_id)\n extra_desc = self.get_classed_prop(id1, 'extra_desc', looker_id)\n return extra_desc if extra_desc is not None else desc\n desc = self.get_prop(id1, 'desc')\n return self.get_prop(id1, 'extra_desc', desc)\n desc_set = self._node_to_edges[id1][('path_to', id2)]['examine_desc']\n val = self.extract_classed_from_dict(desc_set, looker_id)\n if type(val) is dict and 'iter' in val:\n i = val['iter']\n val['iter'] = (i + 1) % len(val['data'])\n return val['data'][i]\n return val\n\n def path_to_desc(self, id1, id2):\n \"\"\"get the description for a path from the perspective of id2\"\"\"\n rooms = self._node_to_edges[id2]\n for r in rooms:\n if r[0] == 'path_to' and r[1] == id1:\n if 'label' in rooms[r] and rooms[r]['label'] is not None:\n if rooms[r]['full_label']:\n return rooms[r]['label']\n else:\n return 'a path to the ' + rooms[r]['label']\n return False\n\n def node_to_desc_raw(self, id, from_id=False):\n if from_id:\n path_desc = self.path_to_desc(id, from_id)\n if path_desc is not False:\n return path_desc\n return self._node_to_desc[id]\n\n def name_prefix(self, id, txt, use_the):\n \"\"\"Get the prefix to prepend an object with in text form\"\"\"\n # Get the preferred prefix type.\n pre = self.get_prop(id, 'name_prefix')\n\n if pre == '':\n return pre\n\n if use_the is True:\n return 'the'\n\n if pre is False or pre is None or pre == 'auto':\n txt = 'an' if txt[0] in ['a', 'e', 'i', 'o', 'u'] else 'a'\n return txt\n return pre\n\n # -- Messaging commands -- #\n\n def send_action(self, agent_id, action):\n \"\"\"Parse the action and send it to the agent with send_msg\"\"\"\n if action['caller'] is None:\n val = self.extract_classed_from_dict(action['txt'], agent_id, '')\n if type(val) is dict and 'iter' in val:\n i = val['iter']\n val['iter'] = (i + 1) % len(val['data'])\n extracted_text = val['data'][i]\n else:\n extracted_text = val\n self.send_msg(agent_id, extracted_text, action)\n return\n try:\n func_wrap = GRAPH_FUNCTIONS[action['caller']]\n except BaseException:\n func_wrap = CONSTRAINTS[action['caller']]\n try:\n t = func_wrap.format_observation(self, agent_id, action).rstrip()\n except Exception:\n return # the agent doesn't accept observations\n t += ' '\n self.send_msg(agent_id, t, action)\n\n def send_msg(self, agent_id, txt, action=None):\n \"\"\"Send an agent an action and a message\"\"\"\n if agent_id in self._node_to_text_buffer:\n if action is None:\n action = {\n 'caller': None,\n 'room_id': self.location(agent_id),\n 'txt': txt,\n }\n\n if not hasattr(self, '_node_to_observations'):\n # TODO remove when all the samples are converted\n self._node_to_observations = {}\n if agent_id not in self._node_to_observations:\n self._node_to_observations[agent_id] = []\n self._node_to_observations[agent_id].append(action)\n self._node_to_text_buffer[agent_id] += txt\n if agent_id in self.__message_callbacks:\n self.__message_callbacks[agent_id](self, action)\n\n def broadcast_to_room(self, action, exclude_agents=None, told_by=None):\n \"\"\"send a message to everyone in a room\"\"\"\n if exclude_agents is None:\n exclude_agents = []\n else:\n exclude_agents = list(exclude_agents)\n\n agents_list, _descs = self.get_room_agents(action['room_id'])\n agents = set(agents_list)\n if 'actors' in action:\n # send message to the actor first\n actor = action['actors'][0]\n if actor in agents and actor not in exclude_agents:\n self.send_action(actor, action)\n exclude_agents.append(actor)\n\n action['present_agent_ids'] = agents\n for a in agents:\n if a in exclude_agents:\n continue\n self.send_action(a, action)\n\n # ----------------------------------------------------------------\n # TODO: Ideally, all functions below do not use the graph structure\n # directly but only the accessor functions (should not use self._node_* ).\n\n # -- Helpers -- #\n\n def clean_props(self, object_id):\n \"\"\"ensures all necessary props are set on items that might not have\n been on earlier versions of graphworld\n \"\"\"\n # TODO remove when all samples are converted\n size = self.get_prop(object_id, 'size')\n if size is None or type(size) == bool:\n self.set_prop(object_id, 'size', 1)\n contain_size = self.get_prop(object_id, 'contain_size')\n if contain_size is None or type(contain_size) == bool:\n self.set_prop(object_id, 'contain_size', 3)\n classes = self.get_prop(object_id, 'classes')\n if type(classes) == str:\n self.set_prop(object_id, 'classes', [classes])\n elif type(classes) != list:\n self.set_prop(object_id, 'classes', [])\n\n # -- Commands -- #\n\n def create(self, agent_id, params):\n # -- create commands: --\n # *create room kitchen -> creates room with path from this room\n # *create path kitchen -> create path to that room from this one\n # *create agent orc\n # *create object ring\n # *create key golden key\n # create lockable tower with golden key\n # create container box\n # create [un]freeze\n # create reset/load/save [fname]\n # create rename <-- **crashes*\n # create delete \n # create set_prop orc to health=5\n from parlai_internal.tasks.graph_world3.class_nodes import (\n create_thing,\n CLASS_NAMES,\n )\n\n if not self.has_prop(agent_id, 'agent'):\n return False, 'create'\n if params is None:\n return False, 'create'\n room_id = self.room(agent_id)\n all_params = ' '.join(params)\n txt = ' '.join(params[1:])\n resp = 'create ' + ' '.join(params)\n if not (all_params in ['save', 'load', 'freeze', 'unfreeze']):\n if txt == '':\n return False, resp\n if params[0] == 'print':\n ids = self.desc_to_nodes(txt, nearbyid=agent_id, nearbytype='all')\n if len(ids) == 0:\n self.send_msg(agent_id, \"Not found.\\n \")\n return False, resp\n id = ids[0]\n self.send_msg(agent_id, id + \" has:\\n{}\".format(self._node_to_prop[id]))\n return True, resp\n if params[0] == 'save':\n self.save_graph(txt)\n self.send_msg(agent_id, \"[ saved: \" + self._save_fname + ' ]\\n')\n return True, resp\n if params[0] == 'load' or params[0] == 'reset':\n self.load_graph(txt)\n self.send_msg(agent_id, \"[ loaded: \" + self._save_fname + ' ]\\n')\n return True, resp\n if params[0] == 'freeze':\n self.freeze(True)\n self.send_msg(agent_id, \"Frozen.\\n\")\n return True, resp\n if params[0] == 'unfreeze':\n self.freeze(False)\n self.send_msg(agent_id, \"Unfrozen.\\n\")\n return True, resp\n if params[0] in ['delete', 'del', 'rm']:\n ids = self.desc_to_nodes(txt, nearbyid=agent_id, nearbytype='all')\n if len(ids) == 0:\n self.send_msg(\"Not found.\\n \")\n return False, resp\n id = ids[0]\n self.delete_node(id)\n self.send_msg(agent_id, \"Deleted.\\n\")\n return True, resp\n if params[0] == 'rename':\n params = self.split_params(params[1:], 'to')\n to_ids = self.desc_to_nodes(params[0], nearbyid=agent_id, nearbytype='all')\n if len(to_ids) == 0:\n self.send_msg(\"Not found.\\n \")\n return False, resp\n to_id = to_ids[0]\n self.set_desc(to_id, params[1])\n self.send_msg(agent_id, \"Done.\\n\")\n return True, resp\n if params[0] == 'agent':\n create_thing(self, room_id, params[0], force=True, use_name=txt)\n self.send_msg(agent_id, \"Done.\\n\")\n return True, resp\n if params[0] == 'room':\n new_id = self.add_node(txt, params[0])\n self.add_path_to(new_id, room_id)\n self.set_prop(new_id, 'contain_size', 2000)\n self.send_msg(agent_id, \"Done.\\n\")\n return True, resp\n if params[0] == 'set_prop':\n params = self.split_params(params[1:], 'to')\n to_ids = self.desc_to_nodes(params[0], nearbyid=agent_id, nearbytype='all')\n if len(to_ids) == 0:\n self.send_msg(\"Not found.\\n \")\n return False, resp\n to_id = to_ids[0]\n key = params[1]\n value = True\n if '=' in key:\n sp = key.split('=')\n if len(sp) != 2:\n return False, resp\n key = sp[0]\n value = sp[1]\n if value == 'True':\n value = True\n try:\n value = int(value)\n except ValueError:\n pass\n self.set_prop(to_id, key, value)\n self.send_msg(agent_id, \"Done.\\n\")\n return True, resp\n if params[0] in CLASS_NAMES:\n if params[0] == 'key' and txt.find('key') == -1:\n self.send_msg(agent_id, \"Keys must be called keys!\\n\")\n return False, resp\n create_thing(self, room_id, params[0], force=True, use_name=txt)\n self.send_msg(agent_id, \"Done.\\n\")\n return True, resp\n if params[0] == 'lockable':\n ps = self.split_params(params[1:], 'with')\n if len(ps) != 2:\n return False, resp\n to_ids = self.desc_to_nodes(ps[0], nearbyid=agent_id, nearbytype='all')\n with_ids = self.desc_to_nodes(ps[1], nearbyid=agent_id, nearbytype='all')\n if len(to_ids) == 0 or len(with_ids) == 0:\n self.send_msg(\"Something was not found.\\n \")\n return False, resp\n to_id = to_ids[0]\n with_id = with_ids[0]\n if not self.get_prop(with_id, 'key'):\n self.send_msg(agent_id, \"You need to use a key!\\n\")\n return False, resp\n self.set_prop(to_id, 'locked_with', with_id)\n self.set_prop(to_id, 'locked', True)\n self.send_msg(agent_id, \"Done.\\n\")\n return True, resp\n if params[0] == 'path':\n to_id = self.desc_to_nodes(txt)\n if to_id is False:\n return False, resp\n self.add_path_to(to_id, room_id)\n self.send_msg(agent_id, \"Done.\\n\")\n return True, resp\n self.send_msg(agent_id, 'Create is not supported for: ' + resp)\n return False, resp\n\n # -- Create helpers -- #\n\n def split_params(self, params, word):\n if type(word) is str:\n word = {word}\n for w in word:\n search = ' {} '.format(w)\n phrase = ' '.join(params)\n if phrase.find(w) != -1:\n return phrase.split(search)\n return None\n\n # -- GraphFunction Helpers -- #\n\n def obj_fits(self, object_id, container_id):\n \"\"\"Return if one object will fit into another\"\"\"\n size = self.get_prop(object_id, 'size')\n max_size = self.get_prop(container_id, 'contain_size')\n if size is None or max_size is None:\n # TODO log these kinds of things\n print(\n 'None compare between {} and {}'.format(object_id, container_id),\n self._node_to_prop,\n )\n return size <= max_size\n\n def move_object(self, object_id, container_id):\n \"\"\"Move an object from wherever it is into somewhere else\"\"\"\n size = self.get_prop(object_id, 'size')\n # Remove from the old container\n old_id = self.node_contained_in(object_id)\n if old_id is not None:\n contain_size = self.get_prop(old_id, 'contain_size')\n contain_size += size\n self.set_prop(old_id, 'contain_size', contain_size)\n # Put in the new container\n contain_size = self.get_prop(container_id, 'contain_size')\n contain_size -= size\n self.set_prop(container_id, 'contain_size', contain_size)\n self.add_contained_in(object_id, container_id)\n\n def die(self, id):\n \"\"\"Update an agent into a dead state\"\"\"\n if not self.has_prop(id, 'agent'):\n return False\n if self.get_prop(id, 'is_player', False) is True:\n self.set_follow(id, None)\n room = self.location(id)\n add_text = ''\n contents = self.node_contains(id)\n if len(contents) > 0:\n add_text += '[*SPLIT*] Your travel companion leaves behind {}.'.format(\n self.display_node_list(contents)\n )\n for content in contents:\n self.move_object(content, room)\n text = {\n 'elf': \"Josephine collapses to the ground! \"\n \"She looks like she's asleep except for an awful \"\n \"stillness about her. Although her home is in the \"\n \"mountains, she seems a part of the woods as well. You \"\n \"hope to meet her again in the next life. And as you \"\n \"think this, a bright white light filters through the \"\n \"trees, engulfing the troll's peaceful form. You stare in \"\n \"wonder: when the light fades away, so does Josephine!\" + add_text,\n 'troll': \"You watch in horror as the elf drops lifelessly to the \"\n \"ground. Lying there, Alixlior looks strangely peaceful \"\n \"and as much a part of the woods as when alive. You know \"\n \"that were your friend alive, you would be told not to \"\n \"mourn and that all of this is a journey that will repeat \"\n \"itself - where you will undoubtedly meet again. But for \"\n \"now, this kind of blows. Before you can wonder if you \"\n \"should conduct a burial ceremony, a strange white light \"\n \"engulfs the elf's body, causing you to close your eyes. \"\n \"When you open them, Alixlior is gone!\" + add_text,\n }\n self.broadcast_to_room({'caller': None, 'room_id': room, 'txt': text}, [id])\n self.set_prop(id, 'dead', True)\n self.delete_node(id)\n return True\n\n agent_desc = self.node_to_desc(id, use_the=True).capitalize()\n self.broadcast_to_room(\n {\n 'caller': None,\n 'room_id': self.location(id),\n 'txt': agent_desc + ' died!\\n',\n },\n [id],\n )\n self.set_follow(id, None)\n self.set_prop(id, 'dead', True)\n self.delete_prop(id, 'agent')\n self.remove_class(id, 'agent')\n self.add_class(id, 'container')\n self.add_class(id, 'object')\n self.add_class(id, 'food')\n self.set_prop(id, 'container')\n self.set_prop(id, 'object')\n self.set_prop(id, 'food')\n self.set_prop(id, 'examined', True)\n return True\n\n def get_room_edge_text(self, room_descs, past=False):\n \"\"\"Get text for all the edges outside of a room\"\"\"\n if len(room_descs) == 1:\n if past:\n return 'There was ' + room_descs[0] + '.\\n'\n else:\n return 'There\\'s ' + room_descs[0] + '.\\n'\n default_paths = [\n path[10:] for path in room_descs if path.startswith('a path to')\n ]\n non_default_paths = [\n path for path in room_descs if not path.startswith('a path to')\n ]\n if len(default_paths) == 0:\n if past:\n s = 'There was '\n else:\n s = 'There\\'s '\n s += self.display_desc_list(non_default_paths)\n s += '.\\n'\n elif len(non_default_paths) == 0:\n if past:\n s = 'There were paths to '\n else:\n s = 'There are paths to '\n\n s += self.display_desc_list(default_paths)\n s += '.\\n'\n else:\n if past:\n s = 'There was '\n else:\n s = 'There\\'s '\n s += \", \".join(non_default_paths)\n if len(default_paths) == 1:\n s += ', and a path to '\n else:\n s += ', and paths to '\n s += self.display_desc_list(default_paths)\n s += '.\\n'\n return s\n\n def get_room_object_text(self, object_descs, ents, past=False, give_empty=True):\n \"\"\"Get text for all the objects in a room\"\"\"\n s = ''\n tensed_is = 'was' if past else 'is'\n tensed_are = 'were' if past else 'are'\n loc = 'there' if past else 'here'\n if len(object_descs) == 0:\n if not give_empty:\n return ''\n s += 'It ' + tensed_is + ' empty.\\n'\n elif len(object_descs) > 20:\n s += 'There ' + tensed_are + ' a lot of things here.\\n'\n else:\n s += 'There\\'s '\n s += self.display_desc_list(object_descs, ents)\n s += ' {}.\\n'.format(loc)\n return s\n\n def get_room_agent_text(self, agent_descs, past=False):\n \"\"\"Get text for all the agents in a room\"\"\"\n loc = 'there' if past else 'here'\n you_are = 'You were ' if past else 'You are '\n is_tensed = ' was ' if past else ' is '\n are_tensed = ' were ' if past else ' are '\n count = len(agent_descs)\n if count == 0:\n return ''\n elif count == 1:\n if agent_descs[0] == 'you':\n return you_are + loc + '.\\n'\n else:\n return agent_descs[0].capitalize() + is_tensed + loc + '.\\n'\n elif count == 2:\n all_descs = ' and '.join(agent_descs).capitalize()\n return all_descs + are_tensed + loc + '.\\n'\n else:\n before_and = ', '.join(agent_descs[:-1]).capitalize()\n all_descs = before_and + ', and ' + agent_descs[-1]\n return all_descs + are_tensed + loc + '.\\n'\n\n def get_room_edges(self, room_id):\n \"\"\"Return a list of edges from a room and their current descriptions\"\"\"\n rooms = self._node_to_edges[room_id]\n rooms = [r[1] for r in rooms if r[0] == 'path_to']\n room_descs = [self.node_to_desc(ent, room_id) for ent in rooms]\n return rooms, room_descs\n\n def get_nondescribed_room_objects(self, room_id):\n \"\"\"Return a list of objects in a room and their current descriptions\"\"\"\n objects = self.node_contains(room_id)\n objects = [o for o in objects if self.get_prop(o, 'object')]\n objects = [o for o in objects if 'described' not in self.get_prop(o, 'classes')]\n object_descs = [self.node_to_desc(o) for o in objects]\n return objects, object_descs\n\n def get_room_objects(self, room_id):\n \"\"\"Return a list of objects in a room and their current descriptions\"\"\"\n objects = self.node_contains(room_id)\n objects = [o for o in objects if self.get_prop(o, 'object')]\n object_descs = [self.node_to_desc(o) for o in objects]\n return objects, object_descs\n\n def get_nondescribed_room_agents(self, room):\n \"\"\"Return a list of agents in a room and their current descriptions\n if those agents aren't described in the room text\"\"\"\n agents = self.node_contains(room)\n agents = [a for a in agents if self.get_prop(a, 'agent')]\n agents = [a for a in agents if 'described' not in self.get_prop(a, 'classes')]\n agent_descs = [self.node_to_desc(a) for a in agents]\n return agents, agent_descs\n\n def get_room_agents(self, room):\n \"\"\"Return a list of agents in a room and their current descriptions\"\"\"\n agents = self.node_contains(room)\n agents = [a for a in agents if self.get_prop(a, 'agent')]\n agent_descs = [self.node_to_desc(a) for a in agents]\n return agents, agent_descs\n\n def get_text(self, agent, clear_actions=True):\n txt = ''\n if agent in self._node_to_text_buffer:\n txt = self._node_to_text_buffer[agent]\n self._node_to_text_buffer[agent] = '' # clear buffer\n if clear_actions:\n self._node_to_observations[agent] = [] # clear buffer\n return txt\n\n def cnt_obj(self, obj, c, ents=None):\n \"\"\"Return a text form of the count of an object\"\"\"\n cnt = c[obj]\n if cnt == 1:\n return obj\n else:\n if ents is not None:\n if self.get_prop(ents[obj], 'plural') is not None:\n words = self.get_prop(ents[obj], 'plural').split(' ')\n else:\n words = (obj + 's').split(' ')\n f = [\n 'two',\n 'three',\n 'four',\n 'five',\n 'six',\n 'seven',\n 'eight',\n 'nine',\n 'a lot of',\n ]\n rep = ['a', 'an', 'the']\n cnt = cnt - 2\n if cnt > 8:\n cnt = 8\n cnt = f[cnt]\n if words[0] in rep:\n return cnt + ' ' + ' '.join(words[1:])\n else:\n return cnt + ' ' + ' '.join(words)\n\n def display_desc_list(self, descs, ents=None):\n if len(descs) == 0:\n return 'nothing'\n if len(descs) == 1:\n return descs[0]\n c = Counter(descs)\n unique_items = set(descs)\n s = ''\n cnt = 0\n for obj in unique_items:\n s += self.cnt_obj(obj, c, ents)\n if len(unique_items) > 2 and cnt < len(unique_items) - 1:\n s += ','\n s += ' '\n cnt = cnt + 1\n if cnt == len(unique_items) - 1:\n s += 'and '\n return s.rstrip(' ')\n\n def display_node_list(self, l, from_id=False):\n desc_to_ent = {self.node_to_desc(ent, from_id): ent for ent in l}\n descs = [self.node_to_desc(ent, from_id) for ent in l]\n return self.display_desc_list(descs, desc_to_ent)\n\n def display_node(self, id):\n if self.get_prop(id, 'surface_type') == 'on':\n contents = self.node_contains(id)\n content_desc = self.display_node_list(contents)\n obj_desc = self.node_to_desc(id, use_the=True)\n return \"There's {} on {}\".format(content_desc, obj_desc)\n else:\n s = self.node_to_desc(id, use_the=True).capitalize() + ' contains '\n contents = self.node_contains(id)\n return s + self.display_node_list(contents) + '.\\n'\n\n def help(self):\n txt = (\n '----------------------------------\\n'\n 'Commands:\\n'\n 'look (l, for short)\\n'\n 'inventory (i or inv, for short)\\n'\n 'examine \\n'\n 'status/health\\n'\n 'go \\n'\n 'get/drop \\n'\n 'eat/drink \\n'\n 'wear/remove \\n'\n 'wield/unwield \\n'\n 'lock/unlock with \\n'\n 'follow \\n'\n 'hit \\n'\n 'put in \\n'\n 'get from \\n'\n 'give to \\n'\n 'steal from \\n'\n 'say \"\"\\n'\n 'tell \"\"\\n'\n '----------------------------------\\n'\n )\n return txt\n\n def args_to_descs(self, args):\n loc = self.location(args[0])\n return [self.node_to_desc_raw(i, from_id=loc) for i in args]\n\n def get_possible_actions(self, my_agent_id='dragon', use_actions=None):\n \"\"\"\n Get all actions that are possible from a given agent\n \"\"\"\n # TODO rather than iterating over objects and checking validity for\n # all functions, iterate over functions and query valid objects\n if self.get_prop(my_agent_id, 'dead'):\n return []\n o = self.get_actionable_ids(my_agent_id)\n final_o = o\n for item in o:\n if self.get_prop(item, 'agent') or self.get_prop(item, 'container'):\n final_o = final_o.union(self.node_contains(item))\n actions = []\n use_functions = CANNONICAL_GRAPH_FUNCTIONS.items()\n if use_actions is not None:\n use_functions = [\n (fn, func) for (fn, func) in use_functions if fn in use_actions\n ]\n for func_name, func in use_functions:\n if func_name in FUNC_IGNORE_LIST:\n continue # Ignore functions we don't want to expose directly\n args = [my_agent_id]\n if func.valid_args(self, args):\n canon = func.get_canonical_form(self, args)\n actions.append(canon)\n for id1 in final_o:\n if id1 in args:\n continue\n args = [my_agent_id, id1]\n if func.valid_args(self, args):\n canon = func.get_canonical_form(self, args)\n actions.append(canon)\n for id2 in final_o:\n if id2 in args:\n continue\n args = [my_agent_id, id1, id2]\n if func.valid_args(self, args):\n canon = func.get_canonical_form(self, args)\n actions.append(canon)\n return list(set(actions))\n\n @staticmethod\n def parse_static(inst):\n inst = inst.strip().split()\n symb_points = []\n in_quotes = False\n for i, symb in enumerate(inst):\n if '\"' in symb:\n in_quotes = not in_quotes\n if symb.lower() in GRAPH_FUNCTIONS.keys() and not in_quotes:\n symb_points.append(i)\n symb_points.append(len(inst))\n return inst, symb_points\n\n @staticmethod\n def filter_actions(inst):\n ret_actions = []\n inst, symb_points = Graph.parse_static(inst)\n for i in range(len(symb_points) - 1):\n j, k = symb_points[i], symb_points[i + 1]\n if inst[j].lower() in GRAPH_FUNCTIONS.keys():\n ret_actions.append(' '.join(inst[j:k]))\n return ' '.join(ret_actions), ret_actions\n\n def parse(self, inst):\n return Graph.parse_static(inst)\n\n def canonical_action(self, agentid, inst):\n words = inst.split(' ')\n if words[0].lower() in GRAPH_FUNCTIONS.keys():\n func_wrap = GRAPH_FUNCTIONS[words[0].lower()]\n valid, args, _canon_args = func_wrap.parse_text_to_args(\n self, agentid, words[1:]\n )\n if not valid:\n return False, inst\n return True, func_wrap.get_canonical_form(self, args)\n return False, inst\n\n def get_reverse_action(self, agentid, action, old_g):\n \"\"\"Attempts to get the reverse action for the given action. Makes no\n guarantees, could fail miserably\"\"\"\n inst, symb_points = self.parse(action)\n j, k = symb_points[0], symb_points[1]\n if inst[j].lower() in GRAPH_FUNCTIONS.keys():\n func_wrap = GRAPH_FUNCTIONS[inst[j].lower()]\n valid, args, _canon_args = func_wrap.parse_text_to_args(\n old_g, agentid, inst[j + 1 : k]\n )\n rev_func_name, new_args = func_wrap.get_reverse(self, args)\n if rev_func_name is None or rev_func_name is False:\n return rev_func_name, ''\n rev_func_wrap = GRAPH_FUNCTIONS[rev_func_name]\n rev_action = rev_func_wrap.get_canonical_form(self, new_args)\n return True, rev_action\n return None, ''\n\n def valid_exec(self, agentid, inst=None):\n if inst is None:\n inst = agentid\n agentid = 'dragon'\n\n if self.get_prop(agentid, 'dead'):\n return False\n\n inst, symb_points = self.parse(inst)\n inst[0] = inst[0].lower()\n\n if len(inst) == 1 and (inst[0] == 'help'):\n return True\n\n if inst[0] not in GRAPH_FUNCTIONS.keys():\n return False\n\n for i in range(len(symb_points) - 1):\n j, k = symb_points[i], symb_points[i + 1]\n params = inst[j + 1 : k]\n if inst[j].lower() in GRAPH_FUNCTIONS.keys():\n func_wrap = GRAPH_FUNCTIONS[inst[j].lower()]\n valid, args, _canon_args = func_wrap.parse_text_to_args(\n self, agentid, params\n )\n if not valid:\n return False\n else:\n return False\n return True\n\n def parse_exec(self, agentid, inst=None):\n \"\"\"ATTENTION: even if one of the actions is invalid, all actions\n before that will still be executed (the world state will be changed)!\n \"\"\"\n if inst is None:\n inst = agentid\n agentid = 'dragon'\n\n if inst.startswith('look '):\n inst = 'look'\n\n if self.get_prop(agentid, 'dead'):\n self.send_msg(agentid, \"You are dead, you can't do anything, sorry.\")\n return False, 'dead'\n inst, symb_points = self.parse(inst)\n inst[0] = inst[0].lower()\n\n hint_calls = ['a', 'actions', 'hints']\n if len(inst) == 1 and (inst[0] in hint_calls):\n # TODO remove the list of valid instructions from the main game,\n # Perhaps behind and admin gatekeeper of sorts\n self.send_msg(\n agentid, '\\n'.join(sorted(self.get_possible_actions(agentid))) + '\\n'\n )\n return True, 'actions'\n if len(inst) == 1 and (inst[0] == 'help'):\n self.send_msg(agentid, self.help())\n return True, 'help'\n # if inst[0] == 'create':\n # return self.create(agentid, inst[1:])\n if inst[0] not in GRAPH_FUNCTIONS.keys():\n # if Callbacks.handle_failed_parse_callbacks(\n # inst[0].lower(), self, inst[1:], agentid):\n # return False, inst[0]\n self.send_msg(agentid, \"You can't {}.\".format(inst[0]))\n return False, inst[0]\n acts = []\n for i in range(len(symb_points) - 1):\n j, k = symb_points[i], symb_points[i + 1]\n params = inst[j + 1 : k]\n if inst[j].lower() in GRAPH_FUNCTIONS.keys():\n func_wrap = GRAPH_FUNCTIONS[inst[j].lower()]\n valid, args, _canon_args = func_wrap.parse_text_to_args(\n self, agentid, params\n )\n if not valid:\n # if Callbacks.handle_failed_parse_callbacks(\n # func_wrap.get_name(), self, params, agentid):\n # return False, ' '.join(acts)\n if type(args) is str:\n self.send_msg(agentid, args)\n else:\n self.send_action(agentid, args)\n return False, ' '.join(acts)\n new_act = func_wrap.get_canonical_form(self, args)\n success = func_wrap.handle(self, args)\n acts.append(new_act)\n if not success:\n return False, ' '.join(acts)\n # elif Callbacks.handle_failed_parse_callbacks(\n # inst[j].lower(), self, params, agentid):\n # return False, ' '.join(acts)\n else:\n return False, ' '.join(acts)\n return True, ' '.join(acts)\n\n def update_world(self):\n \"\"\"\n Move agents, do basic actions with npcs, handle telling npcs things\n \"\"\"\n if self.freeze():\n return\n for agent_id in self._node_npcs:\n if not self.get_prop(agent_id, 'agent'):\n continue\n if self.get_prop(agent_id, 'dead'):\n continue\n # if agent_id in self._node_to_observations:\n # for obs in self._node_to_observations[agent_id]:\n # if obs['caller'] == 'say' and self.npc_say_respond:\n # # TODO make a property of model agents rather than\n # # manually present in the graph engine\n # actor = obs['actors'][0]\n # listeners = obs['present_agent_ids']\n # name_guess = ' '.join(agent_id.split('_')[:-1])\n # content_words = obs['content'].split(' ')\n # resp_confidence = 1 / (len(listeners)-1)\n # if self._last_tell_target[actor] == agent_id:\n # resp_confidence += 0.5\n #\n # # Filter out the name from the word list if its there\n # fin_content = []\n # for word in content_words:\n # stripped = word.replace('.', '').replace('?', '')\n # if stripped == name_guess:\n # resp_confidence += 0.8\n # else:\n # fin_content.append(stripped)\n #\n # # Talk if it makes sense to\n # if resp_confidence > 0.9:\n # obs = obs.copy()\n # args = [\n # obs['actors'][0],\n # agent_id,\n # ' '.join(fin_content)\n # ]\n # self._last_tell_target[actor] = agent_id\n # # Callbacks.handle_callbacks(\n # # TellFunction(), self, args)\n self.get_text(agent_id)\n did_hit = False\n possible_agents = self._node_contains[self.room(agent_id)]\n for other_agent_id in possible_agents:\n if self.get_prop(other_agent_id, 'is_player'):\n aggression = self.get_prop(agent_id, 'aggression', 0)\n if random.randint(0, 100) < aggression:\n act = 'hit {}'.format(other_agent_id)\n self.parse_exec(agent_id, act)\n did_hit = True\n if not did_hit:\n # random movement for npcs..\n if random.randint(0, 100) < self.get_prop(agent_id, 'speed'):\n cur_loc = self.room(agent_id)\n locs = self.node_path_to(cur_loc)\n loc = locs[random.randint(0, len(locs) - 1)]\n act = 'go ' + self.node_to_desc_raw(loc, from_id=cur_loc)\n self.parse_exec(agent_id, act)\n","repo_name":"natashamjaques/neural_chat","sub_path":"ParlAI/parlai/mturk/tasks/light/light_chats/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":160831,"program_lang":"python","lang":"en","doc_type":"code","stars":172,"dataset":"github-code","pt":"85"} +{"seq_id":"18255084581","text":"from turtle import Screen\r\n\r\nfrom ball import Ball\r\nfrom padles import Paddles\r\nfrom score_board import Score\r\nimport time\r\n\r\nscreen = Screen()\r\nscreen.setup(height=600, width=800)\r\nscreen.bgcolor(\"black\")\r\nscreen.title(\"Pong\")\r\nscreen.tracer(0)\r\nscreen.listen()\r\n\r\nr_paddle = Paddles((350, 0))\r\nl_paddle = Paddles((-350, 0))\r\nscreen.onkey(r_paddle.move_up, \"Up\")\r\nscreen.onkey(r_paddle.move_down, \"Down\")\r\nscreen.onkey(l_paddle.move_up, \"w\")\r\nscreen.onkey(l_paddle.move_down, \"s\")\r\n\r\nball = Ball((0, 0))\r\ngame_is_on = True\r\nscore = Score()\r\n\r\n\r\nwhile game_is_on:\r\n\r\n time.sleep(0.05)\r\n screen.update()\r\n ball.move()\r\n score.score_update()\r\n\r\n if ball.ycor() > 280 or ball.ycor() < -280:\r\n ball.bounce_y()\r\n\r\n if ball.xcor() > 380 or ball.xcor() < -380:\r\n ball.bounce_x()\r\n\r\n if (ball.distance(r_paddle) < 50 and ball.xcor() > 340) or (ball.distance(l_paddle) < 50 and ball.xcor() < -340):\r\n ball.bounce_x()\r\n\r\n if ball.xcor() < -380:\r\n score.score_increase_left()\r\n print(\"ball is out\")\r\n ball.reset()\r\n if ball.xcor() > 380:\r\n score.score_increase_right()\r\n print(\"ball is out\")\r\n ball.reset()\r\n\r\nscreen.exitonclick()\r\n","repo_name":"islombek90/Python","sub_path":"Pong Game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73575839957","text":"def d(n):\n s = 0\n for x in str(n):\n s += int(x)\n return n + s\n\nsize = 10_001\nouts = []\nrecord = set(range(1, size))\nfor i in range(1, size):\n point = d(i)\n if point in record:\n record.remove(point)\n \n[print(x) for x in record]","repo_name":"tc-ha/PS","sub_path":"self_numbers.py","file_name":"self_numbers.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"43231667404","text":"import os\nimport pickle\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.metrics import plot_confusion_matrix, classification_report\nfrom sklearn.model_selection import train_test_split\n\n\ndef preprocessing(path):\n data = pd.read_csv(f\"data/DetectPD{path}.csv\")\n\n # Preprocessing\n gender = list(data['GENDER'])\n handedness = list(data['RIGH/LEFT-HANDED'])\n age = list(data['AGE'])\n rms = list(data['RMS'])\n max_st_ht = list(data['MAX_BETWEEN_ST_HT'])\n min_st_ht = list(data['MIN_BETWEEN_ST_HT'])\n std_st_ht = list(data['STD_DEVIATION_ST_HT'])\n mrt = list(data['MRT'])\n max_ht = list(data['MAX_HT'])\n min_ht = list(data['MIN_HT'])\n std_ht = list(data['STD_HT'])\n n_to_p_st_ht = list(data['CHANGES_FROM_NEGATIVE_TO_POSITIVE_BETWEEN_ST_HT'])\n class_type = list(data['CLASS_TYPE'])\n\n # Creating 'x' and 'y'\n x = list(\n zip(gender, handedness, age, rms, max_st_ht, min_st_ht, std_st_ht, mrt, max_ht, min_ht, std_ht, n_to_p_st_ht))\n y = list(class_type)\n\n return x, y\n\n\ndef train_voting_classifier(path):\n estimators = []\n for root, directories, files in os.walk(f\"models/DetectPD{path}\", topdown=False):\n for name in files:\n model = pickle.load(open(os.path.join(root, name), \"rb\"))\n estimators.append((name, model))\n\n x, y = preprocessing(path)\n\n best_model = None\n best_accuracy = 0\n best_x_test = None\n best_y_test = None\n\n for i in range(10000):\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1)\n\n model = VotingClassifier(estimators=estimators, voting='hard')\n\n model.fit(x_train, y_train)\n\n model_accuracy = model.score(x_test, y_test)\n\n if best_accuracy < model_accuracy:\n best_model = model\n best_accuracy = model_accuracy\n print(f\"iteration {i+1}: {model_accuracy * 100}\")\n best_x_test = x_test\n best_y_test = y_test\n\n pickle.dump(best_model, open(f\"VotingClassifier{path}.pickle\", \"wb\"))\n\n # Running predictions using test data\n predictions = best_model.predict(best_x_test)\n\n # getting accuracy as percentage\n text = classification_report(best_y_test, predictions) + f\"\\nVotingClassifier accuracy: {best_accuracy}\"\n\n file = open(f\"plots/DetectPD{path}/DetectPD{path}_report.txt\", \"w\")\n file.write(text)\n file.close()\n\n # Creating confusion matrix\n labels = ['negative', 'positive']\n\n titles_options = [(\"Confusion matrix, without normalization\", None),\n (\"Normalized confusion matrix\", 'true')]\n for title, normalize in titles_options:\n disp = plot_confusion_matrix(best_model, best_x_test, best_y_test, display_labels=labels, cmap=plt.cm.Blues,\n normalize=normalize)\n disp.ax_.set_title(title)\n plt.savefig(f\"plots/DetectPD{path}/DetectPD{path}_{title}.png\".replace(\" \", \"_\").replace(\",\", \"\"))\n","repo_name":"RadhikaRanasinghe/Meraki","sub_path":"Backend/Models/VotingClassifier/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"42434544995","text":"from util import *\n# given: x != y\n# x not in {y}\n\n\n@apply\ndef apply(given):\n x, S = given.of(Element)\n return Unequal(S, x.emptySet)\n\n\n@prove\ndef prove(Eq):\n n = Symbol(integer=True, positive=True, given=True)\n x = Symbol(complex=True, shape=(n,), given=True)\n S = Symbol(etype=dtype.complex * n, given=True)\n Eq << apply(Element(x, S))\n\n Eq << ~Eq[-1]\n\n Eq << Eq[0].subs(Eq[-1])\n\n\nif __name__ == '__main__':\n run()\n\n# created on 2019-09-22\n","repo_name":"cosmosZhou/sympy","sub_path":"axiom/sets/el/imply/ne_empty.py","file_name":"ne_empty.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"83"} +{"seq_id":"2066395722","text":"class Solution:\n def findMaxAverage(self, nums, k):\n total = sum(nums[0:k])\n res = total\n i = 0\n j = i + k - 1\n while j <= len(nums)-2:\n temp = total - nums[i] + nums[j+1]\n total = temp\n res = max(temp, res)\n i += 1\n j += 1\n return res/k\n\nnums = [1,12,-5,-6,50,3]\nk = 4\nsolution = Solution()\nprint(solution.findMaxAverage(nums, k))","repo_name":"BrandonLee0604/Leetcode","sub_path":"Python/643. 子数组最大平均数 I.py","file_name":"643. 子数组最大平均数 I.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"34394915164","text":"import FWCore.ParameterSet.Config as cms\n\nfrom JetMETAnalysis.JetSkims.photonjets_EventContent_cff import *\nfrom JetMETAnalysis.JetSkims.RECOSIMPhotonJetsEventContent_cff import *\nphotonjetsOutputModuleRECOSIM = cms.OutputModule(\"PoolOutputModule\",\n photonjetsEventSelection,\n RECOSIMPhotonJetsEventContent,\n dataset = cms.untracked.PSet(\n filterName = cms.untracked.string('photonjets_RECOSIM'),\n dataTier = cms.untracked.string('USER')\n ),\n fileName = cms.untracked.string('photonjets_RECOSIM.root')\n)\n\n\n","repo_name":"ahlinist/cmssw","sub_path":"JetMETAnalysis/JetSkims/python/photonjetsOutputModuleRECOSIM_cfi.py","file_name":"photonjetsOutputModuleRECOSIM_cfi.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"71357708750","text":"import functools\nfrom os import listdir\nfrom os.path import isfile, join\nimport multiprocessing as mp\nimport matplotlib as mplt\nimport more_itertools as mi\nimport numpy as np\nimport pandas as pd\nimport soundfile as sf\nfrom matplotlib import mlab\nfrom scipy import signal\n\nfrom database import Database, Connection, DB\n\n\ndef stereo2mono(stereo):\n return (stereo[:, 0] + stereo[:, 1]) / 2\n\n\ndef generate_footprint(data, fs):\n # mono = stereo2mono(data)\n spec, freq, t = generate_specgram(fs, data)\n\n buckets = generate_buckets()\n\n new_spec = remap_frequencies_for_specgram(spec, freq, buckets)\n\n return generate_h(new_spec)\n\n\ndef remap_frequencies_for_specgram(spec, freq, buckets):\n return np.array(list(map(lambda s: np.array(remap_frequencies(s, freq, buckets)), spec.T))).T\n\n\ndef generate_h(e):\n h = np.zeros((len(e) - 1, len(e[0])))\n for row_idx in range(1, len(e) - 1):\n for col_idx in range(1, len(e[row_idx]) - 1):\n h[row_idx][col_idx] = int(\n e[row_idx + 1][col_idx] - e[row_idx][col_idx] > e[row_idx + 1][col_idx - 1] - e[row_idx][\n col_idx - 1])\n return h\n\n\ndef find_new_freq_band(f, bands):\n return list(filter(lambda band: band[0] <= f <= band[1], bands))[0][0]\n\n\ndef remap_frequencies(spectrum, freq, buckets):\n freq_to_energy_list = zip(spectrum ** 2, freq)\n energy_band_new_relation = map(\n lambda energy_freq: (energy_freq[0], find_new_freq_band(energy_freq[1], buckets)), freq_to_energy_list)\n grouped_by_frequencies = mi.groupby_transform(energy_band_new_relation, lambda e_f: e_f[1], lambda e_f: e_f[0])\n frequency_energy_sum = map(lambda kv: (kv[0], sum(kv[1])), grouped_by_frequencies)\n return list(mi.unzip(frequency_energy_sum)[1])[1:-1]\n\n\ndef generate_buckets():\n bands = np.concatenate((np.array([0]), np.geomspace(300, 2000, num=22), np.array([np.inf])), axis=None)\n\n return list(mi.pairwise(bands))\n\n\ndef generate_specgram(samplerate, mono):\n # df = pd.DataFrame(mono)\n # df['t'] = df.index / samplerate\n # df['avg'] = df[0]\n fs = samplerate\n nyq = fs / 2\n length = filter_order = 87\n f_high = 5512 / 2\n window = \"hamming\"\n b = signal.firwin(length, cutoff=f_high / nyq, window=window, pass_zero='lowpass')\n num = b\n dec = np.zeros(len(b))\n dec[0] = 1\n decimation = 8\n n = 2 ** 12\n dlti = signal.dlti(num, dec)\n mono_dec = signal.decimate(mono, 8, ftype=dlti, n=filter_order)\n fxx, txx, sxx = signal.spectrogram(mono_dec, fs=fs / decimation, window=window, nperseg=n,\n noverlap=np.round(n * .9), mode='magnitude')\n # op_1 = signal.lfilter(b, 1, df['avg'])\n # df['avg_filtered'] = op_1\n # compression_factor = 8\n # compress_sample_df = lambda df, compression_factor: df[df.index % compression_factor == 0]\n # compressed_df = compress_sample_df(df[['t', 'avg_filtered']], compression_factor).reset_index(inplace=False)\n # # compressed_df['avg_filtered_fft'] = np.fft.fft(compressed_df['avg_filtered'])\n # number_of_points = lambda time_mils, samplerate: int((time_mils / 1000) * samplerate)\n # # decimated_signal = compressed_df['avg_filtered']\n # smpl_rate = samplerate / 8\n # spec, freq, t = mlab.specgram(compressed_df['avg_filtered'], Fs=smpl_rate, NFFT=number_of_points(100, smpl_rate),\n # window=mplt.mlab.window_hanning)\n # return spec, freq, t\n return sxx, fxx, txx\n\n\ndef make_db_with_songs(song, connection=Connection):\n print(\"%s processing \\n\" % song)\n db = try_get_from_cache(connection, song)\n print(\"%s processed \\n\" % song)\n return db\n\n\ndef cache_path_from_song_path(song):\n return \"/\".join(song.split(\"/\")[:-1] + [\"cache\"] + [song.split(\"/\")[-1]])\n\n\ndef song_cached(song):\n try:\n f = open(cache_path_from_song_path(song), \"rb\")\n f.close()\n return True\n except FileNotFoundError:\n return False\n\n\ndef try_get_from_cache(connection, song):\n song_name = song.split(\"/\")[-1].split(\".\")[0]\n if song_cached(song):\n return Database(Connection.from_disk(cache_path_from_song_path(song)), song_name)\n else:\n db = Database(connection(), song_name)\n save_song(db, song)\n db.set_path(cache_path_from_song_path(song))\n # db.flush()\n return db\n\n\ndef generate_db(path, db_name, make_connection):\n print(\"collecting songs\")\n\n songs = get_song_paths(path)\n\n print(\"Songs found: %i\" % len(songs))\n\n db = make_db(songs, db_name, make_connection)\n\n save_db(db, db_name, path)\n print(\"Finished\")\n\n return db\n\n\ndef save_db(db, db_name, path):\n filename = path\n db.set_path(filename)\n db.set_name(db_name)\n db.flush()\n\n\ndef make_db(songs, db_name, make_connection=Connection):\n p = mp.Pool(4)\n dbs = p.map(make_db_with_songs, songs)\n p.close()\n # dbs = list(map(make_db_with_songs, songs))\n print('Merging db\\'s')\n db = functools.reduce(lambda db1, db2: db1 + db2, dbs)\n return db\n\n\ndef get_song_paths(path):\n filenames = [f for f in listdir(path) if isfile(join(path, f))]\n songs = [path + '/' + name for name in filenames if name.endswith(\".ogg\")]\n return songs\n\n\ndef save_song(db, song):\n data, samplerate = sf.read(song)\n footprint = generate_footprint(data, samplerate)\n song_id = song.split('/')[-1]\n db.save_footprint(song_id, footprint)\n\n\ndef generate_db2(path):\n # Incializo tabla hash\n files = get_song_paths(path)\n hash_nbits = 20 # Cantidad de bits de los hashes\n n_entries = len(files) # Cantidad de columnas de la tabla; cant canciones\n ID_nbits = 12 # Cantidad de bits para ID numerico de la cancion\n db = DB(hash_nbits, n_entries, ID_nbits, np.zeros((2 ** hash_nbits, n_entries), dtype=np.uint32))\n\n for k in range(n_entries):\n file_path = files[k]\n # Muestro por consola el archivo que analizamos\n track, fs = sf.read(file_path)\n # Generamos la huella acustica H\n sound_print = generate_footprint(track, fs)\n # print(sound_print)\n # Guardamos la huella en la DB. A esta cancion se asigna el\n # identificador numerico k, el cual se guarda en la base de datos\n # La matriz H debera ser una matriz con elementos binarios de\n # hash_nbits filas\n db.save_footprint(k + 1, sound_print)\n db.set_path(path + \"/main_db\")\n db.flush()\n\nif __name__ == '__main__':\n path = \"/home/leonardo/Documents/seniales/tp/10songs\"\n generate_db2(path)\n","repo_name":"LeoCenturion/tp_seniales_sistemas","sub_path":"generatedb.py","file_name":"generatedb.py","file_ext":"py","file_size_in_byte":6523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"43944668026","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport os, logging, datetime\nfrom qgis.core import *\nfrom PyQt4 import QtCore, QtGui\nfrom processing.tools import *\nfrom dialog_lumens_base import DialogLumensBase\n\n\nclass DialogLumensQUESHWatershedModelEvaluation(DialogLumensBase):\n \"\"\"\n \"\"\"\n \n \n def __init__(self, parent):\n super(DialogLumensQUESHWatershedModelEvaluation, self).__init__(parent)\n \n self.dialogTitle = 'LUMENS QUES-H Watershed Model Evaluation'\n \n self.setupUi(self)\n \n self.buttonSelectWorkingDir.clicked.connect(self.handlerSelectWorkingDir)\n self.buttonSelectObservedDebitFile.clicked.connect(self.handlerSelectObservedDebitFile)\n self.buttonSelectOutputWatershedModelEvaluation.clicked.connect(self.handlerSelectOutputWatershedModelEvaluation)\n self.buttonLumensDialogSubmit.clicked.connect(self.handlerLumensDialogSubmit)\n \n \n def setupUi(self, parent):\n super(DialogLumensQUESHWatershedModelEvaluation, self).setupUi(self)\n \n layoutLumensDialog = QtGui.QGridLayout()\n \n self.labelWorkingDir = QtGui.QLabel(parent)\n self.labelWorkingDir.setText('Working directory:')\n layoutLumensDialog.addWidget(self.labelWorkingDir, 0, 0)\n \n self.lineEditWorkingDir = QtGui.QLineEdit(parent)\n self.lineEditWorkingDir.setReadOnly(True)\n layoutLumensDialog.addWidget(self.lineEditWorkingDir, 0, 1)\n \n self.buttonSelectWorkingDir = QtGui.QPushButton(parent)\n self.buttonSelectWorkingDir.setText('Select &Working Directory')\n layoutLumensDialog.addWidget(self.buttonSelectWorkingDir, 1, 0, 1, 2)\n \n self.labelDateInitial = QtGui.QLabel(parent)\n self.labelDateInitial.setText('Initial date:')\n layoutLumensDialog.addWidget(self.labelDateInitial, 2, 0)\n \n self.dateDateInitial = QtGui.QDateEdit(QtCore.QDate.currentDate(), parent)\n self.dateDateInitial.setCalendarPopup(True)\n self.dateDateInitial.setDisplayFormat('dd/MM/yyyy')\n layoutLumensDialog.addWidget(self.dateDateInitial, 2, 1)\n \n self.labelDateFinal = QtGui.QLabel(parent)\n self.labelDateFinal.setText('Final date:')\n layoutLumensDialog.addWidget(self.labelDateFinal, 3, 0)\n \n self.dateDateFinal = QtGui.QDateEdit(QtCore.QDate.currentDate(), parent)\n self.dateDateFinal.setCalendarPopup(True)\n self.dateDateFinal.setDisplayFormat('dd/MM/yyyy')\n layoutLumensDialog.addWidget(self.dateDateFinal, 3, 1)\n \n self.labelSWATModel = QtGui.QLabel(parent)\n self.labelSWATModel.setText('SWAT &model:')\n layoutLumensDialog.addWidget(self.labelSWATModel, 4, 0)\n \n SWATModel = {\n 1: 'Skip',\n 2: 'Run',\n }\n \n self.comboBoxSWATModel = QtGui.QComboBox()\n \n for key, val in SWATModel.iteritems():\n self.comboBoxSWATModel.addItem(val, key)\n \n layoutLumensDialog.addWidget(self.comboBoxSWATModel, 4, 1)\n \n self.labelSWATModel.setBuddy(self.comboBoxSWATModel)\n \n self.labelLocation = QtGui.QLabel(parent)\n self.labelLocation.setText('&Location:')\n layoutLumensDialog.addWidget(self.labelLocation, 5, 0)\n \n self.lineEditLocation = QtGui.QLineEdit(parent)\n self.lineEditLocation.setText('location')\n layoutLumensDialog.addWidget(self.lineEditLocation, 5, 1)\n \n self.labelLocation.setBuddy(self.lineEditLocation)\n \n self.labelOutletReachSubBasinID = QtGui.QLabel(parent)\n self.labelOutletReachSubBasinID.setText('Outlet reach/sub-basin ID:')\n layoutLumensDialog.addWidget(self.labelOutletReachSubBasinID, 6, 0)\n \n self.spinBoxOutletReachSubBasinID = QtGui.QSpinBox(parent)\n self.spinBoxOutletReachSubBasinID.setRange(1, 99999)\n self.spinBoxOutletReachSubBasinID.setValue(10)\n layoutLumensDialog.addWidget(self.spinBoxOutletReachSubBasinID, 6, 1)\n \n self.labelOutletReachSubBasinID.setBuddy(self.spinBoxOutletReachSubBasinID)\n \n self.labelObservedDebitFile = QtGui.QLabel(parent)\n self.labelObservedDebitFile.setText('Observed debit file:')\n layoutLumensDialog.addWidget(self.labelObservedDebitFile, 7, 0)\n \n self.lineEditObservedDebitFile = QtGui.QLineEdit(parent)\n self.lineEditObservedDebitFile.setReadOnly(True)\n layoutLumensDialog.addWidget(self.lineEditObservedDebitFile, 7, 1)\n \n self.buttonSelectObservedDebitFile = QtGui.QPushButton(parent)\n self.buttonSelectObservedDebitFile.setText('Select Observed &Debit File')\n layoutLumensDialog.addWidget(self.buttonSelectObservedDebitFile, 8, 0, 1, 2)\n \n self.labelOutputWatershedModelEvaluation = QtGui.QLabel(parent)\n self.labelOutputWatershedModelEvaluation.setText('Watershed model evaluation (output):')\n layoutLumensDialog.addWidget(self.labelOutputWatershedModelEvaluation, 9, 0)\n \n self.lineEditOutputWatershedModelEvaluation = QtGui.QLineEdit(parent)\n self.lineEditOutputWatershedModelEvaluation.setReadOnly(True)\n layoutLumensDialog.addWidget(self.lineEditOutputWatershedModelEvaluation, 9, 1)\n \n self.buttonSelectOutputWatershedModelEvaluation = QtGui.QPushButton(parent)\n self.buttonSelectOutputWatershedModelEvaluation.setText('Select Watershed Model Evaluation')\n layoutLumensDialog.addWidget(self.buttonSelectOutputWatershedModelEvaluation, 10, 0, 1, 2)\n \n self.buttonLumensDialogSubmit = QtGui.QPushButton(parent)\n self.buttonLumensDialogSubmit.setText(self.dialogTitle)\n layoutLumensDialog.addWidget(self.buttonLumensDialogSubmit, 11, 0, 1, 2)\n \n self.dialogLayout.addLayout(layoutLumensDialog)\n \n self.setLayout(self.dialogLayout)\n \n self.setWindowTitle(self.dialogTitle)\n self.setMinimumSize(400, 200)\n self.resize(parent.sizeHint())\n \n \n def setAppSettings(self):\n \"\"\"Set the required values from the form widgets\n \"\"\"\n self.main.appSettings[type(self).__name__]['workingDir'] = unicode(self.lineEditWorkingDir.text()).replace(os.path.sep, '/')\n self.main.appSettings[type(self).__name__]['dateInitial'] = self.dateDateInitial.date().toString('dd/MM/yyyy')\n self.main.appSettings[type(self).__name__]['dateFinal'] = self.dateDateFinal.date().toString('dd/MM/yyyy')\n self.main.appSettings[type(self).__name__]['SWATModel'] = self.comboBoxSWATModel.itemData(self.comboBoxSWATModel.currentIndex())\n self.main.appSettings[type(self).__name__]['location'] = unicode(self.lineEditLocation.text())\n self.main.appSettings[type(self).__name__]['outletReachSubBasinID'] = self.spinBoxOutletReachSubBasinID.value()\n self.main.appSettings[type(self).__name__]['observedDebitFile'] = unicode(self.lineEditObservedDebitFile.text())\n \n outputWatershedModelEvaluation = unicode(self.lineEditOutputWatershedModelEvaluation.text())\n \n if not outputWatershedModelEvaluation:\n outputWatershedModelEvaluation = '__UNSET__'\n \n self.main.appSettings[type(self).__name__]['outputWatershedModelEvaluation'] = outputWatershedModelEvaluation\n \n \n def handlerSelectWorkingDir(self):\n \"\"\"Select a folder as working dir\n \"\"\"\n workingDir = unicode(QtGui.QFileDialog.getExistingDirectory(self, 'Select Working Directory'))\n \n if workingDir:\n self.lineEditWorkingDir.setText(workingDir)\n \n logging.getLogger(type(self).__name__).info('select working directory: %s', workingDir)\n \n \n def handlerSelectObservedDebitFile(self):\n \"\"\"Select observed debit file\n \"\"\"\n file = unicode(QtGui.QFileDialog.getOpenFileName(\n self, 'Select Observed Debit File', QtCore.QDir.homePath(), 'Observed Debit File (*{0})'.format(self.main.appSettings['selectDatabasefileExt'])))\n \n if file:\n self.lineEditObservedDebitFile.setText(file)\n \n logging.getLogger(type(self).__name__).info('select file: %s', file)\n \n \n def handlerSelectOutputWatershedModelEvaluation(self):\n \"\"\"Select a output file\n \"\"\"\n outputfile = unicode(QtGui.QFileDialog.getSaveFileName(\n self, 'Create/Select Watershed Model Evaluation Output', QtCore.QDir.homePath(), 'Watershed Model Evaluation (*{0})'.format(self.main.appSettings['selectDatabasefileExt'])))\n \n if outputfile:\n self.lineEditOutputWatershedModelEvaluation.setText(outputfile)\n \n logging.getLogger(type(self).__name__).info('select output file: %s', outputfile)\n \n \n def handlerLumensDialogSubmit(self):\n \"\"\"\n \"\"\"\n self.setAppSettings()\n \n if self.validDialogForm():\n logging.getLogger(type(self).__name__).info('start: %s' % self.dialogTitle)\n \n self.buttonLumensDialogSubmit.setDisabled(True)\n \n outputWatershedModelEvaluation = self.main.appSettings[type(self).__name__]['outputWatershedModelEvaluation']\n \n if outputWatershedModelEvaluation == '__UNSET__':\n outputWatershedModelEvaluation = None\n \n outputs = general.runalg(\n 'modeler:ques-h_watershed_model_evaluation',\n self.main.appSettings[type(self).__name__]['workingDir'],\n self.main.appSettings[type(self).__name__]['period1'],\n self.main.appSettings[type(self).__name__]['period2'],\n self.main.appSettings[type(self).__name__]['SWATModel'],\n self.main.appSettings[type(self).__name__]['location'],\n self.main.appSettings[type(self).__name__]['outletReachSubBasinID'],\n self.main.appSettings[type(self).__name__]['observedDebitFile'],\n outputWatershedModelEvaluation,\n )\n \n \"\"\"\n print outputs\n \"\"\"\n \n self.buttonLumensDialogSubmit.setEnabled(True)\n \n logging.getLogger(type(self).__name__).info('end: %s' % self.dialogTitle)\n \n self.close()\n ","repo_name":"geoenvo/lumens","sub_path":"unused/dialog_lumens_quesh_watershedmodelevaluation.py","file_name":"dialog_lumens_quesh_watershedmodelevaluation.py","file_ext":"py","file_size_in_byte":10458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"38678479237","text":"from pandas import read_csv\nimport time\n#==========================\ndef main():\n f = open ('/mnt/tb/amirdata/Merged_File_Reading_Info.txt', 'w')\n f.write(\"reading the dataframe and getting its details \\r\\n\")\n t0 = time.perf_counter() \n df = read_csv(\"/mnt/tb/amirdata/Merge_All_Waves.zip\", compression='zip', encoding=\"ISO-8859-1\", engine='python')\n f.write(\"Duplicate Tweetid : \" + str(df['tweetid'].duplicated().any()) + '\\r\\n')\n df = df.drop_duplicates('tweetid').reset_index(drop=True)\n f.write(\"The first timestamp after sorting : \" + str(df['created_at'].iloc[[0]].values)+'\\r\\n') #getting the first timestamp\n f.write(\"The last timestamp after sorting: \" + str(df['created_at'].iloc[[-1]].values)+'\\r\\n') #getting the last timestamp\n f.write(\"Data Shape : \" + str(df.shape) + '\\r\\n') #getting the data shape\n f.write(\"Duplicate Tweetid : \" + str(df['tweetid'].duplicated().any()) + '\\r\\n') #to see if there is a tweetid duplicate in the data yet!\n f.write(\"Columns Labels : \" + str(df.columns.values) + '\\r\\n') #to get the column labels\n Size_Frame = df.groupby('id').size()\n number_unique_users = len(Size_Frame.index)\n f.write(\"Number of Unique Users : \" + str(number_unique_users) + '\\r\\n') #to get the number of unique users in the final dataframe \n t1 = time.perf_counter()\n f.write(str(t1-t0) + '\\r\\n')\n \n f.close()\n#==========================\nmain()\ninput (\"press enter to end\")\n","repo_name":"AmirhoseinBodaghi/TwitterPolicyProject","sub_path":"Merged_File_Reading.py","file_name":"Merged_File_Reading.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"26917963255","text":"class Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n inf = float('inf')\n sum = [[inf for j in range(n)] for i in range(m)]\n sum[0][0] = grid[0][0]\n for i in range(m):\n for j in range(n):\n if i-1>=0:\n sum[i][j] = min(sum[i][j], sum[i-1][j] + grid[i][j])\n if j-1>=0:\n sum[i][j] = min(sum[i][j], sum[i][j-1] + grid[i][j])\n return sum[-1][-1]","repo_name":"tlxxzj/leetcode","sub_path":"64. Minimum Path Sum.py","file_name":"64. Minimum Path Sum.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"6262306059","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom torch.utils.data import DataLoader\n\nfrom modelmanager import run\nfrom didson.data import SequenceDataset\nfrom didson.model import models\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ntrainpath = \"labeled\"\ntestpath = \"labeled_test\"\n\ntrainset = SequenceDataset(trainpath)\ntrainloader = DataLoader(trainset, batch_size=1, shuffle=True, num_workers=2)\n\ntestset = SequenceDataset(testpath)\ntestloader = DataLoader(testset, batch_size=1, shuffle=False, num_workers=2)\n\n\nclass Embedding(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(2, 8, 3, 1, 1)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(8, 16, 3, 2, 1)\n self.conv3 = nn.Conv2d(16, 64, 1, 1, 0)\n\n def forward(self, x, mask):\n x = torch.cat((x, mask), 0)\n x = x.unsqueeze(0)\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = self.conv3(x)\n return x.squeeze(0)\n\n\nclass RNN(nn.Module):\n def __init__(self, config=\"imagenet_trained.json\", hidden_size=15*64):\n super().__init__()\n self.hidden_size = hidden_size\n self.embedding = run(models, config).net.resnet\n for p in self.embedding.parameters():\n p.requires_grad = False\n self.frame_conv = nn.Conv2d(64, 64, kernel_size=1)\n self.mask_conv = nn.Conv2d(64, 64, kernel_size=1)\n self.center_embed = nn.Linear(2, hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size)\n\n def trainable_parameters(self):\n return (\n list(self.frame_conv.parameters()) +\n list(self.mask_conv.parameters()) +\n list(self.center_embed.parameters()) +\n list(self.gru.parameters())\n )\n\n def forward(self, input, hidden):\n frame, mask, center = input\n self.embedding.eval()\n embedded = self.embedding(torch.cat((frame, mask), 0))\n embedded = self.conv1(embedded)\n frame, mask = embedded.chunk(2)\n frame = self.frame_conv(frame)\n mask = self.mask_conv(mask)\n embedded = F.tanh(frame) * F.sigmoid(mask).view(1, 1, -1)\n center = self.center_embed(center.view(1, -1)).view(1, 1, -1)\n output = embedded + center\n output, hidden = self.gru(output, hidden)\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=device)\n\n\nclass Predictor(nn.Module):\n def __init__(self, hidden_size=10):\n super().__init__()\n self.hidden_size = hidden_size\n self.rnn = RNN(hidden_size)\n self.predictor = nn.Linear(hidden_size, 3)\n\n def trainable_parameters(self):\n return (\n self.rnn.trainable_parameters() +\n list(self.predictor.parameters()))\n\n def forward(self, x):\n frame, mask, center = x\n frame = frame.to(device=device).squeeze(0)\n mask = mask.to(device=device).squeeze(0)\n center = center.to(device=device).squeeze(0)\n\n input_length = frame.size(0)\n encoder_hidden = self.rnn.initHidden()\n\n encoder_output = torch.zeros(self.hidden_size, device=device)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = self.rnn(\n (frame[ei], mask[ei], center[ei]), encoder_hidden)\n return self.predictor(encoder_output).squeeze(0)\n\n\npredictor = Predictor(15*64).to(device=device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(predictor.trainable_parameters(), lr=0.0001)\n\nfor epoch in range(2): # loop over the dataset multiple times\n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n optimizer.zero_grad()\n inputs, labels = data\n labels = labels.to(device=device)\n prediction = predictor(inputs)\n loss = criterion(prediction, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n if i % 500 == 499: # print every 100 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 500))\n running_loss = 0.0\n\ncorrect = 0\ntotal = 0\ncounts = {\n 0: {0: 0, 1: 0, 2: 0},\n 1: {0: 0, 1: 0, 2: 0},\n 2: {0: 0, 1: 0, 2: 0},\n}\nwith torch.no_grad():\n for data in testloader:\n inputs, labels = data\n labels = labels.to(device=device)\n outputs = predictor(inputs)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n out = labels.numpy()[0]\n pred = predicted.numpy()[0]\n counts[out][pred] += 1\n\nprint('Accuracy of the network on the test sequences: %d %%' % (\n 100 * correct / total))\nprint(counts)\n","repo_name":"safnuk/DIDSON.jl","sub_path":"didson/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"74231475150","text":"#!/usr/bin/env python\nimport rospy\nimport roslib; roslib.load_manifest('pcl_eod')\n\nfrom pcl_eod.msg import Clusters\n\nimport numpy\nimport tf\n\nclass ClusterSub(Exception):\n br = tf.TransformBroadcaster()\n def __init__(self):\n rospy.init_node(\"cluster\")\n rospy.logwarn(\"EOD Cluster Organizing\")\n self.initSubAndPub() \n \n \n def initSubAndPub(self): \n #Init the subscribers \n rospy.loginfo(\"In Sub and pub Func\")\n rospy.Subscriber(\"clusters\", Clusters, self.ClustersCb)\n #Init the publishers\n self.clusterPub = rospy.Publisher('obstacles', Clusters)\n \n def segment(selfs):\n pass\n \n def ClustersCb(self, data):\n for i in range(len(data.minpoint)):\n mp = data.minpoint[i]\n xp = data.maxpoint[i]\n self.br.sendTransform([mp.x, mp.y, mp.z], [0,0,0,1], rospy.Time.now(), \"obs\"+str(i), \"/camera\")\n j = 0\n for p in numpy.linspace(data.minpoint[i].x, data.maxpoint[i].x, 10):\n self.br.sendTransform([p, mp.y, mp.z], [0,0,0,1], rospy.Time.now(), \"obs\"+str(i)+str(j), \"/camera\")\n j += 1\n\nif __name__ == \"__main__\": \n cls = ClusterSub()\n rospy.spin()\n rospy.logwarn(\"Exiting EOD Navigation! Bye Bye\")\n\n\n\n\n\n\n","repo_name":"ashokzg/eod","sub_path":"pcl_eod/src/obsFinder.py","file_name":"obsFinder.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"40973635657","text":"# Hangman Game\nimport random\n\nmyWords=open(\"Words.txt\", \"r\")\n\ntemp=myWords.read()\nwordList=temp.split(\",\")\n\nmyWords.close()\n\ndef show_chances(chances):\n if chances==5:\n return \"\\n O\\n\"\n elif chances==4:\n return \"\\n O\\n |\"\n elif chances==3:\n return \"\\n O\\n/|\"\n elif chances==2:\n return \"\\n O\\n/|\\\\\"\n elif chances==1:\n return \"\\n O\\n/|\\\\\\n/\"\n elif chances==0:\n return \"\\n O\\n/|\\\\\\n/ \\\\\"\n\nsecretWord=random.choice(wordList).lower() #to make sure every letter is in lowercase\nlength=len(secretWord)\nchances=6\nguessList=[]\nprint(\"Welcome to Hangman Game!\")\nprint(\"_ \"*length)\nprint(\"You have 6 chances.\\n\")\nwhile chances>0:\n wordLeft=0\n guess=input(\"Guess a letter. Your guess: \")\n if guess.isalpha() & len(guess)==1: #The input must be only one letter\n if guess in guessList: #The repeated letters will not be tested.\n print(\"This letter is already guessed. Try another letter.\")\n else:\n guess=guess.lower() #change it into lowercase if it is upper\n guessList.append(guess)\n for item in secretWord:\n if item in guessList:\n print(item, end=\" \")\n else:\n print(\"_\", end=\" \")\n wordLeft+=1\n if guess in secretWord:\n print(\"\\nYou are correct!\")\n else:\n chances-=1\n print(\"\\nSorry! Wrong Guess\")\n print(show_chances(chances))\n if chances==0:\n print(\"\\nGame Over! You lost!\")\n print(\"The secret word is '\"+ secretWord + \"'\")\n if wordLeft==0:\n print(\"Congratulations! You won!!\")\n break\n else:\n print(\"Invalid Input! Please Try again!\")\nprint(\"\\nThanks for playing Hangman Game!\")","repo_name":"HtetAungHlaing21/Hangman_Game","sub_path":"Hangman Game.py","file_name":"Hangman Game.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"13930820791","text":"from datetime import datetime\nimport platform\nimport random\nimport time\n\n# Make sure pyautogui was installed as instructed in the readme\ntry:\n import pyautogui as screen\nexcept:\n print(\"There was an error loading pyautogui. Please ensure it is installed correctly.\\n(see readme)\\n\\nPress ENTER to exit...\")\n input(\"\")\n exit()\n\n# Check for errors loading custom libraries. Expect incorrect entries in config values to be frequent by novice users.\ntry:\n from config import TIME_IN_SECONDS, PLACEMENT, TIME_WARN\n from utils import print_error, runtime_output, interrupt_output, exit_output, PLACEMENT_ERROR, OS_ERROR, TIME_ERROR, TIME_WARNING, DEFAULT_ERROR\nexcept:\n print(\"************************************************************\\n\")\n print(\"There was error loading the program.\\n\\nThis is probably because a value in the config.py file was entered incorrectly.\\n\\nPlease do the following:\\n\\t- Open the config.py file.\\n\\t- Follow the instructions in the file to set the values correctly.\\n\\n\\nIf the problem continues, ensure Python is installed correctly. (see readme)\\n\")\n print(\"************************************************************\\n\\n\\n\")\n print(\"Press ENTER to exit...\")\n input(\"\")\n exit()\n\n# Function to make sure TIME_IN_SECONDS variable from config.py is an integer with error handling.\ndef check_time_for_integer(num):\n int_check = 0\n try:\n int_check = int(num)\n if int_check < 5:\n print_error(TIME_ERROR)\n return int_check\n except:\n print_error(TIME_ERROR)\n\n\n# Function to read PLACEMENT variable from config.py with error handling.\ndef determine_placement():\n if PLACEMENT == \"TOP\":\n return y - (y - 5)\n elif PLACEMENT == \"BOTTOM\":\n return y - 5\n else:\n print_error(PLACEMENT_ERROR)\n\n# Function for determining OS information and clear message.\ndef determine_OS():\n OS_platform = platform.system()\n\n clear_message = \"\"\n name = \"\"\n\n if OS_platform == \"Windows\":\n clear_message = \"cls\"\n name = \"Windows\"\n elif OS_platform == \"Linux\":\n clear_message = \"clear\"\n name = \"Linux\"\n elif OS_platform == \"Darwin\":\n clear_message = \"clear\"\n name = \"MacOS\"\n else:\n print_error(OS_ERROR)\n \n return {\"name\": name, \"message\": clear_message}\n\n\n# This infinite loop:\n# - Generates 2 random (x,y) coordinates\n# - Moves and clicks mouse\n# - Displays main program output\ndef movement_loop():\n\n counter = 0\n amount_of_time = 0.0\n\n try:\n while True:\n\n # Generate 2 random (x,y) coordinates\n x1 = random.randint(0, x)\n y1 = random.randint(0, y)\n\n x2 = random.randint(0, x)\n y2 = random.randint(0, y)\n\n\n # Move and click mouse\n screen.moveTo(x1, y1)\n screen.moveTo(x2, x2)\n screen.click(x/2, screen_placement)\n\n\n # Display main program output\n runtime_output(system_clear_message, OS_name, start_time_display, amount_of_time)\n\n\n # Adjust counter and amount of time program has been running\n counter = counter + 1\n amount_of_time = round((counter * time_converted)/60, 2)\n\n\n # Warn user if tie interval is greater than 60 seconds\n if time_converted > 60 and TIME_WARN == True:\n print(TIME_WARNING)\n\n\n # Sleep for time interval specified by user.\n time.sleep(time_converted)\n\n except KeyboardInterrupt:\n end_time = datetime.now().strftime(\"%H:%M:%S\")\n interrupt_output(system_clear_message, start_time_display, end_time, amount_of_time)\n\n# Main Function\nif __name__ == \"__main__\":\n try:\n\n # Record the start time of the program\n start_time_display = datetime.now().strftime(\"%H:%M:%S\")\n\n # Get TIME_IN_SECONDS from config.py and validate\n time_converted = check_time_for_integer(TIME_IN_SECONDS)\n\n # Get the screen size\n x, y = screen.size()\n\n # Get and set the OS and system clear message\n system_info = determine_OS()\n OS_name = system_info[\"name\"]\n system_clear_message = system_info[\"message\"]\n\n #Get PLACEMENT value from config.py and validate\n screen_placement = determine_placement()\n\n # Move the mouse on set time interval for moving the mouse. Stops on KeyboardInterrupt (CTRL+C)\n movement_loop()\n\n except:\n \n # If there is an unhandled error, print default error.\n print_error(DEFAULT_ERROR)\n\n finally:\n\n # Notify the user the program has ended.\n exit_output(system_clear_message)","repo_name":"DavidMiles1925/mouse_mover","sub_path":"mousemove.py","file_name":"mousemove.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"6592764483","text":"import time\nimport fire\nimport queue\nimport prompt_toolkit\nimport threading\nimport sys\n\nfrom prompt_toolkit.input import create_input\nfrom prompt_toolkit.keys import Keys\n\nfrom chatgpt import ChatBot\nfrom speech_recognition import get_recognizer\n\nbot = ChatBot()\n\n\nclass AiBotFire(object):\n @staticmethod\n def __ask_and_speak(prompt, need_speak=True):\n print_queue = queue.Queue()\n synthesize_queue = queue.Queue()\n speak_queue = queue.Queue()\n\n def print_answer():\n while True:\n try:\n text = print_queue.get(timeout=3)\n sys.stdout.write(text)\n sys.stdout.flush()\n except queue.Empty:\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n return\n\n def synthesize_answer():\n if not need_speak:\n return\n current = []\n cnt = 1\n while True:\n try:\n word = synthesize_queue.get(timeout=3)\n current.append(word)\n\n def endswith(text):\n symbols = [\",\", \".\", \"?\", \"!\", \"'\", '\"']\n for symbol in symbols:\n if text.endswith(symbol):\n return True\n\n if endswith(word):\n threshold = cnt * 16\n if threshold > 128:\n threshold = 128\n if len(current) < threshold:\n continue\n speak_queue.put_nowait(\"\".join(current))\n current = []\n cnt += 1\n continue\n except queue.Empty:\n if current:\n speak_queue.put_nowait(\" \".join(current))\n speak_queue.put_nowait(\"IM_EOF\")\n return\n\n def speak_answer():\n from speech_recognition import synthesize_and_speak\n synthesize_and_speak(speak_queue)\n\n printer_thread = threading.Thread(target=print_answer)\n synthesizer_thread = threading.Thread(target=synthesize_answer)\n speaker_thread = threading.Thread(target=speak_answer)\n printer_thread.start()\n synthesizer_thread.start()\n speaker_thread.start()\n for word in bot.ask(prompt):\n print_queue.put_nowait(word)\n synthesize_queue.put_nowait(word)\n printer_thread.join()\n synthesizer_thread.join()\n speaker_thread.join()\n\n @staticmethod\n def text_conversation():\n from speech_recognition import init\n init()\n while True:\n prompt = prompt_toolkit.prompt(\"you:\")\n AiBotFire.__ask_and_speak(prompt, True)\n\n @staticmethod\n def voice_conversation():\n from speech_recognition import init\n init()\n\n def recognize_and_answer():\n recognizer = get_recognizer()\n data = []\n\n def handle_final_result(evt):\n print(evt.result.text)\n data.append(evt.result.text)\n sys.stdout.write(evt.result.text)\n sys.stdout.flush()\n\n recognizer.recognized.connect(handle_final_result)\n recognizer.start_continuous_recognition()\n input = create_input()\n while True:\n press_enter = False\n for key_press in input.read_keys():\n print(key_press.key)\n if key_press.key == Keys.Escape:\n recognizer.stop_continuous_recognition()\n return\n if key_press.key == Keys.ControlJ:\n press_enter = True\n break\n if press_enter is True:\n break\n recognizer.stop_continuous_recognition()\n AiBotFire.__ask_and_speak(\" \".join(data))\n data.clear()\n\n while True:\n print(\"Speak into your microphone.\")\n recognize_and_answer()\n\n\ndef main():\n fire.Fire(AiBotFire)\n\n\nif __name__ == '__main__':\n fire.Fire(AiBotFire)\n","repo_name":"faycheng/chatGPT-voice-cli","sub_path":"pkg/chatbot_cli.py","file_name":"chatbot_cli.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"13111352801","text":"\"\"\"PRAW exception classes.\n\nIncludes two main exceptions: :class:`.APIException` for when something goes\nwrong on the server side, and :class:`.ClientException` when something goes\nwrong on the client side. Both of these classes extend :class:`.PRAWException`.\n\nAll other exceptions are subclassed from :class:`.ClientException`.\n\n\"\"\"\nfrom typing import Optional\n\n\nclass PRAWException(Exception):\n \"\"\"The base PRAW Exception that all other exception classes extend.\"\"\"\n\n\nclass APIException(PRAWException):\n \"\"\"Indicate exception that involve responses from Reddit's API.\"\"\"\n\n def __init__(self, error_type: str, message: str, field: Optional[str]):\n \"\"\"Initialize an instance of APIException.\n\n :param error_type: The error type set on Reddit's end.\n :param message: The associated message for the error.\n :param field: The input field associated with the error if available.\n \"\"\"\n error_str = \"{}: '{}'\".format(error_type, message)\n if field:\n error_str += \" on field '{}'\".format(field)\n\n super().__init__(error_str)\n self.error_type = error_type\n self.message = message\n self.field = field\n\n\nclass ClientException(PRAWException):\n \"\"\"Indicate exceptions that don't involve interaction with Reddit's API.\"\"\"\n\n\nclass DuplicateReplaceException(ClientException):\n \"\"\"Indicate exceptions that involve the replacement of MoreComments.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the class.\"\"\"\n super().__init__(\n \"A duplicate comment has been detected. Are you attempting to call\"\n \" ``replace_more_comments`` more than once?\"\n )\n\n\nclass InvalidImplicitAuth(ClientException):\n \"\"\"Indicate exceptions where an implicit auth type is used incorrectly.\"\"\"\n\n def __init__(self):\n \"\"\"Instantize the class.\"\"\"\n super().__init__(\n \"Implicit authorization can only be used with installed apps.\"\n )\n\n\nclass InvalidURL(ClientException):\n \"\"\"Indicate exceptions where an invalid URL is entered.\"\"\"\n\n def __init__(self, url: str, message: str = \"Invalid URL: {}\"):\n \"\"\"Initialize the class.\n\n :param url: The invalid URL.\n :param message: The message to display. Must contain a format\n identifier (``{}`` or ``{0}``). (default: ``\"Invalid URL: {}\"``)\n \"\"\"\n super().__init__(message.format(url))\n\n\nclass MissingRequiredAttributeException(ClientException):\n \"\"\"Indicate exceptions caused by not including a required attribute.\"\"\"\n\n\nclass WebSocketException(ClientException):\n \"\"\"Indicate exceptions caused by use of WebSockets.\"\"\"\n\n def __init__(self, message: str, exception: Exception):\n \"\"\"Initialize a WebSocketException.\n\n :param message: The exception message.\n :param exception: The exception thrown by the websocket library.\n \"\"\"\n super().__init__(message)\n self.original_exception = exception\n","repo_name":"gruiz28/praw","sub_path":"praw/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"83"} +{"seq_id":"39302228454","text":"import requests\n\n\nclass HTTP:\n\n def __init__(self, token, url):\n self.headers = {\n \"Authorization\": \"Bearer \" + token,\n \"Accept\": \"application/vnd.api+json\"\n }\n self.r = None\n self.response = self.make_request(url)\n self.json = self.response.json()\n\n def make_request(self, endpoint):\n self.r = requests.get(endpoint, headers=self.headers)\n return self.r\n","repo_name":"byWambo/PUBG.py","sub_path":"pubg/http/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"41706580043","text":"\"\"\"Contains miscellaneous functions to communicate using sound and text.\"\"\"\nfrom pathlib import Path\n\nimport pygame\n\nimport constants\n\n\ndef play_sound(sound: str, volume: float = 0.5) -> None:\n \"\"\"Plays the specified sound.\"\"\"\n sound = pygame.mixer.Sound(Path.cwd() / 'src' / 'assets' / 'sounds' / f'{sound}.wav')\n sound.set_volume(volume)\n sound.play()\n\n\ndef get_font():\n return pygame.font.Font(Path.cwd() / 'src' / 'assets' / 'font.ttf', 48)\n\n\ndef make_centered_text(screen: pygame.Surface,\n text: str,\n center: tuple = (constants.SCREEN_WIDTH / 2, constants.OFFSET)) -> None:\n \"\"\"Write text centered at a position.\"\"\"\n font = get_font()\n title = font.render(text, True, constants.COLOR_FG)\n title_rect = title.get_rect(center=center)\n screen.blit(title, title_rect)\n\n\ndef make_aligned_text(screen: pygame.Surface, text: str, position: tuple) -> None:\n \"\"\"Write text starting at a specified position.\"\"\"\n font = get_font()\n text = font.render(text, True, constants.COLOR_FG)\n screen.blit(text, position)\n\n\ndef display_header(screen: pygame.Surface, header: str) -> None:\n \"\"\"Flushes screen and displays the header.\"\"\"\n screen.fill(constants.COLOR_BG)\n make_centered_text(screen, constants.TITLE)\n make_centered_text(screen, header, (constants.SCREEN_WIDTH / 2, 2 * constants.OFFSET))\n\n\ndef display_options(screen: pygame.Surface, options: list) -> None:\n \"\"\"Display a list of numbered options.\"\"\"\n for i, option in enumerate(options, 1):\n number_position = (constants.OFFSET, (2 + i) * constants.OFFSET)\n make_aligned_text(screen, f'{i}.', number_position)\n\n option_position = (constants.INDENT * constants.OFFSET, (2 + i) * constants.OFFSET)\n make_aligned_text(screen, option, option_position)\n\n\ndef display_controls(screen: pygame.Surface) -> None:\n \"\"\"Display a menu of controls.\"\"\"\n categories = {\n 'LEFT PADDLE': ('MOVE UP: W', 'MOVE DOWN: S'),\n 'RIGHT PADDLE': ('MOVE UP: I / UP', 'MOVE DOWN: K / DOWN'),\n 'MENUS': ('MAIN MENU: ESC', 'NEW POINT: SPACE')\n }\n\n i = 3\n for category, controls in categories.items():\n make_aligned_text(screen, category, (constants.OFFSET, i * constants.OFFSET))\n for j, control in enumerate(controls, 1):\n make_aligned_text(screen, control, (constants.INDENT * constants.OFFSET, (i + j) * constants.OFFSET))\n i += 1 + j\n\n\ndef prompt_end_of_point(screen: pygame.Surface, rally_length: int, scores: dict) -> None:\n \"\"\"Play a sound and display the score and a prompt to press space at the end of a point.\"\"\"\n play_sound('end')\n make_centered_text(screen, f'RALLY LENGTH: {rally_length}',\n (3 * constants.SCREEN_WIDTH / 4, constants.SCREEN_HEIGHT - constants.OFFSET))\n make_centered_text(screen, f'{scores[\"left\"]} - {scores[\"right\"]}',\n (constants.SCREEN_WIDTH / 4, constants.SCREEN_HEIGHT - constants.OFFSET))\n pygame.display.update()\n","repo_name":"KarstenEconomou/pong-clone","sub_path":"src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"36835008787","text":"# Import TensorFlow\nimport tensorflow as tf\n\n# Import Keras\nfrom tensorflow import keras\n\n# Import NumPy\nimport numpy as np\n\n# Download the IMDB dataset\nimdb = keras.datasets.imdb\n\n# The argument num_words = 10000 keeps the top 10,000 most frequent occurring words in the training data.\n(train_data, train_labels),(test_data,test_labels) = imdb.load_data(num_words=10000)\n\n# Explore the data\nprint(\"Training entries: {}, labels: {}\".format(len(train_data),len(train_labels)))\n\n# Each integer represents a specific word in a dictionary.\nprint(train_data[0])\n\n# Movie reviews may be of different lengths.\nprint(len(train_data[0]),len(train_data[1]))\n\n####################################\n\n# Convert the integers back to words\nword_index = imdb.get_word_index()\n\n# The first indices are reserved\nword_index = {k:(v+3) for k,v in word_index.items()}\nword_index[\"\"] = 0\nword_index[\"\"] = 1\nword_index[\"\"] = 2 # unknown\nword_index[\"\"] = 3\n\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n\ndef decode_review(text):\n return ' '.join([reverse_word_index.get(i, '?') for i in text])\n\n####################################\n\n# Display the text for the first review\nprint(decode_review(train_data[0]))\n\n# Use pad_sequences to standardize the lengths\ntrain_data = keras.preprocessing.sequence.pad_sequences(train_data,\n value=word_index[\"\"],\n padding='post',\n maxlen=256)\n\ntest_data = keras.preprocessing.sequence.pad_sequences(test_data,\n value=word_index[\"\"],\n padding='post',\n maxlen=256)\n\n# Look at the length of the examples\nprint(len(train_data[0]))\nprint(len(train_data[1]))\n\n# Look at the padded first review\nprint(train_data[0])\nprint(decode_review(train_data[0]))\n\n# The size (See line 13)\nvocab_size = 10000\n\n# The architecture\n\n# This is a sequential model, meaning the layers are stacked.\nmodel = keras.Sequential()\n\n# The first layer is an Embedding layer. This layer takes the integer-encoded vocabulary and looks up\n# the embedding vector for each word-index. These vectors are learned as the model trains. The vectors\n# add a dimension to the output array. The resulting dimensions are: (batch, sequence, embedding).\nmodel.add(keras.layers.Embedding(vocab_size, 16))\n\n# A GlobalAveragePooling1D layer returns a fixed-length output vector for each example by averaging\n# over the sequence dimension. This allows the model to handle input of variable length, in the\n# simplest way possible.\nmodel.add(keras.layers.GlobalAveragePooling1D())\n\n# This fixed-length output vector is piped through a fully-connected layer with 16 hidden units.\nmodel.add(keras.layers.Dense(16, activation=tf.nn.relu))\n\n# The last layer is densely connected with a single output node. Using the sigmoid activation function,\n# this value is a float between 0 and 1, representing a probability, or confidence level.\nmodel.add(keras.layers.Dense(1, activation=tf.nn.sigmoid))\n\n# A summary of the model\nmodel.summary()\n\n# Configure the model with an optimizer and a loss function\nmodel.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\n# Create a validation set\nx_val = train_data[:10000]\npartial_x_train = train_data[10000:]\ny_val = train_labels[:10000]\npartial_y_train = train_labels[10000:]\n\n# Train the model\nhistory = model.fit(partial_x_train,\n partial_y_train,\n epochs=40,\n batch_size=512,\n validation_data=(x_val, y_val),\n verbose=1)\n\n# Evaluate the model\nresults = model.evaluate(test_data, test_labels)\nprint(results)","repo_name":"chenyueg/keras-demo","sub_path":"keras_demo.py","file_name":"keras_demo.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"15206652983","text":"from discord import PartialEmoji\nfrom discord.ext import commands\nimport yaml\n\ndata = {}\n\nwith open(\"src/config.yml\", 'r') as stream:\n data = yaml.safe_load(stream)\n\nclass SenateCogs(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n chid = data.get(\"senate_channel\")\n guild = payload.member.guild\n channel = guild.get_channel(chid)\n role = guild.get_role(data.get(\"senate_role\"))\n emoji = payload.emoji.name\n msg = await channel.fetch_message(payload.message_id)\n buysell = {\"buynow\":\"<:buynow:845805676499435541>\", \"sellnow\":\"<:sellnow:845805705683271690>\"}\n buynum = 0\n sellnum = 0\n\n for reaction in msg.reactions:\n if type(reaction.emoji) is PartialEmoji:\n if reaction.emoji.name == \"buynow\":\n buynum = reaction.count\n elif reaction.emoji.name == \"sellnow\":\n sellnum = reaction.count\n\n if payload.channel_id == chid:\n if emoji == 'buynow' or emoji == 'sellnow':\n if role not in payload.member.roles:\n await msg.remove_reaction(payload.emoji, payload.member)\n if(data.get(\"atv\")):\n await self.trg.send(\":no_entry: \" + payload.member.name + \" tried to react with \" + buysell.get(payload.emoji.name))\n else:\n if(data.get(\"atv\")):\n await self.trg.send(\":white_check_mark: \" + payload.member.name + \" reacted with \" + buysell.get(payload.emoji.name) + \"\\n\"\n \"<:buynow:845805676499435541> **\" + str(buynum) + \"** | **\" + str(sellnum) + \"** <:sellnow:845805705683271690>\")\n \n @commands.Cog.listener()\n async def on_ready(self):\n if data.get(\"atv\"):\n self.trg = await self.bot.fetch_user(data.get(\"trg\"))\n print('Ready :)')\n\ndef setup(bot):\n bot.add_cog(SenateCogs(bot))","repo_name":"notbnbn/botlitical","sub_path":"src/cogs/senatecogs.py","file_name":"senatecogs.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"1727234981","text":"\n\nimport tensorflow as tf\nimport numpy as np\nimport logging\nfrom datetime import datetime\nimport os\nimport time\nfrom util import Progbar, minibatches\nimport argparse\nfrom tensorflow.python.platform import gfile\n\nfrom tensorflow.contrib import rnn\nfrom tensorflow.python.platform import gfile\n\n\nPAD_ID = 0\nSOS_ID = 1\nUNK_ID = 2 \n\nlogger = logging.getLogger(\"final_project\")\nlogger.setLevel(logging.DEBUG)\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n\nmodel_path = \"\"\n\nclass Config(object):\n\t\"\"\"Holds model hyperparams and data information.\n\n\tThe config class is used to store various hyperparameters and dataset\n\tinformation parameters. Model objects are passed a Config() object at\n\tinstantiation.\n\n\tCHECK WHICH VALUES WE ACTUALLY NEED AND MODIFY THEM\n\t\"\"\"\n\tdropout = 0.5\n\tembed_size = 100\n\tencoder_hidden_size = 200\n\tdecoder_hidden_size = encoder_hidden_size\n\tbatch_size = 50 # batch size was previously 2048\n\tn_epochs = 10\n\tlr = 0.001\n\tmax_sentence_len = 20\n\tvocab_size = 10000\n\n\tdef __init__(self):\n\t\tself.output_path = \"results/{:%Y%m%d_%H%M%S}/\".format(datetime.now())\n\t\tos.makedirs(self.output_path)\n\t\tself.model_output = self.output_path + \"model.weights\"\n\t\tself.log_output = self.output_path + \"log\"\n\t\tself.vocabulary = self.init_vocab()\n\t\tself.preds_output = self.output_path + \"preds\"\n\n\tdef init_vocab(self):\n\t\tvocab_path = 'data/summarization/vocab.dat'\n\t\tif gfile.Exists(vocab_path):\n\t\t\tvocab = []\n\t\t\twith gfile.GFile(vocab_path, mode=\"r\") as f:\n\t\t\t\tvocab.extend(f.readlines())\n\t\t\tvocab = [line.strip('\\n') for line in vocab]\n\t\t\treturn vocab\n\nclass RNN(object):\n\tdef __init__(self, config):\n\t\tself.save_predictions = False\n\t\tself.config = config\n\t\tloaded = np.load('data/summarization/glove.trimmed.{}.npz'.format(str(self.config.embed_size)))\n\t\tself.embedding_matrix = loaded['glove']\n\t\tself.build()\n\n\tdef __nonzero__(self):\n\t\treturn self.save_predictions != 0\n\n\tdef add_placeholders(self):\n\t\tself.encoder_inputs_placeholder = tf.placeholder(tf.int32, shape=([None, self.config.max_sentence_len]))\n\t\tself.labels_placeholder = tf.placeholder(tf.int32, shape=([None, self.config.max_sentence_len]))\n\t\tself.mask_placeholder = tf.placeholder(tf.bool, shape=([None, self.config.max_sentence_len])) # batch_sz x max_sentence_length\n\t\tself.sequence_placeholder = tf.placeholder(tf.int32, shape=([None]))\n\n\tdef create_feed_dict(self, inputs_batch, unstacked_labels_batch=None, stacked_labels_batch=None, sequence_batch=None, mask_batch=None):\n\t\tfeed_dict = {\n\t\t\tself.encoder_inputs_placeholder: inputs_batch,\n\t\t}\n\n\t\tif stacked_labels_batch is not None:\n\t\t\tfeed_dict[self.stacked_labels_placeholder] = stacked_labels_batch\n\n\t\tif mask_batch is not None:\n\t\t\tfeed_dict[self.mask_placeholder] = mask_batch\n\t\tif sequence_batch is not None:\n\t\t\tfeed_dict[self.sequence_placeholder] = sequence_batch\n\t\treturn feed_dict\n\n\n\tdef add_embedding(self, placeholder):\n\t\t\"\"\"Adds an embedding layer that maps from input tokens (integers) to vectors and then\n\t\tconcatenates those vectors:\n\n\t\t\t- Create an embedding tensor and initialize it with self.pretrained_embeddings.\n\t\t\t- Use the input_placeholder to index into the embeddings tensor, resulting in a\n\t\t\t tensor of shape (None, max_length, n_features, embed_size).\n\t\t\t- Concatenates the embeddings by reshaping the embeddings tensor to shape\n\t\t\t (None, max_length, n_features * embed_size).\n\n\t\tReturns:\n\t\t\tembeddings: tf.Tensor of shape (None, max_length, embed_size)\n\t\t\"\"\"\n\t\t### YOUR CODE HERE (~4-6 lines)\n\t\tembedding_tensor = tf.Variable(self.embedding_matrix)\n\t\tlookup_tensor = tf.nn.embedding_lookup(embedding_tensor, placeholder)\n\t\t#embeddings = tf.reshape(lookup_tensor, [-1, self.config.max_sentence_len, self.config.embed_size])\n\t\t### END YOUR CODE\n\t\treturn lookup_tensor\n\n\t# Handles a single batch, returns the outputs\n\tdef add_pred_single_batch_train(self):\n\t\twith tf.variable_scope(tf.get_variable_scope()):\n\t\t\tinput_sequence_lengths = self.sequence_placeholder\n\t\t\tencoder_outputs, final_enc_state = self.encode() # TODO: gather sequence lengths\n\t\t\tpreds = self.decode_train(encoder_outputs, final_enc_state)\n\n\t\treturn preds # [batch_size, max_sentence_len, vocab_size]\n\n\tdef encode(self):\n\n\t\t#inputs: [batch_size x max_sentence_length x embed_size]\n\t\t#sequence_length: [batch_size] vector containing actual length for each sequence\n\n\t\t# encoder_hidden_size is considered the size of the concatenation of the forward and backward cells\n\t\tinput_sequence_lengths = self.sequence_placeholder # [batch_size] tensor of the lengths of each input sentence in the batch\n\t\tx = self.add_embedding(self.encoder_inputs_placeholder) # [batch_sz, max_sentence_len, embed_sz]\n\n\t#\tfw_cell2 = tf.nn.rnn_cell.LSTMCell(num_units=.5 * self.config.encoder_hidden_size, initializer=tf.contrib.layers.xavier_initializer())\n\t#\tbckwd_cell2 = tf.nn.rnn_cell.LSTMCell(num_units=.5 * self.config.encoder_hidden_size, initializer=tf.contrib.layers.xavier_initializer())\n\n\t\tfw_cell = tf.contrib.rnn.LSTMCell(.5 * self.config.encoder_hidden_size, initializer=tf.contrib.layers.xavier_initializer())\n\t\tbckwd_cell = tf.contrib.rnn.LSTMCell(.5 * self.config.encoder_hidden_size, initializer=tf.contrib.layers.xavier_initializer())\n\n\t\toutputs, final_state = tf.nn.bidirectional_dynamic_rnn(cell_fw=fw_cell, cell_bw=bckwd_cell, \\\n\t\t\tinputs=x, sequence_length=input_sequence_lengths, dtype=tf.float64)\n\n\t#\toutputs_fw, outputs_bw = outputs\n\t#\toutputs_fw = tf.cast(outputs_fw, tf.float32)\n\t#\toutputs_bw = tf.cast(outputs_bw, tf.float32)\n\n\t\tconcat_outputs = tf.concat(outputs, 2) # dimension: [batch_size x max_sentence_length x encoder_hidden_size]\n\n\t\tfinal_state_fw, final_state_bw = final_state\n\n\t\tfinal_state = tf.concat([final_state_fw[1], final_state_bw[1]], 1)\n\n\t\treturn concat_outputs, final_state # concat_outputs -> attention_values, sequence_length -> attention_values_length\n\t\t# concat_outputs: [batch_size, max_sentence_len, output_size (encoder_hidden_size)]\n\n\n\tdef decode_train(self, attention_values, decoder_start_state):\n\n\t\tinput_embeddings = self.add_embedding(self.labels_placeholder) # truth embeddings. [batch_size x max_sentence_length x embed_size]\n\n\t\tpreds = [] # currently saved as a list, where each elem represents one timestep. TODO: reshape to tensor, where max_sentence_len is second dimension\n\n\t\tcur_hidden_state = None\n\t\tcur_inputs = None\n\n\t\twith tf.variable_scope(\"lstm\") as scope:\n\n\t\t\tfor i in xrange(self.config.max_sentence_len + 1): # max_sequence_length iterations + 1 (+1 for start symbol). starts at 0\n\t\t\t\tif i > 0:\n\t\t\t\t\tscope.reuse_variables()\n\n\t\t\t\tif (i==0): \n\t\t\t\t\tcur_hidden_state = decoder_start_state # shape: [batch_size, decoder_hidden_size]\n\t\t\t\t\tstart_symbol_tensor = tf.constant(value=SOS_ID, dtype=tf.int32, shape=[self.config.batch_size])\n\t\t\t\t\tcur_inputs = self.add_embedding(start_symbol_tensor) # TODO: fairly unsure whether or not this will work. will just try\n\t\t\t\telse:\n\t\t\t\t\t# cur_hidden_state initialized previously at end of for loop\n\t\t\t\t#\tcur_inputs = input_embeddings[:, i-1, :] # desired shape: [batch_size, embed_size]. unsure whether or not this will work (might return as numpy array?)\n\t\t\t\t\tcur_inputs = tf.slice(input_embeddings, [0, i-1, 0], [-1, 1, -1])\n\n\t\t\t\tintermediate_hidden_state = None\n\t\t\t\tif (i==0): # state_is_tuple is true for first cell bc end of encoder function outputs final state in weird ass format\n\t\n\t\t\t\t\tlstmCell = tf.contrib.rnn.LSTMCell(num_units=self.config.decoder_hidden_size, \\\n\t\t\t\t\t\tinitializer=tf.contrib.layers.xavier_initializer(), state_is_tuple=False)\n\t\t\t\t\tintermediate_hidden_state, _ = lstmCell(cur_inputs, cur_hidden_state) # LSTM output has shape: [batch_size, decoder_hidden_size]\n\n\t\t\t\telse:\n\t\t\t\t\tlstmCell = tf.contrib.rnn.LSTMCell(num_units=self.config.decoder_hidden_size, \\\n\t\t\t\t\t\tinitializer=tf.contrib.layers.xavier_initializer(), state_is_tuple=False)\n\t\t\t\t\tintermediate_hidden_state, _ = lstmCell(cur_inputs, cur_hidden_state) # LSTM output has shape: [batch_size, decoder_hidden_size]\n\n\t\t\t\tif (i==0):\n\t\t\t\t\t# layer_inputs = intermediate_hidden_state\n\t\t\t\t\tnext_hidden_state = intermediate_hidden_state\n\t\t\t\telse:\n\t\t\t\t\tattn_scores, context_vector = self.attention_function_simple(intermediate_hidden_state, attention_values, self.sequence_placeholder)\n\t\t\t\t\t\n\t\t\t\t\tlayer_inputs = tf.concat([intermediate_hidden_state, context_vector], 1) # size: [batch_size, 2 * decoder_hidden_size]\n\t\t\t\t\tnext_hidden_state = tf.contrib.layers.fully_connected(inputs=layer_inputs, \\\n\t\t\t\t\t\tnum_outputs=self.config.decoder_hidden_size, activation_fn=tf.nn.tanh, trainable=True) # should be trainable as is\n\n\t\t\t\t\tW_out = tf.get_variable(\"W_out\", shape=[self.config.decoder_hidden_size, self.config.vocab_size], initializer=tf.contrib.layers.xavier_initializer())\n\t\t\t\t\tb_out = tf.get_variable(\"b_out\", shape=[self.config.vocab_size], initializer=tf.constant_initializer(0.0))\n\n\t\t\t\t\tcur_pred = tf.matmul(cur_hidden_state, W_out) + b_out\n\t\t\t\t\tpreds.append(cur_pred)\n\n\t\t\t\tcur_hidden_state = next_hidden_state\n\t\t\t\tprint(\"made it through first iteration of for loop\")\n\n\t\tpreds_tensor_form = tf.stack(preds, axis=1) # axis = 1 so that max_sentence_len will be second dimension\n\n\t\treturn preds_tensor_form # TODO: EOS token? or output one pad token -> fill the rest with pad?\n\n\tdef attention_function_simple(self, cell_output, attention_values, sequence_length): # h{enc_i} dot h{s} ... h{s} represents previous hidden state of decoder\n\n\t\t# cell_output: [batch_size, decoder_hidden_size] (same dimension as concat_outputs) # h(t-1) of decoder\n\t\t# attention_values: [batch_size, max_sentence_len, encoder_hidden_size] ... okay bc we're using global attention\n\n\t#\tW = tf.get_variable(shape=[self.encoder_hidden_size, self.decoder_hidden_size], initializer=tf.contrib.layers.xavier_initializer()) # manually set scope?\n\n\t#\tfirst_dot = tf.matmul(attention_values, W) # [batch_size, max_sentence_len, 2 * encoder_hidden_size]\n\t#\tprint(\"shape of first dot: \")\n\t#\tprint(first_dot.get_shape)\n\n\t\t# global attention. using bilinear formula: ht dot W dot cell_output\n\t\traw_scores = tf.reduce_sum(attention_values * tf.expand_dims(cell_output, 1), [2]) # [batch_sz, max_sentence_len]\n\t\tscores_mask = tf.sequence_mask(lengths=tf.to_int32(sequence_length), maxlen=self.config.max_sentence_len, dtype=tf.float64)\n\t\tattn_scores = raw_scores * scores_mask + ((1.0 - scores_mask) * tf.float64.min) # unsure what exactly this does ... seems to be a typecast\n\t\tprob_distribution = tf.nn.softmax(attn_scores) # [batch_sz, max_sentence_len]\n\t\tcontext_vector = tf.expand_dims(prob_distribution, 2) * attention_values # multiplies each hidden encoder vector by its attention score\n\t\t# context_vectors shape: [batch_sz, max_sentence_len, dec_hidden_size]\n\t\tcontext_vector = tf.reduce_sum(context_vector, 1) # reduced over max_sentence_len dimension bc we're using global attention\n\t\t# unsure if we actually need context.set_shape ... shape should be: [batch_size, dec_hidden_size]\n\n\t\treturn (prob_distribution, context_vector)\n\n\n\t# Handles a single batch, returns the outputs\n\tdef add_pred_single_batch_test(self, W, b):\n\t\t# TODO: \n\t\treturn\n\n\t# assumes we already have padding implemented.\n\n\tdef add_loss_op(self, preds, print_pred=False):\n\n\t\t\"\"\"\n\t\tpreds: [batch_size x max_sent_length x vocab_size]\n\t\tlabels: [batch_size x max_sentence_length] (IDs)\n\n\t\t\"\"\"\n\t\tlabels = self.labels_placeholder\n\t\tce = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=unstacked_labels, logits=preds)\n\t\t# shape of ce: same as labels, with same type as preds [batch_size x max_sentence_length]\n\t\tce = tf.boolean_mask(ce, self.mask_placeholder)\n\t\tloss = tf.reduce_mean(ce)\n\n\t\treturn loss\n\n\n\tdef add_training_op(self, loss):\n\n\t\ttrain_op = tf.train.AdadeltaOptimizer(self.config.lr).minimize(loss) # same optimizer as in IBM paper\n\t\t# Similar to Adagrad, which gives smaller updates to frequent params and larger updates to infrequent parameters.\n\t\t# Improves on Adagrad by addressing Adagrad's aggressive, monotonically decreasing learning rate.\n\n\t\treturn train_op\n\n\t# \n\tdef train_on_batch(self, sess, inputs_batch, labels_batch, mask_batch, sequence_batch):\n\t\tfeed = self.create_feed_dict(inputs_batch=inputs_batch, \\\n\t\t\tstacked_labels_batch=labels_batch, \\\n\t\t\tmask_batch=mask_batch, \\\n\t\t\tsequence_batch=sequence_batch) # TODO: what does sequence_batch mean?\n\t\t_, loss = sess.run([self.train_op, self.train_loss], feed_dict=feed)\n\t\treturn loss\n\n\n\tdef predict_on_batch(self, sess, inputs_batch, labels_batch, mask_batch, sequence_batch, num_of_batch=2, using_dev=True):\n\t\tfeed = self.create_feed_dict(inputs_batch=inputs_batch, \\\n\t\t\tstacked_labels_batch=labels_batch, \\\n\t\t\tmask_batch=mask_batch, \\\n\t\t\tsequence_batch=sequence_batch)\n\n\t\tpreds = None # make sure this is legit\n\t\tloss = None\n\n\t\tif (using_dev):\n\t\t\tpreds, loss = sess.run([self.dev_pred, self.dev_loss], feed)\n\t\telse:\n\t\t\tpreds, loss = sess.run([self.test_pred, self.test_loss], feed)\n\n\t\tif (self.save_predictions == True):\n\t\t\tif num_of_batch % 40 == 0:\n\t\t\t\tself.save_outputs(sess, preds, inputs_batch, labels_batch, num_preds=1)\n\n\t\treturn loss\n\n\tdef save_outputs(self, sess, preds, inputs, titles, num_preds=-1): # shape of each input: [batch_size x max_sentence_length]\n\t\tpreds = tf.stack(preds, axis=1) # new shape: [batch_size, max_sentence_length, vocab_size]\n\t\tpreds = tf.argmax(preds, axis=2) # new shape: [batch_size, max_sentence_length]\n\n\t#\tinputs = self.encoder_inputs_placeholder # shape: [max_sentence_len, batch_size]\n\t#\tinputs = tf.unstack(inputs, axis=0) \n\t\tinputs = tf.transpose(inputs) # new shape: [batch_size, max_sentence_len]\n\n\t\ttitles = tf.transpose(titles)\n\n\t\tinputs_list = tf.unstack(inputs, num=self.config.batch_size) # batch_size elems, each a tensor: [max_sentence_len]\n\t\ttitles_list = tf.unstack(titles, num=self.config.batch_size)\n\t\tpreds_list =tf.unstack(preds, num=self.config.batch_size)\n\n\n\t\twith gfile.GFile(self.config.preds_output, mode=\"a\") as output_file:\n\t\t\tlogger.info(\"Storing predictions in \" + self.config.preds_output)\n\t\t\tfor i, _input in enumerate(inputs_list[:num_preds]):\n\t\t\t\t\n\t\t\t\t_input = _input.eval(session=sess)\n\t\t\t\ttitle = titles_list[i].eval(session=sess)\n\t\t\t\tpred = preds_list[i].eval(session=sess)\n\n\t\t\t\toutput_file.write(\"article (input): \")\n\t\t\t\tfor index in tf.unstack(_input): # input is a numpy array. iterate through it somehow\n\t\t\t\t\tw = self.config.vocabulary[index.eval(session=sess)]\n\t\t\t\t\toutput_file.write(w + \" \")\n\t\t\t\toutput_file.write(\"\\n\")\n\n\t\t\t\toutput_file.write(\"prediction: \")\n\t\t\t\tfor index in tf.unstack(pred):\n\t\t\t\t\tw = self.config.vocabulary[index.eval(session=sess)]\n\t\t\t\t\toutput_file.write(w + \" \")\n\t\t\t\toutput_file.write(\"\\n\")\n\n\t\t\t\toutput_file.write(\"title (truth): \")\n\t\t\t\tfor index in tf.unstack(title):\n\t\t\t\t\tw = self.config.vocabulary[index.eval(session=sess)]\n\t\t\t\t\toutput_file.write(w + \" \")\n\t\t\t\toutput_file.write(\"\\n \\n\")\n\n\t# dev_loss is likely to be much higher than train_loss, since we're feeding in prev outputs (instead of ground truth)\n\t# into the decoder\n\tdef compute_dev_loss(self, sess, input_batches, labels_batches, mask_batches, sequence_batches):\n\n\t\tprog = Progbar(target=1 + len(input_batches))\n\t\ttotal_dev_loss = 0\n\t\tfor i, input_batch in enumerate(input_batches):\n\n\t\t#\tfeed = self.create_feed_dict(inputs_batch=input_batch, stacked_labels_batch=labels_batches[i], mask_batch=mask_batches[i]) #problem: labels has shape: [batch_size x max_sentence_length], should be opposite\n\t\t#\tdev_loss = sess.run(self.dev_loss, feed_dict=feed)\n\t\t\tdev_loss = self.predict_on_batch(sess, inputs_batch=input_batch, labels_batch=labels_batches[i], \\\n\t\t\t\tmask_batch=mask_batches[i], sequence_batch=sequence_batches[i], num_of_batch=i, using_dev=True)\n\n\t\t\ttotal_dev_loss += dev_loss\n\t\t\tprog.update(i + 1, [(\"dev loss\", dev_loss)])\n\t\t\tif i == len(input_batches) - 1:\n\t\t\t\tlogger.info(\"Last batch dev loss: %d\", dev_loss)\n\t\treturn total_dev_loss\n\n\n\tdef run_epoch(self, sess, train_data, dev_data):\n\t\ttrain_input_batches, train_truth_batches, train_mask_batches, train_input_sequence = train_data\n\t\tdev_input_batches, dev_truth_batches, dev_mask_batches, dev_input_sequence = dev_data\n\n\t\tlogger.info(\"number of train input batches: %d\", int(len(train_input_batches)))\n\t\tprog = Progbar(target=1 + len(train_input_batches))\n\n\t\tloss = 0\n\t\tfor i, input_batch in enumerate(train_input_batches):\n\t\t\tloss = self.train_on_batch(sess, input_batch, train_truth_batches[i], train_mask_batches[i], train_input_sequence[i])\n\t\t\tprog.update(i + 1, [(\"train loss\", loss)])\n\t\tlogger.info(\"\\nTrain loss: %d\", loss)\n\n\t\t#\tif self.report: self.report.log_train_loss(loss)\n\t\t#print(\"\")\n\n\t\tdev_loss = self.compute_dev_loss(sess, dev_input_batches, dev_truth_batches, dev_mask_batches, train_input_sequence) # print loss on dev set\n\n\t\treturn dev_loss # TODO: to check where the return value is used\n\n\n\t# function called when working with test set. outputs loss on test set, along with the model's predictions\n\tdef preds_and_loss(self, sess, saver): # not sure which of these params we actually need\n\t\t# TODO: make sure what we're working with is actually 'test.ids.article'\n\t\ttest_input, _, test_input_len = tokenize_data('test.ids.article', self.config.max_sentence_len, False)\n\t\ttest_truth, test_truth_mask, test_truth_len = tokenize_data('test.ids.title', self.config.max_sentence_len, True)\n\n\t\ttest_input_batches = get_stacked_minibatches(test_input, self.config.batch_size)\n\t\ttest_truth_batches = get_stacked_minibatches(test_truth, self.config.batch_size)\n\t\ttest_mask_batches = get_reg_minibatches(test_truth_mask, self.config.batch_size)\n\t\ttest_input_sequence_batches = get_reg_minibatches(test_input_len, self.config.batch_size)\n\n\t\t# run through once (don't need multiple epochs)\n\n\t\tprog = Progbar(target=1 + int(len(test_input_batches) / self.config.batch_size))\n\n\t\ttotal_test_loss = 0\n\t\tself.save_predictions = True\n\t\tfor i, input_batch in enumerate(test_input_batches):\n\t\t\tloss = self.predict_on_batch(sess, input_batch, test_truth_batches[i], test_mask_batches[i],\\\n\t\t\t\t\t\t\t\t\t\ttest_input_sequence_batches[i], num_of_batch=i, using_dev=False)\n\t\t\ttotal_test_loss += loss\n\t\t\tprog.update(i + 1, [(\"test loss on batch\", loss)])\n\n\t\treturn total_test_loss\n\n\tdef fit(self, sess, saver):\n\t\tlowest_dev_loss = float(\"inf\")\n\n\t\ttrain_input, _, train_input_len = tokenize_data('train.ids.article', self.config.max_sentence_len, False)\n\t\ttrain_truth, train_truth_mask, _ = tokenize_data('train.ids.title', self.config.max_sentence_len, True)\n\n\t\tdev_input, _, dev_input_len = tokenize_data('val.ids.article', self.config.max_sentence_len, False)\n\t\tdev_truth, dev_truth_mask, _ = tokenize_data('val.ids.title', self.config.max_sentence_len, True)\n\n\t\ttrain_input_batches = get_reg_minibatches(train_input, self.config.batch_size)\n\t\ttrain_truth_batches = get_reg_minibatches(train_truth, self.config.batch_size)\n\t\ttrain_mask_batches = get_reg_minibatches(train_truth_mask, self.config.batch_size)\n\t\ttrain_input_sequence = get_reg_minibatches(train_input_len, self.config.batch_size)\n\n\t\tlogger.info(\"number of training input batches, as indicated by fit: %d\", len(train_input_batches))\n\n\t\tdev_input_batches = get_reg_minibatches(dev_input, self.config.batch_size)\n\t\tdev_truth_batches = get_reg_minibatches(dev_truth, self.config.batch_size)\n\t\tdev_mask_batches = get_reg_minibatches(dev_truth_mask, self.config.batch_size)\n\t\tdev_input_sequence = get_reg_minibatches(dev_input_len, self.config.batch_size)\n\n\t\tfor epoch in range(self.config.n_epochs):\n\t\t\tif epoch == self.config.n_epochs - 2:\n\t\t\t\tself.save_predictions = True\n\t\t\telse:\n\t\t\t\tself.save_predictions = False\n\n\t\t\tlogger.info(\"Epoch %d out of %d\", epoch + 1, self.config.n_epochs)\n\t\t\tdev_loss = self.run_epoch(sess, (train_input_batches, train_truth_batches, train_mask_batches, train_input_sequence), \\\n\t\t\t\t\t\t\t\t\t\t(dev_input_batches, dev_truth_batches, dev_mask_batches, dev_input_sequence))\n\t\t\tlogger.info(\"Epoch #%d dev loss: %d\", epoch + 1, dev_loss)\n\t\t\tif dev_loss < lowest_dev_loss:\n\t\t\t\tlowest_dev_loss = dev_loss\n\t\t\t\tif saver:\n\t\t\t\t\tlogger.info(\"New lowest loss! Saving model in %s\", self.config.model_output)\n\t\t\t\t\tsaver.save(sess, self.config.model_output) # saves parameters for best-performing model (lowest total dev loss)\n\t\t\t\n\t\t\tprint(\"\")\n\t\t\t\n\t#\t\tif self.report:\n\t#\t\t\tself.report.log_epoch()\n\t#\t\t\tself.report.save()\n\t\t\t\n\t\treturn lowest_dev_loss\n\n\n\tdef output_predictions(self, preds):\n\t\toutput_file = open('dev_predictions', 'w')\n\t\tfor i in range(tf.shape(preds)[0]):\n\t\t\tindex = tf.argmax(preds[i])\n\n\n\tdef build(self):\n\t\tself.add_placeholders()\n\t\tself.train_pred= self.add_pred_single_batch_train()\n\t\tself.train_loss = self.add_loss_op(self.train_pred)\n\t\tself.train_op = self.add_training_op(self.train_loss)\n\n\t\tself.dev_pred = self.add_pred_single_batch_test(W, b)\n\t\tself.dev_loss = self.add_loss_op(self.dev_pred, W, b)\n\n\t\tself.test_pred = self.add_pred_single_batch_test(W, b)\n\t\tself.test_loss = self.add_loss_op(self.test_pred, W, b)\n\n'''\nreturns a list with lists containing the first words of all sentences, then the second words, then\nthe third words, etc. [[a1, b1, c1], [a2, b2, c2], [a3, b3, c3]] for sentences [a1, a2, a3], [b1, b2, b3] etc\n'''\ndef get_stacked_minibatches(tokenized_data, batch_size):\n\tbatches = []\n\tprev_val = 0\n\tfor step in xrange(batch_size, len(tokenized_data) + batch_size, batch_size):\n\t\tbatch = tokenized_data[prev_val:step]\n\t\tprev_val = step\n\t\tbatches.append( np.stack(batch, axis=1) )\n\treturn batches\n\ndef get_reg_minibatches(tokenized_data, batch_size):\n\tbatches = []\n\tprev_val = 0\n\tfor step in xrange(batch_size, len(tokenized_data) + batch_size, batch_size):\n\t\tbatches.append( tokenized_data[prev_val:step] )\n\t\tprev_val = step\n\treturn batches\n\n#Returns a list of sentences, which in turn are lists of integers that represent words\ndef tokenize_data(path, max_sentence_len, do_mask):\n\ttokenized_data = []\n\tmasks = []\n\tsequence_length = []\n\tf = open('data/summarization/' + path,'r')\n\tfor line in f.readlines():\n\t\tsentence = [int(x) for x in line.split()]\n\t\tif path[-5:] == 'title':\n\t\t\tsentence.insert(0,SOS_ID)\n\t\tif len(sentence) > max_sentence_len:\n\t\t\tsentence = sentence[:max_sentence_len]\n\t\tsequence_length.append(len(sentence))\n\t\tif do_mask:\n\t\t\tmask = [True] * len(sentence)\n\t\t\tmask.extend([False] * (max_sentence_len - len(sentence)))\n\t\t\tmasks.append(mask)\n\t\tsentence.extend([PAD_ID] * (max_sentence_len - len(sentence)))\n\t\ttokenized_data.append(sentence)\n\tprint(\"Tokenized \" + path + \" with %d sentences\" % len(tokenized_data))\n\treturn tokenized_data, masks, sequence_length\n\ndef do_train(args):\n\n\t# allows filehandler to write to the file specified by log_output\n\tconfig = Config()\n\thandler = logging.FileHandler(config.log_output)\n\thandler.setLevel(logging.DEBUG)\n\thandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s'))\n\tlogging.getLogger().addHandler(handler)\n\n\twith tf.Graph().as_default():\n\t\tlogger.info(\"Building model...\",)\n\t\tstart = time.time()\t\t\t\n\t\tmodel = RNN(config)\n\t\tlogger.info(\"took %.2f seconds\", time.time() - start)\n\n\t\tinit = tf.global_variables_initializer() # saves an op to initialize variables\n\n\t\tsaver = tf.train.Saver() # adds ops to save and restore variables to and from checkpoints\n\n\t\twith tf.Session() as session:\n\t\t\tsession.run(init)\n\t\t\trnn.fit(session, saver)\n\t\t\tprint(\"finished\")\n\t\t\t# Save predictions in a text file.\n\t# \t\toutput = model.output(session, dev_raw)\n\t#\t\tsentences, labels, predictions = zip(*output)\n\t#\t\tpredictions = [[LBLS[l] for l in preds] for preds in predictions]\n\t#\t\toutput = zip(sentences, labels, predictions)\n\n\t\t#\twith open(model.config.conll_output, 'w') as f:\n\t\t#\t\twrite_conll(f, output)\n\t\t#\twith open(model.config.eval_output, 'w') as f:\n\t\t#\t\tfor sentence, labels, predictions in output:\n\t\t#\t\t\tprint_sentence(f, sentence, labels, predictions)\n\n# using previously trained parameters, calculates loss and generates labels for unseen data\ndef do_test(args):\n\n\t# allows filehandler to write to the file specified by log_output\n\tconfig = Config()\n\thandler = logging.FileHandler(config.log_output)\n\thandler.setLevel(logging.DEBUG)\n\thandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s'))\n\tlogging.getLogger().addHandler(handler)\n\n\twith tf.Graph().as_default():\n\t\tlogger.info(\"Building model...\",)\n\t\tstart = time.time()\t\t\t\n\t\trnn = RNN(config)\n\t\tlogger.info(\"took %.2f seconds\", time.time() - start)\n\n\t\tinit = tf.global_variables_initializer() # saves an op to initialize variables\n\n\t\tsaver = tf.train.Saver()\n\n\t\twith tf.Session() as session:\n\t\t\tsession.run(init)\n\t\t\tprint(\"Applying saved params: \" + args.saved_params)\n\t\t\tsaver.restore(session, args.saved_params) # restores and initiales old saved params. make sure this works\n\t\t\t# TODO: create way of inputting model_output params that we want to evaluate on\n\n\t\t\t# TODO: need method of taking in input_data\n\t\t\ttotal_loss = rnn.preds_and_loss(session, saver)\n\t\t\tlogger.info(\"Total loss on test set: %d\", total_loss)\n\t\t\t# get outputs on data\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Trains and tests an attentive model for abstractive summarization')\n\tsubparsers = parser.add_subparsers()\n\n\tcommand_parser = subparsers.add_parser('train', help='')\n\tcommand_parser.set_defaults(func=do_train)\n\n\tcommand_parser = subparsers.add_parser('test', help='')\n\tparser.add_argument(\"--saved_params\")\n\t#command_parser.add_argument('-p', '--saved-params', type=argparse.FileType('r'), help=\"Saved params to use when testing\")\n\tcommand_parser.set_defaults(func=do_test)\n\n\tARGS = parser.parse_args()\n\tif ARGS.func is None:\n\t\tparser.print_help()\n\t\tsys.exit(1)\n\telse:\n\t\tARGS.func(ARGS)\n\t\tmodel_path = ARGS.saved_params","repo_name":"abielg/cs224n-final","sub_path":"iter4.py","file_name":"iter4.py","file_ext":"py","file_size_in_byte":25472,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"413890898","text":"import flask_unittest # type: ignore\nfrom flask import request, Flask\nfrom backend.app import app\n\n\nclass TestSession(flask_unittest.ClientTestCase):\n app = app\n\n def test_get_ticket_price(self, client):\n response = client.post(\n \"/ticket_price\",\n json=dict(flight_number=2323, dep_date=\"2021-5-28\", dep_time=\"15:31:14\"),\n )\n self.assertEqual(response.json[\"result\"], \"success\")\n self.assertEqual(response.json[\"data\"], dict(price=45))\n\n def test_purchase_ticket(self, client):\n response = client.post(\n \"/login/cust\", json=dict(email=\"speiaz123@nyu.edu\", password=\"wendy\")\n )\n assert response.json[\"result\"] == \"success\"\n\n response = client.post(\n \"/ticket_purchase\",\n json=dict(\n flight_number=2323,\n dep_date=\"2021-5-28\",\n dep_time=\"15:31:14\",\n email=\"asd@asd.com\",\n card_type=\"debt\",\n card_number=\"1812938912\",\n name_on_card=\"tesasd\",\n exp_date=\"2024-04-23\",\n airline_name=\"China Eastern\",\n ),\n )\n self.assertEqual(response.json[\"result\"], \"success\")\n","repo_name":"PIG208/Airbook","sub_path":"backend/tests/test_purchase.py","file_name":"test_purchase.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"42285710056","text":"# Set up initial directory for putting packets\nimport os\nif not os.path.exists('packets'):\n os.makedirs('packets')\n\n# Import libraries\nfrom fastapi import FastAPI, Request\nimport json\nfrom datetime import datetime, date\n\n# Create FastAPI app\napp = FastAPI()\n\n# Create post at root\n@app.post(\"/\")\nasync def root(info : Request):\n req_info = await info.json()\n date_today = str(date.today())\n time = datetime.now()\n\n date_path = 'packets/' + date_today + '/'\n if not os.path.exists(date_path):\n os.makedirs(date_path)\n\n dev_name = req_info['name']\n\n # Save packet using current time\n folder = date_path + str(dev_name)\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n path = date_path + str(dev_name) + '/' + str(time) + '.json'\n with open(path, 'w+') as f:\n json.dump(req_info, f, indent=4)\n\n # Return SUCCESS\n return {\n \"status\" : \"SUCCESS\",\n \"data\" : req_info\n }\n","repo_name":"goshawk22/helium-http-integration","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"31439116264","text":"from flask import Flask, render_template, request, redirect, url_for, jsonify\nfrom flask import flash\nfrom flask import session as login_session\nfrom flask import make_response\nfrom sqlalchemy import create_engine, asc, desc\nfrom sqlalchemy.orm import sessionmaker, exc\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom models import Base, Category, Recipe, User\nimport random\nimport string\nfrom oauth2client.client import flow_from_clientsecrets, FlowExchangeError\nimport httplib2\nimport json\nimport requests\nfrom functools import wraps\n\napp = Flask(__name__)\n\n\nCLIENT_ID = json.loads(\n open('client_secrets.json', 'r').read())['web']['client_id']\n\n\n# Connect to database and create db session\nengine = create_engine('sqlite:///recipes.db',\n connect_args={'check_same_thread': False})\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n\n# Decorator to redirect user if not logged in and trying to add or modify\n# resource.\ndef login_required(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n if 'username' not in login_session:\n flash('Please login')\n return redirect('/login')\n return f(*args, **kwargs)\n return wrapper\n\n\n# Decorator to check if user owns resource they are trying to modify.\ndef authorized(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n recipe_id = kwargs[\"recipe_id\"]\n recipe = session.query(Recipe).filter_by(id=recipe_id).one()\n if ('user_id' in login_session and\n login_session['user_id'] != recipe.user_id):\n flash(\"You are not authorized to edit that recipe\")\n return render_template('recipe.html',\n category_name=kwargs[\"category_name\"],\n recipe=recipe)\n return f(*args, **kwargs)\n return wrapper\n\n\n# Create anti-forgery state token\n@app.route('/login')\ndef showLogin():\n state = ''.join(random.choice(string.ascii_uppercase + string.digits)\n for x in xrange(32))\n login_session['state'] = state\n return render_template('login.html', STATE=state)\n\n\n@app.route('/gconnect', methods=['POST'])\ndef gconnect():\n # Validate state token\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Obtain authorization code\n code = request.data\n\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n response = make_response(\n json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check that the access token is valid.\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user.\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(\n json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(\n json.dumps(\"Token's client ID does not match app's.\"), 401)\n print(\"Token's client ID does not match app's.\")\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_access_token = login_session.get('access_token')\n stored_gplus_id = login_session.get('gplus_id')\n if stored_access_token is not None and gplus_id == stored_gplus_id:\n response = make_response(json.dumps('Current user is already'\n 'connected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Store the access token in the session for later use.\n login_session['access_token'] = credentials.access_token\n login_session['gplus_id'] = gplus_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n # ADD PROVIDER TO LOGIN SESSION\n login_session['provider'] = 'google'\n\n # see if user exists, if it doesn't make a new one\n user_id = getUserID(data[\"email\"])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n output = ''\n output += '

Welcome, '\n output += login_session['username']\n output += '!

'\n output += ' ')\n flash(\"you are now logged in as %s\" % login_session['username'])\n return output\n\n\n# User Helper Functions\ndef createUser(login_session):\n newUser = User(name=login_session['username'], email=login_session[\n 'email'], picture=login_session['picture'])\n session.add(newUser)\n session.commit()\n user = session.query(User).filter_by(email=login_session['email']).one()\n return user.id\n\n\ndef getUserInfo(user_id):\n user = session.query(User).filter_by(id=user_id).one()\n return user\n\n\ndef getUserID(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except NoResultFound:\n return None\n\n\n# DISCONNECT - Revoke a current user's token and reset their login_session.\n@app.route('/gdisconnect')\ndef gdisconnect():\n # Only disconnect a connected user.\n access_token = login_session.get('access_token')\n if access_token is None:\n response = make_response(\n json.dumps('Current user not connected.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n if result['status'] == '200':\n response = make_response(json.dumps('Successfully disconnected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n else:\n response = make_response(json.dumps('Failed to revoke token for given '\n 'user.', 400))\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\n@app.route('/fbconnect', methods=['POST'])\ndef fbconnect():\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n access_token = request.data\n print(\"access token received %s \") % access_token\n\n app_id = json.loads(open('fb_client_secrets.json', 'r').read())[\n 'web']['app_id']\n app_secret = json.loads(\n open('fb_client_secrets.json', 'r').read())['web']['app_secret']\n url = ('https://graph.facebook.com/oauth/access_token?grant_type='\n 'fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token'\n '=%s') % (app_id, app_secret, access_token)\n h = httplib2.Http()\n result = h.request(url, 'GET')[1]\n\n # Use token to get user info from API\n userinfo_url = \"https://graph.facebook.com/v2.8/me\"\n '''\n Due to the formatting for the result from the server token exchange we\n have to split the token first on commas and select the first index\n which gives us the key : valuefor the server access token then we split\n it on colons to pull out the actual token value and replace the\n remaining quotes with nothing so that it can be used directly in the\n graph api calls\n '''\n token = result.split(',')[0].split(':')[1].replace('\"', '')\n\n url = ('https://graph.facebook.com/v2.8/me?access_token=%s&fields=name,id,'\n 'email') % token\n h = httplib2.Http()\n result = h.request(url, 'GET')[1]\n # print \"url sent for API access:%s\"% url\n # print \"API JSON result: %s\" % result\n data = json.loads(result)\n login_session['provider'] = 'facebook'\n login_session['username'] = data[\"name\"]\n login_session['email'] = data[\"email\"]\n login_session['facebook_id'] = data[\"id\"]\n\n # The token must be stored in the login_session in order to properly logout\n login_session['access_token'] = token\n\n # Get user picture\n url = ('https://graph.facebook.com/v2.8/me/picture?access_token=%s&'\n 'redirect=0&height=200&width=200') % token\n h = httplib2.Http()\n result = h.request(url, 'GET')[1]\n data = json.loads(result)\n\n login_session['picture'] = data[\"data\"][\"url\"]\n\n # see if user exists\n user_id = getUserID(login_session['email'])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n output = ''\n output += '

Welcome, '\n output += login_session['username']\n\n output += '!

'\n output += ' ')\n\n flash(\"Now logged in as %s\" % login_session['username'])\n return output\n\n\n@app.route('/fbdisconnect')\ndef fbdisconnect():\n facebook_id = login_session['facebook_id']\n # The access token must me included to successfully logout\n access_token = login_session['access_token']\n url = 'https://graph.facebook.com/%s/permissions?access_token=%s' % (\n facebook_id, access_token)\n h = httplib2.Http()\n result = h.request(url, 'DELETE')[1]\n return \"you have been logged out\"\n\n\n# Disconnect based on provider\n@app.route('/disconnect')\ndef disconnect():\n if 'provider' in login_session:\n if login_session['provider'] == 'google':\n gdisconnect()\n del login_session['gplus_id']\n del login_session['access_token']\n if login_session['provider'] == 'facebook':\n fbdisconnect()\n del login_session['facebook_id']\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n del login_session['user_id']\n del login_session['provider']\n flash(\"You have successfully been logged out.\")\n return redirect(url_for('showCatalog'))\n else:\n flash(\"You were not logged in\")\n return redirect(url_for('showCatalog'))\n\n\n# Return JSON data for all recipes in a category\n@app.route('/catalog//recipes/json')\ndef showCategoryJSON(category_name):\n category = session.query(Category).filter_by(name=category_name).one()\n recipes = session.query(Recipe).filter_by(category_id=category.id).all()\n category = {\"Category\": category_name,\n \"Recipes\": [r.serialize for r in recipes]}\n return jsonify(Catalog=category)\n\n\n# Return JSON data for a specific recipe\n@app.route('/catalog//recipe//json')\ndef showRecipeJSON(category_name, recipe_id):\n recipe = session.query(Recipe).filter_by(id=recipe_id).one()\n return jsonify(Recipe=recipe.serialize)\n\n\n# Home page of catalog showing latest recipes added in descending order\n@app.route('/')\n@app.route('/catalog')\ndef showCatalog():\n categories = session.query(Category).order_by(asc(Category.name)).all()\n latest_recipes = session.query(Recipe).order_by(\n desc(Recipe.id)).limit(10).all()\n print(login_session)\n return render_template(\n 'home.html', categories=categories, latest_recipes=latest_recipes)\n\n\n# Show all recipes in a particular category with sidebar\n@app.route('/catalog//recipes')\ndef showCategory(category_name):\n categories = session.query(Category).order_by(asc(Category.name)).all()\n category = session.query(Category).filter_by(name=category_name).one()\n recipes = session.query(Recipe).filter_by(category_id=category.id).all()\n return render_template(\n 'recipe-category.html', categories=categories, recipes=recipes,\n category=category)\n\n\n# Show all recipes in all categories with sidebar\n@app.route('/catalog/recipes')\ndef showRecipes():\n categories = session.query(Category).order_by(asc(Category.name)).all()\n recipes = session.query(Recipe).all()\n return render_template(\n 'allrecipes.html', categories=categories, recipes=recipes)\n\n\n# Show recipe detail\n@app.route('/catalog//recipe/')\ndef showRecipe(category_name, recipe_id):\n recipe = session.query(Recipe).filter_by(id=recipe_id).one()\n return render_template(\n 'recipe.html', category_name=category_name, recipe=recipe)\n\n\n# Create a new recipe\n@app.route('/catalog//recipe/new',\n methods=['GET', 'POST'])\n@login_required\ndef newRecipe(category_name):\n categories = session.query(Category).order_by(asc(Category.name)).all()\n if request.method == 'POST':\n category = session.query(Category).filter_by(\n name=request.form['category']).one()\n newrecipe = Recipe(name=request.form['name'],\n category_id=category.id,\n instructions=request.form['instructions'],\n ingredients=request.form['ingredients'],\n user_id=login_session['user_id'])\n session.add(newrecipe)\n session.commit()\n flash(\"New recipe created!\")\n return redirect(url_for('showCategory', category_name=category.name))\n else:\n return render_template(\n 'newrecipe.html', category_name=category_name,\n categories=categories)\n\n\n# Edit a recipe\n@app.route('/catalog//recipe//edit',\n methods=['GET', 'POST'])\n@authorized\n@login_required\ndef editRecipe(category_name, recipe_id):\n categories = session.query(Category).order_by(asc(Category.name)).all()\n editedRecipe = session.query(Recipe).filter_by(id=recipe_id).one()\n if request.method == 'POST':\n category = session.query(Category).filter_by(\n name=request.form['category']).one()\n if request.form['name']:\n editedRecipe.name = request.form['name']\n if request.form['category']:\n editedRecipe.category_id = category.id\n if request.form['instructions']:\n editedRecipe.instructions = request.form['instructions']\n if request.form['ingredients']:\n editedRecipe.ingredients = request.form['ingredients']\n session.add(editedRecipe)\n session.commit()\n flash(\"Recipe updated!\")\n return redirect(url_for('showCategory', category_name=category.name))\n else:\n return render_template(\n 'editrecipe.html', category_name=category_name,\n categories=categories, recipe=editedRecipe)\n\n\n# Delete a recipe\n@app.route('/catalog//recipe//delete',\n methods=['GET', 'POST'])\n@authorized\n@login_required\ndef deleteRecipe(category_name, recipe_id):\n deletedRecipe = session.query(Recipe).filter_by(id=recipe_id).one()\n if request.method == 'POST':\n session.delete(deletedRecipe)\n session.commit()\n flash(\"Recipe has been deleted!\")\n return redirect(url_for('showCategory', category_name=category_name))\n else:\n return render_template('deleterecipe.html', recipe=deletedRecipe)\n\n\n# Show the about page\n@app.route('/about')\ndef showAbout():\n return render_template('about.html')\n\n\nif __name__ == \"__main__\":\n app.secret_key = \"super_secret_key\"\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"marloncard/recipe-item-catalog","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"6987605378","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport random\n\nimport pytz\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils import Choices\nfrom model_utils.models import TimeStampedModel\nfrom south.modelsinspector import add_introspection_rules\nfrom timezones2.models import TimeZoneField\n\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedEmailField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.encryption.models import EncryptionKey\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.utils import deprecated\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.units import CURRENCY_CHOICES\nfrom gridplatform.utils.units import ENERGY_CHOICES\nfrom gridplatform.utils.units import POWER_CHOICES\nfrom gridplatform.utils.units import TEMPERATURE_CHOICES\nfrom gridplatform.utils.units import VOLUME_CHOICES\nfrom gridplatform.utils.units import VOLUME_FLOW_CHOICES\nfrom gridplatform.utils.units import WATT_HOUR_ENERGY_CHOICES\nfrom gridplatform.utils.units import WATT_POWER_CHOICES\n\nfrom .managers import CustomerManager\n\n\nadd_introspection_rules([], [\"^timezones2\\.models\\.TimeZoneField\"])\n\n\ndef get_default_provider():\n # NOTE: Currently getting id rather than object, to avoid attempting to\n # decrypt, to avoid crashing in existing fixture_hack code.\n from gridplatform.providers.models import Provider\n return Provider.objects.order_by(\n 'id').values_list('id', flat=True).first()\n\n\nclass Customer(EncryptedModel, TimeStampedModel):\n \"\"\"\n Represents a GridManager customer. Customer is the target of foreign keys\n from various other models.\n\n :ivar id: The ``id`` for customers is randomly generated on creation/first\n save. The ``id`` is randomized to hide the number of customers from\n our users.\n :ivar provider: A foreign key to the\n :class:`~gridplatform.providers.models.Provider` that facilitates the\n energy management system to this customer.\n :ivar name:\n :ivar vat: The VAT number of this customer.\n :ivar address:\n :ivar postal_code: The zip code of this customer.\n :ivar city:\n :ivar phone:\n :ivar country_code:\n :ivar timezone: The timezone in which the customer operates.\n\n Details of contact person:\n\n :ivar contact_name:\n :ivar contact_email:\n :ivar contact_phone:\n\n Various preferred units applied in GridPortal 2.0. These are not used\n elsewhere in the gridplatform.\n\n :ivar electricity_instantaneous: Preferred unit for electric power.\n :ivar electricity_consumption: Preferred unit for electric energy.\n :ivar gas_instantaneous: Preferred unit for volume flow of gas.\n :ivar gas_consumption: Preferred unit for gas volume.\n :ivar water_instantaneous: Preferred unit for volume flow of water.\n :ivar water_consumption: Preferred unit for water volume.\n :ivar heat_instantaneous: Preferred unit for thermal power of district heating.\n :ivar heat_consumption: Preferred unit for thermal energy of district heating.\n :ivar temperature: Preferred unit for temperatures. Note that these need\n not be bucking ham units.\n :ivar oil_instantaneous: Preferred unit for volume flow of oil.\n :ivar oil_consumption: Preferred unit for oil volume.\n :ivar currency_unit: Customers unit of currency.\n :ivar electricity_tariff: Default tariff for new electricity measurement points.\n :ivar gas_tariff: Default tariff for new gas measurement points.\n :ivar water_tariff: Default tariff for new water measurement points.\n :ivar heat_tariff: Default tariff for new district heating measurement points.\n :ivar oil_tariff: Default tariff for new oil measurement points.\n\n Filtering specific columns:\n\n :ivar is_active: A Boolean indicating if customer is active. Inactive\n customers will be filtered out by\n :class:`~gridplatform.customers.managers.CustomerManager`.\n\n The units ``\"production_a\"`` ... ``\"production_e\"`` identify per\n customer unit dimensions whose human readable representation is defined by\n the following fields:\n\n :ivar production_a_unit:\n :ivar production_b_unit:\n :ivar production_c_unit:\n :ivar production_d_unit:\n :ivar production_e_unit:\n\n Energy manager specific fields:\n\n Additional meta data fields:\n\n :ivar created_by: The :class:`~gridplatform.users.models.User` that created\n this customer.\n \"\"\"\n id = models.IntegerField(primary_key=True, editable=False)\n provider = models.ForeignKey(\n 'providers.Provider', editable=False, default=get_default_provider)\n name = EncryptedCharField(\n _('name'), max_length=50, blank=False)\n vat = EncryptedCharField(\n _('VAT no.'), max_length=20, blank=True)\n address = EncryptedCharField(\n _('address'), max_length=50, blank=True)\n postal_code = EncryptedCharField(\n _('postal code'), max_length=10, blank=True)\n city = EncryptedCharField(\n _('city'), max_length=30, blank=True)\n phone = EncryptedCharField(\n _('phone'), max_length=50, blank=True)\n country_code = EncryptedCharField(\n _('country code'), max_length=3, blank=True)\n timezone = TimeZoneField()\n # Contact person details\n contact_name = EncryptedCharField(\n _('contact person'), max_length=50, blank=True)\n contact_email = EncryptedEmailField(\n _('e-mail'), max_length=50, blank=True)\n contact_phone = EncryptedCharField(\n _('phone'), max_length=50, blank=True)\n # Preferred units\n electricity_instantaneous = models.CharField(\n _('Electricity instantaneous unit'), choices=WATT_POWER_CHOICES,\n default=\"kilowatt\", max_length=50)\n electricity_consumption = models.CharField(\n _('Electricity consumption unit'), choices=WATT_HOUR_ENERGY_CHOICES,\n default=\"kilowatt*hour\", max_length=50)\n gas_instantaneous = models.CharField(\n _('Gas instantaneous unit'), choices=VOLUME_FLOW_CHOICES,\n default=\"meter*meter*meter*hour^-1\", max_length=50)\n gas_consumption = models.CharField(\n _('Gas consumption unit'), choices=VOLUME_CHOICES,\n default=\"meter*meter*meter\", max_length=50)\n water_instantaneous = models.CharField(\n _('Water instantaneous unit'), choices=VOLUME_FLOW_CHOICES,\n default=\"meter*meter*meter*hour^-1\", max_length=50)\n water_consumption = models.CharField(\n _('Water consumption unit'), choices=VOLUME_CHOICES,\n default=\"meter*meter*meter\", max_length=50)\n heat_instantaneous = models.CharField(\n _('Heat instantaneous unit'), choices=POWER_CHOICES,\n default=\"kilowatt\", max_length=50)\n heat_consumption = models.CharField(\n _('Heat consumption unit'), choices=ENERGY_CHOICES,\n default=\"kilowatt*hour\", max_length=50)\n temperature = models.CharField(\n _('Temperature unit'), choices=TEMPERATURE_CHOICES,\n default=\"celsius\", max_length=50)\n oil_instantaneous = models.CharField(\n _('Oil instantaneous unit'), choices=VOLUME_FLOW_CHOICES,\n default=\"meter*meter*meter*hour^-1\", max_length=50)\n oil_consumption = models.CharField(\n _('Oil consumption unit'), choices=VOLUME_CHOICES,\n default=\"meter*meter*meter\", max_length=50)\n currency_unit = BuckinghamField(_('currency'), choices=CURRENCY_CHOICES,\n default='currency_dkk')\n\n electricity_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"electricity_tariff_set\",\n blank=True, null=True)\n gas_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"gas_tariff_set\",\n blank=True, null=True)\n water_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"water_tariff_set\",\n blank=True, null=True)\n heat_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"heat_tariff_set\",\n blank=True, null=True)\n oil_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"oil_tariff_set\",\n blank=True, null=True)\n\n is_active = models.BooleanField(_('is active'), default=True)\n\n production_a_unit = EncryptedCharField(\n _('production A unit'), max_length=50, blank=True)\n\n production_b_unit = EncryptedCharField(\n _('production B unit'), max_length=50, blank=True)\n\n production_c_unit = EncryptedCharField(\n _('production C unit'), max_length=50, blank=True)\n\n production_d_unit = EncryptedCharField(\n _('production D unit'), max_length=50, blank=True)\n\n production_e_unit = EncryptedCharField(\n _('production E unit'), max_length=50, blank=True)\n\n created_by = models.ForeignKey(\n 'users.User',\n related_name='+',\n null=True,\n editable=False)\n\n objects = CustomerManager()\n\n class Meta:\n verbose_name = _('customer')\n verbose_name_plural = _('customers')\n ordering = ['id']\n\n def clean_fields(self, exclude=None):\n \"\"\"\n :raise ValidationError: if an applied production unit is cleared.\n \"\"\"\n super(Customer, self).clean_fields(exclude)\n\n def clean_production_unit(letter):\n do_check_production_unit = (\n exclude is None or exclude is not None and\n 'production_%s_unit' % letter not in exclude)\n production_unit_is_set = getattr(\n self, 'production_%s_unit_plain' % letter)\n data_series_using_production_unit = self.dataseries_set.filter(\n unit='production_%s' % letter)\n\n if do_check_production_unit and \\\n not production_unit_is_set and \\\n data_series_using_production_unit.exists():\n raise ValidationError(\n _(\n 'Production unit {production_unit_letter} is in use '\n 'and cannot be empty').format(\n production_unit_letter=letter.upper()))\n for letter in ['a', 'b', 'c', 'd', 'e']:\n clean_production_unit(letter)\n\n def __unicode__(self):\n return unicode(self.name_plain or self.name)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Initializes ``id`` to something random on initial save.\n \"\"\"\n if not self.id:\n self.created_by = get_user()\n\n # NOTE: Will fail if another customer is assigned the same random\n # ID between the exists-check and the save --- for now, we assume\n # that the occasion of several customers being added in the same\n # millisecond and the random-generator returning the same number\n # for each is sufficiently unlikely that we won't add code to\n # handle it. (... apart from the force_insert, so at least we\n # would get an error rather than overwriting existing data...)\n #\n # ID is random from 1 to 10^8 - 1 inclusive --- printable as 8\n # decimal digits, no customer gets ID 0, representable in signed\n # and unsigned 32-bit.\n\n id = random.randint(1, (10 ** 8) - 1)\n while Customer.objects.filter(id=id).exists():\n id = random.randint(1, (10 ** 8) - 1)\n\n # HACK: Create other customer object to get encryption set up\n # before we actually store encrypted fields\n if self.provider_id:\n tmp_customer = Customer(provider_id=self.provider_id)\n else:\n tmp_customer = Customer()\n tmp_customer.id = id\n tmp_customer.save(force_insert=True, force_update=False)\n self.id = tmp_customer.id\n # NOTE: Create encryption key to enable logic\n # for sharing key with users on provider associated with\n # customer...\n EncryptionKey.generate((Customer, self.id))\n\n opts = kwargs.copy()\n opts.update({'force_insert': False, 'force_update': True})\n super(Customer, self).save(*args, **opts)\n else:\n opts = {'force_update': True}\n opts.update(kwargs)\n super(Customer, self).save(*args, **opts)\n\n @deprecated\n def get_preffered_tariff(self, utility_type):\n if utility_type == utilitytypes.METER_CHOICES.electricity:\n return self.electricity_tariff\n elif utility_type == utilitytypes.METER_CHOICES.gas:\n return self.gas_tariff\n elif utility_type == utilitytypes.METER_CHOICES.water:\n return self.water_tariff\n elif utility_type == utilitytypes.METER_CHOICES.district_heating:\n return self.heat_tariff\n elif utility_type == utilitytypes.METER_CHOICES.oil:\n return self.oil_tariff\n raise ValueError('unsupported utility type: %r' % utility_type)\n\n @deprecated\n def count_measurementpoints(self):\n # WTF? (Number of collections with graphs?)\n return self.collection_set.filter(\n graph__isnull=False).distinct().count()\n\n @deprecated\n def count_collections(self):\n # WTF? (Number of collections without graphs?)\n return self.collection_set.filter(\n graph__isnull=True).distinct().count()\n\n @deprecated\n def count_agents(self):\n return {\n 'total': self.agent_set.count(),\n 'online': self.agent_set.filter(online=True).count(),\n 'offline': self.agent_set.filter(online=False).count(),\n }\n\n @deprecated\n def count_meters(self):\n return {\n 'total': self.meter_set.count(),\n 'online': self.meter_set.filter(online=True).count(),\n 'offline': self.meter_set.filter(online=False).count(),\n }\n\n def now(self):\n \"\"\"\n A :class:`~datetime.datetime` object representing the current time in this\n :class:`.Customer`'s timezone.\n \"\"\"\n tz = self.timezone\n if isinstance(tz, basestring):\n tz = pytz.timezone(tz)\n return tz.normalize(datetime.datetime.now(tz))\n\n def get_encryption_id(self):\n \"\"\"\n Implementation of abstract method declared by\n :class:`gridplatform.encryption.models.EncryptedModel`.\n \"\"\"\n return (Customer, self.id)\n\n def satisfies_search(self, search):\n \"\"\"\n Implementation of interface required by\n :py:func:`gridplatform.utils.views.json_list_response` view function\n decorator.\n\n :param search: A string to search for.\n\n :return: True if the ``search`` argument is found in any relevant\n property of this customer.\n \"\"\"\n elems = [\n self.name_plain,\n self.address_plain,\n self.postal_code_plain,\n self.country_code_plain,\n ]\n search = search.lower()\n return any([search in unicode(elem).lower() for elem in elems])\n\n def get_production_unit_choices(self):\n \"\"\"\n Production unit choices for forms.\n\n :return: A Choices object of non-empty production units. The database\n representation will be the relevant buckingham unit, and the human\n readable representation will be the decrypted contents of the\n corresponding production unit field.\n \"\"\"\n result_tuples = []\n\n for letter in ['a', 'b', 'c', 'd', 'e']:\n plain_text = getattr(self, 'production_%s_unit_plain' % letter)\n unit = 'production_%s' % letter\n if plain_text:\n result_tuples.append((unit, plain_text))\n\n return Choices(*result_tuples)\n","repo_name":"taylor19941009/gridplatform.2.1.5","sub_path":"gridagentserver/gridplatform/customers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"13429544833","text":"import sys\n\ndata = []\n\n# use different import based on python version number:\nif (sys.version_info > (3, 0)):\n # python 3:\n import urllib.request\n with urllib.request.urlopen('https://raw.githubusercontent.com/hchiam/cognateLanguage/master/output_shortlist.txt') as response:\n line = response.readline().decode('utf-8').replace('\\n','')\n while line != '':\n data.append(line)\n line = response.readline().decode('utf-8').replace('\\n','')\nelse:\n # python 2:\n import urllib2\n response = urllib2.urlopen('https://raw.githubusercontent.com/hchiam/cognateLanguage/master/output_shortlist.txt')\n data = response.read().split('\\n')\n\nimport string # example use here: to be able to remove punctuation\nimport re # example use here: to be able to remove repeating spaces\n\nkeepGoing = True\n\nwhile keepGoing:\n\n def justTwoInitSylls(word):\n beforeThisIndex = 0\n for vowel1 in word:\n if vowel1 in 'aeiou':\n afterThisIndex = word.index(vowel1)\n break\n for vowel2 in word[afterThisIndex+1:]:\n if vowel2 in 'aeiou':\n beforeThisIndex = word[afterThisIndex+1:].index(vowel2)+1 + afterThisIndex+1\n break\n if beforeThisIndex!=0:\n word = word[:beforeThisIndex+1]\n return word\n\n def countVowels(word):\n vowels = 'aeiou'\n word = word.lower()\n count = 0\n for char in word:\n if char in vowels:\n count += 1\n return count\n\n # filename = 'output_shortlist.txt'\n # data = ''\n # input = ''\n translation = '< Translation Not Found. >'\n shortTranslation = '< Translation Not Found. >'\n\n if (sys.version_info > (3, 0)):\n inputData = input('Enter English word or sentence gloss to translate [and then hit Enter key]:\\n\\t')\n else:\n inputData = raw_input('Enter English word or sentence gloss to translate [and then hit Enter key]:\\n\\t')\n\n # remove punctuation from inputData, except for '?'\n exclude = set(string.punctuation)\n inputData = ''.join(ch for ch in inputData if (ch not in exclude or ch == '?'))\n\n # add space before '?' to enable replacing with question particle word\n inputData = inputData.replace('?',' ?')\n\n # make inputData all lowercase\n inputData = inputData.lower()\n\n # remove repeating spaces from what remains\n inputData = re.sub(' +', ' ', inputData)\n\n # print inputData # debug output\n\n if inputData != \"\":\n # split inputData into words\n inputData = inputData.split(' ')\n\n translation = ''\n shortTranslation = ''\n trackLastLetterOfLastWord = ''\n\n for word in inputData:\n\n translationFound = False\n\n # account for plural nouns or 2nd person singular verbs\n if word not in data and word[-1] == 's' and word[:-1] in data:\n word = word[:-1]\n\n # search for word translation in list\n for line in data:\n if line != '\\n' and ',' in line:\n if word == line.split(',')[1] or (word[-1] == 's' and word[:-1] == line.split(',')[1]) and word != 'is': # (also account for plural nouns or 2nd person singular verbs)\n translatedWord = line.split(',')[0]\n shortTranslatedWord = justTwoInitSylls(translatedWord)\n # trackLastLetterOfLastWord = shortTranslatedWord[-1] # THIS GOES WITH ADDING FINAL LETTER AT END OF SENTENCE\n numVowelsInTranslatedWord = countVowels(translatedWord)\n shortTranslation += ' ' + shortTranslatedWord\n # if numVowelsInTranslatedWord == 1:\n # shortTranslation += translatedWord\n # trackLastLetterOfLastWord = ''\n # elif trackLastLetterOfLastWord in 'aeiou':\n # shortTranslation += shortTranslatedWord\n # else:\n # # shortTranslation += shortTranslatedWord[:-1] # THIS GOES WITH ADDING FINAL LETTER AT END OF SENTENCE\n # shortTranslation += shortTranslatedWord\n translation += translatedWord + ' '\n translationFound = True\n\n # add in '?' for words not found\n if translationFound == False:\n translation += '[?]' + ' '\n\n # remove final space ' '\n translation = translation[:-1]\n # # add final letter\n # shortTranslation += trackLastLetterOfLastWord # THIS GOES WITH REMOVING FINAL LETTER FROM EACH WORD\n\n print ('Long Translation:\\n\\t' + '\"' + translation.capitalize()+'.' + '\"')\n print ('Short Translation:\\n\\t' + shortTranslation)\n\n if (sys.version_info > (3, 0)):\n userResponse = input('Another sentence? (y/n) [and then hit Enter key]:\\n\\t').lower()\n else:\n userResponse = raw_input('Another sentence? (y/n) [and then hit Enter key]:\\n\\t').lower()\n keepGoing = ('y' == userResponse) or ('yes' == userResponse)\n","repo_name":"hchiam/cognateLanguage","sub_path":"repeatTranslation_oneFile.py","file_name":"repeatTranslation_oneFile.py","file_ext":"py","file_size_in_byte":5111,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"83"} +{"seq_id":"23475804445","text":"from gui.gui_info import GUIInfo\nfrom gui.gui_manager import GUIManager\nfrom logic.game_board import GameBoard\n\nfrom rl.agent.epsilon import EpsilonInfo\nfrom rl.agent.agent import Agent\nfrom rl.state.utils.utils import state_to_numpy\n\nfrom constants import *\n\nimport random\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nrows = 7\ncols = 7\n\nguiInfo = GUIInfo(rows = rows,\n\t cols = cols,\n\t side = 35,\n\t space = 3,\n\t offset = (3, 3),\n\t name = ':: Manga Snake ::')\n\n\ndef runStep(game_board, action):\n\tif actions_map[action] == 'LEFT':\n\t\tgame_board.goLeft()\n\telif actions_map[action] == 'RIGHT':\n\t\tgame_board.goRight()\n\telse: # action == 'S', straight\n\t\tpass\n\n\tgame_state = game_board.update()\n\tnext_state = game_board.getState()\n\n\treturn (game_state, next_state)\n\n\nname = '255_train.h5'\n\nactions_map = {0:'LEFT',\n 1:'STRAIGHT',\n 2:'RIGHT'}\n\nguiManager = GUIManager(guiInfo)\ngame_board = GameBoard(rows, cols)\n\nepisodes = 1000\nsteps = 200\neps_info = EpsilonInfo(0.00, 0.00, 0.00)\n\nagent = Agent(rows + 2,\n\t cols + 2,\n\t actions_map, 0.0, 0.0, 0, eps_info)\n\nagent.load('save/' + name)\n\n# Main Loop\ndone = False\n\nfor w in range(episodes):\n\tif done:\n\t\tbreak\n\n\tgame_board.reset()\n\n\tfoodEaten = 0\n\twallHitten = 0\n\tbodyHitten = 0\n\n\tfor v in range(steps):\n\t\tif done:\n\t\t\tbreak\n\n\t\tcurr_state = state_to_numpy(game_board.getState())\n\t\taction = agent.act(curr_state)\n\n\t\tresult, next_state = runStep(game_board, action)\n\n\t\tguiManager.update(next_state)\n\t\tguiManager.show()\n\t\tkey = guiManager.waitKey(100)\n\n\t\tif key == K_ESC:\n\t\t\tdone = True\n\n\t\tif result.hitWall or result.hitSelf:\n\t\t\tif result.hitWall:\n\t\t\t\twallHitten += 1\n\t\t\tif result.hitSelf:\n\t\t\t\tbodyHitten += 1\n\t\t\tgame_board.reset()\n\t\t\tcontinue\n\n\t\tif result.gotFood:\n\t\t\tfoodEaten += 1\n\n\tprint('episode', w + 1)\n\tprint('food:', foodEaten)\n\tprint('wall:', wallHitten)\n\tprint('body:', bodyHitten)\n\tprint()\n\nguiManager.finish()\n","repo_name":"ScharanCysne/SnakeRL","sub_path":"play_rl.py","file_name":"play_rl.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"39704590500","text":"# -*- coding: utf-8 -*-\n\nfrom .. import rabbitmq\n\nfrom odoo import api, fields, models\nfrom odoo.exceptions import UserError\nfrom odoo import _\n\n\nclass CrmLead(models.Model):\n _inherit = 'crm.lead'\n _order = 'is_high_priority DESC, create_date DESC'\n\n internal_reference = fields.Char('Application Number', readonly=True)\n state = fields.Selection([\n ('pending', 'Pending'),\n ('approved', 'Approved'),\n ('rejected', 'Rejected'),\n ], default='pending', readonly=True)\n reject_reason_id = fields.Many2one('crm.lead.reject.reason',\n 'Reject Reason', readonly=True)\n\n # Partner related fields\n partner_logo = fields.Binary(\"Logo\",\n related='partner_id.image_small')\n vat = fields.Char(related='partner_id.vat')\n vat_state = fields.Selection([\n ('draft', 'Draft'),\n ('confirmed', 'Confirmed'),\n ('rejected', 'Rejected'),\n ], default='draft', readonly=True)\n\n invoice_id = fields.Many2one('res.partner', 'Invoice',\n compute='_compute_invoice_id', store=True)\n invoice_address = fields.Char('Invoice Address',\n related='invoice_id.street')\n\n contact_id = fields.Many2one('res.partner', 'Contact',\n compute='_compute_contact_id', store=True)\n contact_identity_number = fields.Char('Identity Number',\n related='contact_id.identity_number')\n contact_email = fields.Char('Email', related='contact_id.email')\n contact_mobile = fields.Char('Gsm', related='contact_id.mobile')\n contact_date_of_birth = fields.Date('Date of Birth',\n related='contact_id.date_of_birth')\n\n # Segment and priority\n segment = fields.Selection([\n ('large', 'Large'),\n ('medium', 'Medium'),\n ('small', 'Small'),\n ], 'Segment')\n is_high_priority = fields.Boolean('Is high priority?', default=False)\n\n # Documents\n document_ids = fields.One2many('crm.lead.document', 'lead_id', 'Documents')\n document_state = fields.Selection([\n ('draft', 'Draft'),\n ('confirmed', 'Confirmed'),\n ], 'Document State', compute='_compute_document_state', stored=True)\n\n @api.depends('document_ids.state')\n def _compute_document_state(self):\n for lead in self:\n state = set(self.document_ids.mapped('state'))\n lead.document_state = 'confirmed' if state == {'confirmed'} else 'draft'\n\n @api.depends('partner_id.child_ids')\n def _compute_contact_id(self):\n for lead in self:\n contacts = lead.partner_id.child_ids.filtered(lambda r: r.type == 'contact')\n lead.contact_id = contacts[0] if contacts else None\n\n @api.depends('partner_id.child_ids')\n def _compute_invoice_id(self):\n for lead in self:\n invoices = lead.partner_id.child_ids.filtered(lambda r: r.type == 'invoice')\n lead.invoice_id = invoices[0] if invoices else None\n\n @api.multi\n def _publish_vat_approval(self, state):\n rabbitmq.client.publish({\n 'message': 'VAT state changed to %s' % state,\n 'vat_ids': self.ids,\n 'vats': self.mapped('vat'),\n 'state': state,\n })\n\n # Actions\n\n @api.multi\n def approve(self):\n\n if self.filtered(lambda r: r.document_state != 'confirmed'):\n raise UserError(\n _('You should confirm all documents before approving the lead!'))\n\n self.sudo().write({'state': 'approved'})\n rabbitmq.client.publish({\n 'message': 'Leads Approved',\n 'lead_ids': self.ids,\n })\n\n @api.multi\n def reject(self):\n self.sudo().write({'state': 'rejected'})\n rabbitmq.client.publish({\n 'message': 'Leads Rejected',\n 'lead_ids': self.ids,\n })\n\n @api.multi\n def confirm_vat(self):\n \"\"\"Confirms VAT \"\"\"\n self.sudo().write({'vat_state': 'confirmed'})\n self._publish_vat_approval('confirmed')\n\n @api.multi\n def reject_vat(self):\n \"\"\"Rejects VAT \"\"\"\n self.sudo().write({'vat_state': 'rejected'})\n self._publish_vat_approval('rejected')\n\n @api.model\n @api.returns('self')\n def register(self, values):\n \"\"\"Creates Lead from given values\"\"\"\n\n # create partner\n partner = self.env['res.partner'].create({\n 'name': values.get('company_name'),\n 'image': values.get('logo'),\n 'vat': values.get('vat'),\n 'child_ids': [\n (0, 0, {\n 'type': 'invoice',\n 'name': '%s Invoice Address' % values.get('company_name'),\n 'street': values.get('invoice_address')}),\n (0, 0, {\n 'type': 'contact',\n 'name': '%s %s' % (values.get('contact_name'),\n values.get('contact_surname')),\n 'identity_number': values.get('contact_tckn'),\n 'date_of_birth': values.get('contact_dob'),\n 'mobile': values.get('contact_gsm'),\n 'email': values.get('contact_email'),\n })\n ],\n })\n\n document_ids = []\n for doc in values.get('documents'):\n document_ids.append((0, 0, {'name': doc.get('name'),\n 'file': doc.get('file')}))\n # create lead\n return self.env['crm.lead'].create({\n 'type': 'opportunity',\n 'name': '%s %s' % (values.get('company_name'),\n values.get('reference')),\n 'internal_reference': values.get('reference'),\n 'partner_id': partner.id,\n 'segment': values.get('segment'),\n 'is_high_priority': values.get('is_high_priority'),\n 'email_from': values.get('contact_email'),\n 'contact_name': '%s %s' % (values.get('contact_name'),\n values.get('contact_surname')),\n 'mobile': values.get('contact_gsm'),\n 'document_ids': document_ids,\n 'user_id': None\n })\n","repo_name":"mocak/iys-modules","sub_path":"crm_apply/models/crm_lead.py","file_name":"crm_lead.py","file_ext":"py","file_size_in_byte":6288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"6362331020","text":"#!usr/bin/env python3\n#-*- coding: utf-8 -*-\n\nimport re\nimport time\nimport random\nimport requests\nfrom config import *\n\nclass Download:\n\n def __init__(self):\n ip_html = requests.get('http://api.xicidaili.com/free2016.txt')\n self.iplist = re.findall(r'(.*?)\\r\\n', ip_html.text, re.S) ##re.S匹配包括换行符\n \n self.user_agent_list = UA_list\n\n\n def get(self, url, timeout=None, proxy=None, num_retry=7): \n ## get策略为:先本地ip+模仿浏览器头,不然就代理ip+模仿浏览器头,辅助为重试(应对对方服务器及网络问题)。\n ## timeout: eg:(6, 12),但实际操作后,只要timeout不是None,就会报错。\n ## proxy: 但requests.get的固定参数为'proxies', eg: 'headers',不要弄错。\n \n UA = random.choice(self.user_agent_list)\n headers = {'User-Agent': UA}\n\n if proxy == None:\n try:\n return requests.get(url, timeout, headers=headers)\n except:\n if (num_retry - 4) > 0:\n time.sleep(7)\n print('获取网页出错,7s后将获取倒数第:', num_retry, '次!')\n return self.get(url, timeout, num_retry-1)\n else:\n print('开始使用代理!')\n time.sleep(1)\n IP = random.choice(self.iplist)\n proxy = {'http': IP}\n print('当前代理@是:', proxy)\n return self.get(url, timeout, proxy)\n\n else: ##代理不为空\n try:\n return requests.get(url, timeout, headers=headers, proxies=proxy) ##proxies\n except:\n if num_retry > 0:\n time.sleep(7)\n IP = random.choice(self.iplist)\n proxy = {'http': IP}\n num_retry -= 1\n print('正在更换代理,7s后将重新获取倒数第', num_retry, '次')\n print('当前@@代理是:', proxy) \n return requests.get(url, timeout, headers=headers, proxies=proxy) ##proxies\n else:\n print('代理也无法使用了,开始转为本地ip抓起!tor!')\n return self.get(url, timeout=None, proxy=None, num_retry=7)\n\n \ndownload = Download()\n","repo_name":"0xr0ot/PY_self","sub_path":"spider/DOWNLOAD/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"83"} +{"seq_id":"70968044111","text":"import subprocess\nfrom File import File\n\ndef cmdLineOutput(cmd):\n data = subprocess.check_output(cmd, shell=True, stderr=(subprocess.STDOUT))\n data = data.decode('utf-8')\n return data.replace('\\r\\n', '\\n')\n\n\ndef makeBinUtilCommandFile(command: str) -> File:\n BIN_UTILS_COMMAND_FILE_PATH = 'IntermediateFiles/binUtilCommands.txt'\n commandFile = File(BIN_UTILS_COMMAND_FILE_PATH)\n commandFile.write(command)\n assert commandFile.exists()\n return commandFile","repo_name":"Brawlback-Team/brawlback-asm","sub_path":"BuildSystem/src/Common.py","file_name":"Common.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"83"} +{"seq_id":"35270133656","text":"# Copyright (C) 2015, Wazuh Inc.\r\n# Created by Wazuh, Inc. .\r\n# This program is a free software; you can redistribute it and/or modify it under the terms of GPLv2\r\nimport asyncio\r\nfrom datetime import datetime, date\r\nfrom unittest.mock import patch, ANY\r\n\r\nimport pytest\r\nfrom connexion import ProblemException\r\n\r\nfrom api import util\r\nfrom api.api_exception import APIError\r\nfrom wazuh.core.exception import WazuhError, WazuhPermissionError, WazuhResourceNotFound, WazuhInternalError\r\n\r\n\r\nclass TestClass:\r\n def __init__(self, origin=None):\r\n self.swagger_types = {\r\n 'api_response': 'test_api_response',\r\n 'data': str\r\n }\r\n self.attribute_map = {\r\n 'api_response': 'api_response',\r\n 'data': 'data'\r\n }\r\n self.__args__ = ['arg0', 'arg1', 'arg2']\r\n self.__origin__ = origin\r\n\r\n\r\n@pytest.mark.parametrize(\"size_input, expected_size\", [\r\n (\"1m\", 1024 * 1024),\r\n (\"1M\", 1024 * 1024),\r\n (\"1024k\", 1024 * 1024),\r\n (\"1024K\", 1024 * 1024),\r\n (\"5m\", 5 * 1024 * 1024)\r\n])\r\ndef test_APILoggerSize(size_input, expected_size):\r\n \"\"\"Assert `APILoggerSize` class returns the correct number of bytes depending on the given unit.\r\n\r\n Parameters\r\n ----------\r\n size_input : str\r\n Input for the class constructor.\r\n expected_size : int\r\n Expected number of bytes after translating the input.\r\n \"\"\"\r\n assert util.APILoggerSize(size_input).size == expected_size\r\n\r\n\r\ndef test_APILoggerSize_exceptions():\r\n \"\"\"Assert `APILoggerSize` class returns the correct exceptions when the given size is not valid.\"\"\"\r\n # Test invalid units\r\n with pytest.raises(APIError, match=\"2011.*expected format.*\"):\r\n util.APILoggerSize(\"3435j\")\r\n\r\n # Test min value\r\n with pytest.raises(APIError, match=\"2011.*Minimum value.*\"):\r\n util.APILoggerSize(\"1k\")\r\n\r\n\r\n@pytest.mark.parametrize('item, is_transformed', [\r\n (date.today(), False),\r\n (datetime.today(), True)\r\n])\r\ndef test_serialize(item, is_transformed):\r\n \"\"\"Assert serialize() function transform datetime as expected\r\n\r\n Parameters\r\n ----------\r\n item : date\r\n Date object to be transformed\r\n is_transformed : bool\r\n Whether if the returned object should remain the same\r\n \"\"\"\r\n result = util.serialize(item)\r\n\r\n if is_transformed:\r\n assert result != item\r\n else:\r\n assert result == item\r\n\r\n\r\n@pytest.mark.parametrize('item, klass', [\r\n ('test', str),\r\n ('2020-06-24 17:02:53.034374', datetime)\r\n])\r\ndef test_deserialize_primitive(item, klass):\r\n \"\"\"Check that _deserialize_primitive function returns expected object\"\"\"\r\n result = util._deserialize_primitive(item, klass)\r\n assert result == item\r\n\r\n\r\n@pytest.mark.parametrize('item', [\r\n 'test', True, {'key': 'value'}\r\n])\r\ndef test_deserialize_object(item):\r\n \"\"\"Check that _deserialize_object function works as expected\"\"\"\r\n result = util._deserialize_object(item)\r\n assert result == item\r\n\r\n\r\ndef test_deserialize_date():\r\n \"\"\"Check that _deserialize_date function transforms string into date\"\"\"\r\n result = util.deserialize_date('2020-06-24')\r\n assert isinstance(result, date)\r\n\r\n\r\n@patch('dateutil.parser.parse', side_effect=ImportError)\r\ndef test_deserialize_date_ko(mock_import):\r\n \"\"\"Check that _deserialize_date function correctly handles expected exceptions\"\"\"\r\n result = util.deserialize_date('2020-06-24')\r\n assert not isinstance(result, date)\r\n\r\n\r\ndef test_deserialize_datetime():\r\n \"\"\"Check that _deserialize_datetime function transforms string into datetime\"\"\"\r\n result = util.deserialize_datetime('2020-06-24 17:02:53.034374')\r\n assert isinstance(result, datetime)\r\n\r\n\r\n@patch('dateutil.parser.parse', side_effect=ImportError)\r\ndef test_deserialize_datetime_ko(mock_import):\r\n \"\"\"Check that _deserialize_datetime function correctly handles expected exceptions\"\"\"\r\n result = util.deserialize_datetime('2020-06-24 17:02:53.034374')\r\n assert not isinstance(result, date)\r\n\r\n\r\ndef test_deserialize_model():\r\n \"\"\"Check that _deserialize_model function transforms item into desired object\"\"\"\r\n test = {'data': 'test'}\r\n result = util.deserialize_model(test, TestClass)\r\n\r\n assert result.data == 'test'\r\n assert isinstance(result, TestClass)\r\n assert isinstance(result.attribute_map, dict)\r\n assert isinstance(result.swagger_types, dict)\r\n\r\n\r\ndef test_deserialize_list():\r\n \"\"\"Check that _deserialize_list function transforms list of items into list of desired objects\"\"\"\r\n test = ['test1', 'test2']\r\n result = util._deserialize_list(test, TestClass)\r\n assert all(isinstance(x, TestClass) for x in result)\r\n\r\n\r\ndef test_deserialize_dict():\r\n \"\"\"Check that _deserialize_dict function transforms dict of items into dict of desired objects\"\"\"\r\n test = {'key1': 'value', 'key2': 'value', 'key3': 'value'}\r\n result = util._deserialize_dict(test, TestClass)\r\n assert all(isinstance(x, TestClass) for x in result.values())\r\n\r\n\r\n@patch('api.util._deserialize_primitive')\r\n@patch('api.util._deserialize_object')\r\n@patch('api.util.deserialize_date')\r\n@patch('api.util.deserialize_datetime')\r\n@patch('api.util._deserialize_list')\r\n@patch('api.util._deserialize_dict')\r\n@patch('api.util.deserialize_model')\r\ndef test_deserialize(mock_model, mock_dict, mock_list, mock_datetime, mock_date, mock_object, mock_primitive):\r\n \"\"\"Check that _deserialize calls the expected function depending on the class\"\"\"\r\n assert util._deserialize(None, None) is None\r\n\r\n util._deserialize(30, int)\r\n mock_primitive.assert_called_once_with(30, int)\r\n\r\n test_object = TestClass(origin=list)\r\n util._deserialize(test_object, object)\r\n mock_object.assert_called_once_with(test_object)\r\n\r\n util._deserialize('test_date', date)\r\n mock_date.assert_called_once_with('test_date')\r\n\r\n util._deserialize('test_date', datetime)\r\n mock_datetime.assert_called_once_with('test_date')\r\n\r\n util._deserialize([0, 1, 2], test_object)\r\n mock_list.assert_called_once_with([0, 1, 2], 'arg0')\r\n\r\n test_object = TestClass(origin=dict)\r\n util._deserialize({'test_key': 'test_value'}, test_object)\r\n mock_dict.assert_called_once_with({'test_key': 'test_value'}, 'arg1')\r\n\r\n util._deserialize(['test'], list)\r\n mock_model.assert_called_once_with(['test'], list)\r\n\r\n\r\ndef test_remove_nones_to_dict():\r\n \"\"\"Check that remove_nones_to_dict removes key:value when value is None\"\"\"\r\n result = util.remove_nones_to_dict({'key1': 'value1', 'key2': None, 'key3': 'value3'})\r\n assert 'key2' not in result.keys()\r\n\r\n\r\n@pytest.mark.parametrize('param, param_type, expected_result', [\r\n (None, 'search', None),\r\n (None, 'sort', None),\r\n (None, 'random', None),\r\n ('ubuntu', 'search', {'value': 'ubuntu', 'negation': False}),\r\n ('-ubuntu', 'search', {'value': 'ubuntu', 'negation': True}),\r\n ('field1', 'sort', {'fields': ['field1'], 'order': 'asc'}),\r\n ('field1,field2', 'sort', {'fields': ['field1', 'field2'], 'order': 'asc'}),\r\n ('-field1,field2', 'sort', {'fields': ['field1', 'field2'], 'order': 'desc'}),\r\n ('random', 'random', 'random')\r\n])\r\ndef test_parse_api_param(param, param_type, expected_result):\r\n \"\"\"Check that parse_api_param returns the expected result\"\"\"\r\n assert util.parse_api_param(param, param_type) == expected_result\r\n\r\n\r\n@patch('os.path.relpath')\r\ndef test_to_relative_path(mock_real_path):\r\n \"\"\"Check that to_relative_path calls expected function with given params\"\"\"\r\n util.to_relative_path('api/conf/api.yaml')\r\n mock_real_path.assert_called_once_with('api/conf/api.yaml', ANY)\r\n\r\n\r\n@pytest.mark.parametrize('exception_type, code, extra_fields, returned_code, returned_exception', [\r\n (ValueError, 100, None, ValueError(100), ValueError),\r\n (WazuhError, 1000, ['remediation', 'code'], 400, ProblemException),\r\n (WazuhPermissionError, 4000, ['remediation', 'code'], 403, ProblemException),\r\n (WazuhResourceNotFound, 1710, ['remediation', 'code'], 404, ProblemException),\r\n (WazuhInternalError, 1000, ['remediation', 'code'], 500, ProblemException)\r\n])\r\ndef test_create_problem(exception_type, code, extra_fields, returned_code, returned_exception):\r\n \"\"\"Check that _create_problem returns exception with expected data\"\"\"\r\n with pytest.raises(returned_exception) as exc_info:\r\n util._create_problem(exception_type(code))\r\n\r\n if returned_exception == ProblemException:\r\n assert exc_info.value.status == returned_code\r\n if extra_fields:\r\n assert all(x in exc_info.value.ext.keys() for x in extra_fields)\r\n assert None not in exc_info.value.ext.values()\r\n\r\n\r\n@pytest.mark.parametrize('obj, code', [\r\n ((WazuhError(6001), ['value0', 'value1']), 429),\r\n ((WazuhInternalError(1000), ['value0', 'value1']), None),\r\n ((WazuhPermissionError(4000), ['value0', 'value1']), None),\r\n ((WazuhResourceNotFound(1710), ['value0', 'value1']), None)\r\n])\r\n@patch('api.util._create_problem')\r\ndef test_raise_if_exc(mock_create_problem, obj, code):\r\n \"\"\"Check that raise_if_exc calls _create_problem when an exception is given\"\"\"\r\n result = util.raise_if_exc(obj)\r\n if isinstance(obj, Exception):\r\n mock_create_problem.assert_called_once_with(obj, code)\r\n else:\r\n assert result == obj\r\n\r\n\r\n@pytest.mark.parametrize(\"dikt, f_kwargs, invalid_keys\", [\r\n ({\"key1\": 0, \"key2\": 0}, {\"key1\": 0}, {\"key2\"}),\r\n ({\r\n \"key1\": 0,\r\n \"key2\": {\r\n \"key21\": 0,\r\n \"key22\": {\r\n \"key221\": 0,\r\n \"key222\": {\r\n \"key2221\": 0\r\n }\r\n }\r\n }\r\n },\r\n {\r\n \"key2\": {\r\n \"key22\": {\r\n \"key221\": 0\r\n }\r\n }\r\n },\r\n {\"key1\", \"key21\", \"key222\"}),\r\n ({\"key1\": 0}, {\"key1\": 0, \"key2\": 0}, set())\r\n])\r\ndef test_get_invalid_keys(dikt, f_kwargs, invalid_keys):\r\n \"\"\"Check that `get_invalid_keys` return the correct invalid keys when comparing two dictionaries with more\r\n than one nesting level.\"\"\"\r\n invalid = util.get_invalid_keys(dikt, f_kwargs)\r\n assert invalid == invalid_keys\r\n\r\n\r\n@pytest.mark.parametrize('link', [\r\n '',\r\n 'https://documentation.wazuh.com/current/user-manual/api/reference.html'\r\n])\r\n@pytest.mark.asyncio\r\nasync def test_deprecate_endpoint(link):\r\n \"\"\"Check that `deprecate_endpoint` decorator adds valid deprecation headers.\"\"\"\r\n class DummyObject:\r\n headers = {}\r\n\r\n @util.deprecate_endpoint(link=link)\r\n def dummy_func():\r\n future_response = asyncio.Future()\r\n future_response.set_result(DummyObject())\r\n return future_response\r\n\r\n response = await dummy_func()\r\n assert response.headers.pop('Deprecated') == 'true', 'No deprecation key in header'\r\n if link:\r\n assert response.headers.pop('Link') == f'<{link}>; rel=\"Deprecated\"', 'No link was found'\r\n\r\n assert response.headers == {}, f'Unexpected deprecation headers were found: {response.headers}'\r\n","repo_name":"wazuh/wazuh","sub_path":"api/api/test/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":11081,"program_lang":"python","lang":"en","doc_type":"code","stars":7656,"dataset":"github-code","pt":"83"} +{"seq_id":"1657219736","text":"# coding=utf-8\n\n''' 显示层 '''\n\nimport logging\nimport Queue\nimport time\nimport threading\n\nfrom . import shared_var\n\nclass TinifyCliDisplay(object):\n def __init__(self, log_to_stderr=False, log_to_file=False):\n self.logger = logging.getLogger('tinify-cli')\n hndl = logging.StreamHandler()\n if shared_var.is_debug:\n hndl.setFormatter(\n logging.Formatter(\n fmt='[%(levelname)s] %(filename)s:%(lineno)s %(funcName)s'\n ' @ %(asctime)s => %(message)s',\n datefmt='%H:%M:%S'))\n hndl.setLevel(logging.DEBUG)\n else:\n hndl.setFormatter(\n logging.Formatter(\n fmt='[%(levelname)s] %(asctime)s : %(message)s',\n datefmt='%H:%M:%S'))\n hndl.setLevel(logging.INFO)\n\n if log_to_stderr:\n self.logger.addHandler(hndl)\n self.logger.setLevel(logging.DEBUG)\n if log_to_file:\n filename = time.strftime(\n 'tinify-cli.%Y-%m-%d-%H-%M-%S.log',\n time.gmtime())\n self.logger.addHandler(\n logging.FileHandler(\n filename,\n encoding='utf-8'))\n\n self.mailbox = Queue.Queue() # for progress_bar_view\n\n def set_logging_level(self, level):\n '''\n level 可以取 \"NOTSET\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"CRITICAL\"\n 中的任何一个\n '''\n self.logger.setLevel(level=eval(\"logging.\" + level))\n\n #def start_progress_bar(self):\n #self.progress_bar_thread = threading.Thread(\n #target=self.progress_bar,\n #name=\"progress_bar\")\n #self.progress_bar_thread.setDaemon(True)\n #self.progress_bar_thread.start()\n\n #def progress_bar(self):\n #pass\n","repo_name":"aheadlead/tinify-cli","sub_path":"tinifycli/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"83"} +{"seq_id":"14244485714","text":"import hashlib\nimport sys\nfrom amara.thirdparty import json\nfrom amara.lib.iri import is_absolute\nfrom akara.services import simple_service\nfrom akara.util import copy_headers_to_dict\nfrom akara import request, response\nfrom dplaingestion.selector import getprop, setprop, exists\n\nCOUCH_ID_BUILDER = lambda src, lname: \"--\".join((src,lname))\nCOUCH_REC_ID_BUILDER = lambda src, id_handle: COUCH_ID_BUILDER(src,id_handle.strip().replace(\" \",\"__\"))\n\n@simple_service('POST', 'http://purl.org/la/dp/select-oac-id', 'select-oac-id',\n 'application/json')\ndef selectid(body, ctype):\n ''' \n Service that accepts a JSON document and adds or sets the \"id\" property to\n the value of the property named by the \"prop\" paramater\n ''' \n try :\n data = json.loads(body)\n except:\n response.code = 500\n response.add_header('content-type', 'text/plain')\n return \"Unable to parse body as JSON\"\n\n request_headers = copy_headers_to_dict(request.environ)\n source_name = request_headers.get('Source')\n\n objid = None\n v = getprop(data, 'identifier')\n if isinstance(v,basestring):\n objid = v\n else:\n if v:\n for h in (v if isinstance(v, list) else [v]):\n if h['text'].startswith('http://ark.cdlib.org/ark:'):\n if is_absolute(h['text']):\n objid = h['text']\n if not objid:\n objid = v[0]\n\n if not objid:\n response.code = 500\n response.add_header('content-type', 'text/plain')\n return \"No id property was found\"\n\n data[u'_id'] = COUCH_REC_ID_BUILDER(source_name, objid)\n data[u'id'] = hashlib.md5(data[u'_id']).hexdigest()\n data[u'isShownAt'] = objid\n data[u'isShownBy'] = objid + '/thumbnail'\n\n return json.dumps(data)\n","repo_name":"calisphere-legacy-harvester/dpla-ingestion","sub_path":"lib/akamod/select_oac_id.py","file_name":"select_oac_id.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"83"} +{"seq_id":"22183931858","text":"# Databricks notebook source\ndef setupdb (env:str) -> None:\n try:\n spark.sql(\n f\"\"\"CREATE database if not exists {env}_bronze_db\n LOCATION '/FileStore/{env}_bronze_db'\n \"\"\"\n )\n print(\"Database \"+env+\"_bronze_db has been setup\")\n except:\n print('Database Creation Failed')\n\n \n","repo_name":"Fredy6789/databricks","sub_path":"Arch/Setup/SetupDB.py","file_name":"SetupDB.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"27102774481","text":"class Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n \n n = len(arr)\n arr.sort()\n \n m = arr[n // 2] if n % 2 else arr[n // 2 - 1]\n \n def compare(x, y):\n valueX, valueY = abs(x - m), abs(y - m)\n if valueX == valueY:\n return y - x\n else:\n return valueY - valueX\n \n arr.sort(key = functools.cmp_to_key(compare))\n \n return arr[:k]","repo_name":"ChengTsungPao/LeetCode","sub_path":"1471_The_k_Strongest_Values_in_an_Array/code2.py","file_name":"code2.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"83"} +{"seq_id":"33034593011","text":"import os\nimport platform\nimport subprocess\nfrom datetime import datetime, time, timedelta\nimport pandas as pd\n\nCURRENT_DAY = datetime.today()\nTHREE_MONTHS_BEFORE = CURRENT_DAY - timedelta(days=90)\nSIX_MONTHS_BEFORE = CURRENT_DAY - timedelta(days=180)\nYEAR_BEFORE = CURRENT_DAY - timedelta(days=365)\n\n# Timestamps\nCURRENT_DAY_TS = datetime.timestamp(CURRENT_DAY)\nTHREE_MONTHS_BEFORE_TS = datetime.timestamp(THREE_MONTHS_BEFORE)\nSIX_MONTHS_BEFORE_TS = datetime.timestamp(SIX_MONTHS_BEFORE)\n# YEAR_BEFORE_TS = datetime.timestamp(YEAR_BEFORE)\nYEAR_BEFORE_TS = 1577840401\n\n\n# related to date and time\ndef date_suffix(d):\n return 'th' if 11 <= d <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(d % 10, 'th')\n\n\ndef custom_strftime(format, t):\n return t.strftime(format).replace('{S}', str(t.day) + date_suffix(t.day))\n\n\ndef is_time_between(begin_time, end_time, check_time=None):\n begin_time = time(begin_time[0], begin_time[1])\n end_time = time(end_time[0], end_time[1])\n check_time = check_time or datetime.now().time()\n if begin_time < end_time:\n return check_time >= begin_time and check_time <= end_time\n else:\n return False\n\n\ndef get_start_end_date():\n final_start_date = ''\n start_date_human_readble = ''\n final_end_date = ''\n end_date_human_readble = ''\n\n try:\n today = datetime.today()\n five_days_ago = today - timedelta(days=5)\n\n start_date = input(\n \"Start Date (YYYY-MM-DD): \").strip() or five_days_ago.strftime('%Y-%m-%d')\n\n end_date = input(\n \"End Date (YYYY-MM-DD): \").strip() or today.strftime('%Y-%m-%d')\n\n if start_date != '':\n start_date = start_date.replace('/', '-')\n start_date = datetime.strptime(start_date, '%Y-%m-%d')\n final_start_date = start_date.strftime('%Y-%m-%d')\n start_date_human_readble = custom_strftime(\n '{S} %A %B, %Y', start_date)\n\n if end_date != '':\n end_date = end_date.replace('/', '-')\n end_date = datetime.strptime(end_date, '%Y-%m-%d')\n final_end_date = end_date.strftime('%Y-%m-%d')\n end_date_human_readble = custom_strftime(\n '{S} %A %B, %Y', end_date)\n\n except Exception as e:\n print(e)\n final_start_date = five_days_ago.strftime('%Y-%m-%d')\n start_date_human_readble = custom_strftime(\n '{S} %A %B, %Y', five_days_ago)\n\n final_end_date = today.strftime('%Y-%m-%d')\n end_date_human_readble = custom_strftime(\n '{S} %A %B, %Y', today)\n\n start_end_date = {\n 'start_date': [final_start_date, start_date_human_readble],\n 'end_date': [final_end_date, end_date_human_readble]\n }\n\n return start_end_date\n\n\ndef clear_screen():\n command = \"cls\" if platform.system().lower() == \"windows\" else \"clear\"\n return subprocess.call(command, shell=True)\n\n\ndef print_char_under_string(msg, char='', newline='\\n\\n'):\n if char != '':\n msg += \"\\n\" + (char * len(msg))\n print(msg, end=newline)\n\n\ndef create_related_dirs(project_dirs):\n # create 2 separate directories to save html and the scraped data\n for dirname, dirpath in project_dirs.items():\n # check weather the dir exists, if not create new one\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n print(\"{}: '{}' directory is created.\".format(dirname, dirpath))\n\n\ndef get_nse_listed_companies():\n listings = pd.read_csv(\"data/listedcompanies/listedcompanies.csv\")\n listings.set_index('SYMBOL')\n return listings.set_index('SYMBOL').T.to_dict('list')\n","repo_name":"vkuberan/yfinance","sub_path":"commonfunctions.py","file_name":"commonfunctions.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"35374424871","text":"from engine.frontend.globales import COLOR_TEXTO, COLOR_TERRESTIAL, COLOR_GASDWARF, COLOR_HABITABLE\r\nfrom engine.frontend.globales import COLOR_GASGIANT, COLOR_PUFFYGIANT, COLOR_DWARFPLANET\r\nfrom engine.frontend.globales import COLOR_ROCKYMOON, COLOR_ICYMOON, COLOR_IRONMOON\r\nfrom .listed_body import ListedBody\r\n\r\n\r\nclass ColoredBody(ListedBody):\r\n def __init__(self, parent, astro, name, x, y):\r\n self._color = self.set_color(astro)\r\n super().__init__(parent, astro, name, x, y)\r\n\r\n self.name = 'Button of '+str(self.object_data)\r\n\r\n def set_color(self, astro):\r\n color = COLOR_TEXTO\r\n if astro.celestial_type not in ('star', 'system'):\r\n if astro.clase == 'Terrestial Planet':\r\n if astro.habitable:\r\n color = COLOR_HABITABLE\r\n else:\r\n color = COLOR_TERRESTIAL\r\n elif astro.clase in ('Gas Giant', 'Super Jupiter'):\r\n color = COLOR_GASGIANT\r\n elif astro.clase == 'Puffy Giant':\r\n color = COLOR_PUFFYGIANT\r\n elif astro.clase == 'Gas Dwarf':\r\n color = COLOR_GASDWARF\r\n elif astro.clase == 'Dwarf Planet':\r\n color = COLOR_DWARFPLANET\r\n elif astro.comp == 'Rocky':\r\n color = COLOR_ROCKYMOON\r\n elif astro.comp == 'Icy':\r\n color = COLOR_ICYMOON\r\n elif astro.comp == 'Iron':\r\n color = COLOR_IRONMOON\r\n\r\n self._color = color\r\n return color\r\n\r\n def on_mousebuttondown(self, event):\r\n raise NotImplementedError()\r\n\r\n def move(self, x, y):\r\n self.rect.topleft = x, y\r\n\r\n def __repr__(self):\r\n return self.name\r\n","repo_name":"AzoeDesarrollos/worldbuilding","sub_path":"engine/frontend/widgets/panels/common/planet_button.py","file_name":"planet_button.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"70787350032","text":"from constants import FIELD_H_NODES, FIELD_W_NODES\n\n\nclass Playground:\n def __init__(self):\n self.minx = 0\n self.maxx = FIELD_W_NODES - 1\n self.miny = 0\n self.maxy = FIELD_H_NODES - 1\n\nplayground = Playground()\n","repo_name":"KirillMysnik/PySnake","sub_path":"modules/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"70027976913","text":"#!/usr/bin/env python3\nimport rospy\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\nimport cv2\n\nclass ImageSubscriber:\n def __init__(self):\n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber(\"cv_camera/image_raw\", Image, self.callback)\n\n def callback(self, data):\n try:\n # Menurunkan resolusi gambar\n width = 320\n height = 240\n\n # Mengubah gambar menjadi array numpy\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n\n # Mengubah ukuran gambar\n frame = cv2.resize(cv_image, (width, height))\n\n except CvBridgeError as e:\n print(e)\n\n # Menampilkan gambar pada jendela\n cv2.imshow(\"Image window\", frame)\n cv2.waitKey(1)\n\ndef main():\n rospy.init_node('image_subscriber', anonymous=True)\n ic = ImageSubscriber()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main()\n","repo_name":"Frey210/Y-BOT_Kinect_SLAM","sub_path":"src/vision/scripts/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"8027435637","text":"import sys\n\nline = sys.stdin.readlines()\n\n\ndef main(line):\n for i in range(len(line)):\n l = line[i].rstrip('\\r\\n')\n es = ves = ies = None\n if not l.isalpha():\n continue\n es = checkES(l)\n ves = checkVES(l)\n ies = checkIES(l)\n if es:\n print(es)\n elif ves:\n print(ves)\n elif ies:\n print(ies)\n elif not ies and not es and not ves:\n print(l + \"s\")\n\n\ndef is_str(v):\n return type(v) is str\n\n\ndef checkES(s):\n add_str = \"es\"\n one = s[-1:]\n two = s[-2:]\n if one == \"s\" or one == \"o\" or one == \"x\" or two == \"sh\" or two == \"ch\":\n return s + add_str\n\n\ndef checkIES(s) -> None:\n one = s[-1:]\n if one == \"y\":\n two = s[-2:-1]\n if two == 'a' or two == \"i\" or two == \"u\" or two == \"e\" or two == \"o\":\n return s + \"s\"\n else:\n return s[:-1] + \"ies\"\n\n\ndef checkVES(s) -> None:\n add_str = \"ves\"\n one = s[-1:]\n two = s[-2:]\n if one == \"f\":\n return s[:-1] + add_str\n elif two == \"fe\":\n return s[:-2] + add_str\n\n\nif __name__ == '__main__':\n main(line)\n","repo_name":"juuuuuun-dev/coding-interview","sub_path":"etc/b_multi.py","file_name":"b_multi.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"42508210641","text":"str=input()\n\nstrList=[]\nfor e in str:\n strList.append(e)\n\nstrList.sort()\n\nfrontStr=\"\"\nmidleStr=\"\"\nbackStr=\"\"\nwhile True:\n alphabet=strList[0]\n idx=strList.index(alphabet)\n count=strList.count(alphabet)\n if count%2==0:\n tempStr=\"\".join(s for s in strList[0:count//2])\n frontStr+=tempStr\n backStr=tempStr+backStr\n else:\n if midleStr!=\"\":\n print(\"I'm Sorry Hansoo\")\n exit()\n tempStr=\"\".join(s for s in strList[0:count//2])\n frontStr+=tempStr\n backStr=tempStr+backStr\n midleStr+=strList[0]\n \n if len(strList)!=count:\n strList=strList[count:]\n else:\n break\n\nprint(frontStr+midleStr+backStr)\n\n","repo_name":"Beopsik/PS","sub_path":"BOJ1213.py","file_name":"BOJ1213.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"22930584319","text":"__author__ = \"Matt Davis\"\n__email__ = \"matthew1.davis@intel.com\"\n__description__ = \"This script loads data for the GSM_ATS_SCCI_Proc_1SOT tabular model by staging the data in the GSMDW database on sql1717-fm1-in.amr.corp.intel.com,3181\"\n__schedule__ = \"Daily at 7:10 AM PST\"\n\nimport os, sys; sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) # add current file's parent directory to path\nimport pandas as pd\nimport numpy as np\nfrom re import sub\nfrom datetime import datetime\nfrom time import time\nimport shutil\nfrom office365.runtime.auth.client_credential import ClientCredential\nfrom office365.runtime.client_request_exception import ClientRequestException\nfrom office365.sharepoint.client_context import ClientContext\nfrom Project_params import params\nfrom Helper_Functions import loadExcelFile, uploadDFtoSQL, getSQLCursorResult,loadSharePointList, getLastRefresh, map_columns\nfrom Logging import log, log_warning\nfrom Password import accounts\n\n\n# remove the current file's parent directory from sys.path\ntry:\n sys.path.remove(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))\nexcept ValueError: # Already removed\n pass\n\n\ndef convert(tup, dictionary):\n for a, b in tup:\n dictionary[a] = b\n return dictionary\n\n\ndef get_sharepoint_files(sp_site: str, relative_url: str):\n # Connect to SharePoint Online\n client_credentials = ClientCredential(accounts['SharePoint'].client_id, accounts['SharePoint'].client_secret)\n ctx = ClientContext(sp_site).with_credentials(client_credentials)\n\n # Load folder information using relative path information\n folder = ctx.web.get_folder_by_server_relative_path(relative_url)\n ctx.load(folder)\n try:\n ctx.execute_query()\n except ClientRequestException:\n return []\n\n # Load all files in the folder\n sp_files = folder.files\n ctx.load(sp_files)\n ctx.execute_query()\n\n return sp_files\n\n\nif __name__ == \"__main__\":\n start_time = time()\n # print(start_time)\n\n params['EMAIL_ERROR_RECEIVER'].append('abhishek.agnihotri@intel.com')\n project_name = 'ATS Operations Dashboard'\n\n ##### BEGIN PSI OTT #####\n # initialize variables\n data_area = 'PSI OTT'\n sp_site = 'https://intel.sharepoint.com/sites/gscatstestsupplierottmanagement'\n table = 'ats.PSI_OTT'\n\n # Determine last upload date\n last_refreshed = getLastRefresh(project_name=project_name, data_area=data_area)\n\n # Extract data from SharePoint Online Lists\n df = loadSharePointList(sp_site=sp_site, list_name='PSI OTT Current', decode_column_names=True, remove_metadata=True, last_upload_time=last_refreshed)\n df_archive = loadSharePointList(sp_site=sp_site, list_name='PSI OTT Archive', decode_column_names=True, remove_metadata=True)\n if len(df.index) == 0: # PSI OTT Current SharePoint List has not been updated since last script run\n log_warning(project_name=project_name, data_area=data_area, warning_type='Not Modified')\n print('\"{} Current\" SharePoint List has not been updated since last run. Skipping.'.format(data_area))\n else:\n if len(df_archive) == 0: # PSI OTT Archive has not been updated since last refresh\n log(False, project_name=project_name, data_area=data_area, error_msg='Unable retrieve SharePoint List \"{} Archive\".'.format(data_area))\n else:\n df = df.append(df_archive) # combine DataFrames\n\n # Transform data\n keep_columns = ['Title', 'Category', 'ATD', 'ATD On Time to', 'Gap',\n 'Potential Late Penal', 'MM', 'PO#', 'PO Line', 'PO Line Qty', 'RTD',\n 'Description', 'Late Reason', 'Remedy Recommendation', 'CTD',\n 'CCMComments', 'CMComments', 'ReconciledATD', 'ReconciledCTD',\n 'CCMOTTRecommendation', 'CCM', 'CM', 'CCMProgress', 'CMProgress',\n 'GR Date', 'SupplierPartNumber', 'SupplierID', 'POCreateDate']\n try:\n df = df[keep_columns] # manually change column order to match database table\n\n # Data type conversions\n for col in ['ATD', 'GR Date', 'CTD', 'RTD', 'ReconciledATD', 'ReconciledCTD', 'POCreateDate']: # date columns\n df[col] = pd.to_datetime(df[col], errors='coerce').dt.date # format='%Y-%m-%dT%H:%M:%S:%Z'\n for col in ['PO#', 'PO Line', 'Gap', 'SupplierID']: # integer columns\n df[col] = pd.to_numeric(df[col], errors='coerce')\n\n df['Remedy Recommendation'].replace(r'^\\s\\$\\s*\\-\\s*$', np.nan, regex=True, inplace=True) # remove random space dash combinations\n\n # Filter rows to remove where Supplier = \"Adder Line\"\n df = df.loc[df['Title'].str.lower() != \"adder line\"]\n\n # Add columns for logging\n df['LoadDtm'] = pd.to_datetime('today')\n df['LoadBy'] = 'AMR\\\\' + os.getlogin().upper()\n\n columns = ['Supplier', 'POType', 'ATD', 'ATDOnTimeToCTD', 'Gap',\n 'CalculatedPenalty', 'MM', 'PONumber', 'POLine', 'POLineQty', 'RTD',\n 'Description', 'LateReason', 'SuggestedPenalty', 'CTD',\n 'CCMComments', 'CMComments', 'ReconciledATD', 'ReconciledCTD',\n 'CMOTTRecommendation', 'CCM', 'CM', 'CCMProgress', 'CMProgress',\n 'GRDate', 'SupplierPartNumber', 'SupplierID','POCreateDate', 'LoadDtm', 'LoadBy']\n\n # map_columns(table, df, sql_columns=columns)\n\n # Load data into SQL Server database\n insert_succeeded, error_msg = uploadDFtoSQL(table, df, columns=columns, truncate=True, driver='{ODBC Driver 17 for SQL Server}')\n log(insert_succeeded, project_name=project_name, data_area=data_area, row_count=df.shape[0], error_msg=error_msg)\n if insert_succeeded:\n print('Successfully inserted {0} records into {1}'.format(df.shape[0], table))\n\n except KeyError as error:\n log(False, project_name=project_name, data_area=data_area, error_msg=\"Column missing/changed. Full error: {0}\".format(error))\n ##### END PSI OTT #####\n\n ##### BEGIN Test Supplier Capacities #####\n # initialize variables\n data_area = 'Supplier Capacities'\n sp_site = 'https://intel.sharepoint.com/sites/gscatstestall'\n table = 'ats.Test_Supplier_Capacities'\n\n # Determine last upload date\n last_refreshed = getLastRefresh(project_name=project_name, data_area=data_area)\n\n df = loadSharePointList(sp_site=sp_site, list_name='Test Supplier Capacities', decode_column_names=True, remove_metadata=True, last_upload_time=last_refreshed)\n if len(df.index) == 0:\n log_warning(project_name=project_name, data_area=data_area, warning_type='Not Modified')\n print('\"{}\" SharePoint List has not been updated since last run. Skipping.'.format(data_area))\n else:\n keep_columns = ['ItemType', 'SupplierID','Supplier', 'ItemFamily','Prev.Capacity(unitsp', 'Capacity(unitsperweek',\n 'PlannedCapacity(units','CMComments','Title']\n try:\n df = df[keep_columns] # remove other columns & reorder columns\n df['ModifiedDateTime'] = pd.to_datetime('today')\n\n insert_succeeded, error_msg = uploadDFtoSQL(table=table, data=df, categorical=['SupplierID'], truncate=True)\n log(insert_succeeded, project_name=project_name, data_area=data_area, row_count=df.shape[0], error_msg=error_msg)\n if insert_succeeded:\n print('Successfully inserted {0} records into {1}'.format(df.shape[0], table))\n\n except KeyError as error:\n log(False, project_name=project_name, data_area=data_area, error_msg=\"Column missing/changed in Test Supplier Capacities List. Full error: {0}\".format(error))\n ##### END Test Supplier Capacities #####\n\n ##### BEGIN PSI Forecast #####\n # initialize variables\n sp_site = \"https://intel.sharepoint.com/sites/gscatsscci-SCCITabularModelDataSources/\"\n relative_url = \"/sites/gscatsscci-SCCITabularModelDataSources/Shared Documents/SCCI Tabular Model Data Sources/ATMBO PSI Forecast Files\"\n data_area = 'ATMBO PSI Forecast'\n table = 'ats.ATMBO_PSI_Forecast'\n\n # Create mapping table to convert Work Week stamp into dates\n query_succeeded, result, error_msg = getSQLCursorResult(\"\"\"SELECT CONCAT(LEFT(Intel_WW, 4), '.', RIGHT(Intel_WW, 2), '.', CASE WHEN day_of_ww_nbr < 10 THEN CONCAT('0', day_of_ww_nbr) ELSE day_of_ww_nbr END), clndr_dt\n FROM dbo.Intel_Calendar\n WHERE fscl_yr_int_nbr >= 2020 AND (day_of_ww_nbr IS NOT NULL AND day_of_ww_nbr <> 'NULL')\"\"\"\n )\n dates = dict()\n if not query_succeeded:\n print(error_msg)\n log(False, project_name=project_name, data_area=data_area, error_msg=error_msg)\n exit(1) # stop the file reporting error\n else:\n convert(result, dates)\n\n # Load information about which PSI Forecast was last loaded to SQL database table\n query_succeeded, result, error_msg = getSQLCursorResult(\"\"\"SELECT CONCAT(LEFT(Intel_WW, 4), '.', RIGHT(Intel_WW, 2), '.', CASE WHEN day_of_ww_nbr < 10 THEN CONCAT('0', day_of_ww_nbr) ELSE day_of_ww_nbr END) AS [stamp]\n FROM dbo.Intel_Calendar\n WHERE clndr_dt = (SELECT MAX([ModifiedDateTime]) FROM {0})\"\"\".format(table)\n )\n if not query_succeeded:\n print(error_msg)\n log(False, project_name=project_name, data_area=data_area, error_msg=error_msg)\n exit(1)\n else:\n last_loaded_stamp = result[0][0] # result[0][0].split('_')[-1][:10]\n # last_loaded_stamp = '2022.49.03' # hard-code last loaded stamp for debug purposes\n print('The last file stamp loaded into the database is: {0}'.format(last_loaded_stamp))\n\n sp_files = get_sharepoint_files(sp_site=sp_site, relative_url=relative_url)\n if not sp_files:\n error_msg = 'Unable to connect to SharePoint site: {0}'.format(sp_site)\n print(error_msg)\n log(False, project_name=project_name, data_area='ATMBO PSI Forecast', error_msg=error_msg)\n\n latest_file_name = ''\n\n # iterate over all files in the SharePoint Online folder\n for excel_file in sp_files:\n # print('File name: {}'.format(excel_file.properties['ServerRelativeUrl']))\n stamp = excel_file.properties['Name'].split('_')[-1][:10]\n if stamp > last_loaded_stamp: # determine if file is newer than the last one loaded into the SQL database table\n latest_file_name = excel_file.properties['Name']\n print('New file: {}'.format(latest_file_name))\n\n upload_dt = dates[stamp] # convert the stamp [Year].[Work Week].[Day of Work Week] into a real date\n print('Uploaded on: {}'.format(upload_dt))\n\n # Load Excel File from SharePoint Online into Pandas DataFrame\n latest_file_path = 'https://intel.sharepoint.com/:x:/r' + relative_url + '/' + latest_file_name\n df = pd.DataFrame()\n df1 = loadExcelFile(file_path=latest_file_path, sheet_name='RDD Table', header_row=0)\n try:\n df2 = loadExcelFile(latest_file_path, 'RDD Table_CRO_4th Quarter', header_row=0)\n df = pd.concat([df1, df2]) # Append second Excel tab to first\n except ValueError as error:\n if str(error) == \"Worksheet named 'RDD Table_CRO_4th Quarter' not found\":\n df = df1\n else:\n log(False, project_name=project_name, data_area='ATMBO PSI Forecast', error_msg=error)\n exit(1)\n # print(df.columns)\n\n # Get column format to match SQL database table\n keep_columns = ['Product', 'Tool', 'Cycle', 'Site', 'ProcureBy', 'Name', 'Type', 'Material',\n 'Supplier Name', 'Supplier Number', 'OaDescription', 'Quantity', 'UOM', 'Date', 'CND',\n 'Subcategory', 'Repairable', 'FundType', 'Forecast$', 'OAUnit$', 'OaLeadTime',\n 'CPA Month', 'Fund Loaded?', 'Status', 'Line Item', 'Remark', 'CRO', 'Checkpoint',\n 'Quarter', 'Common Product Name', 'Category']\n try:\n df = df[keep_columns] # manually change column order to match database table\n except KeyError as error:\n log(False, project_name=project_name, data_area='ATMBO PSI Forecast', error_msg=\"Column missing/changed in PSI Forecast file. Full error: {0}\".format(error))\n exit(1)\n\n # Data massaging for SQL table\n df['Roadmap Segment'] = df['Product'].apply(lambda x: x.split(',')[2] if isinstance(x, str) and len(x.split(',')) > 3 else None) # Only keep product info before the first comma\n df['Product'] = df['Product'].apply(lambda x: x.split(',')[0] if isinstance(x, str) else None) # Only keep product info before the first comma\n\n try:\n df['Date'] = df['Date'].apply(lambda x: x if isinstance(x, datetime) else datetime.strptime(x, '%d %b %Y')) # Convert text \"9 Apr 2021\" to Datetime object\n\n money_columns = ['OAUnit$', 'Forecast$']\n for col in money_columns:\n df[col] = df[col].apply(lambda x: sub(r'[^\\d.]', '', x) if isinstance(x, str) else x) # Remove text \" (OA)\" after decimal number\n df[col] = df[col].apply(lambda x: None if isinstance(x, str) and x == '' else float(x)) # Ignore rows without any values\n\n df['Quantity'] = df['Quantity'].apply(lambda x: sub(r'[^\\d.]', '', x.split('(')[0]) if isinstance(x, str) and '(' in x # Parse first number from cases like \"1 (1 ST of 1)\"\n else sub(r'[^\\d.]', '', x) if isinstance(x, str) # Remove text \" EA\" after number\n else x)\n df['Quantity'] = pd.to_numeric(df['Quantity'], errors='coerce') # convert the strings into numbers for insertion into database\n\n except ValueError as error: # Catch errors with different format of date text, and values that cannot be cast as int or float\n print(error)\n log(False, project_name=project_name, data_area=data_area, row_count=0, error_msg=error)\n exit(1)\n\n tf_columns = ['Repairable', 'Fund Loaded?', 'CRO']\n for col in tf_columns:\n df[col] = df[col].apply(lambda x: True if isinstance(x, str) and x.lower() == 'yes' else False if isinstance(x, str) and x.lower() == 'no' else None) # Change Yes/No column to True/False\n\n df['Module'] = df['Tool'].apply(lambda x: x.split('#')[0] if isinstance(x, str) else None) # Create new column \"Module\" that takes everything from the \"Tool\" column before the first\n df['OaLeadTime'] = df['OaLeadTime'].apply(lambda x: float(sub(r'[^\\d.]', '', x)) if isinstance(x, str) else float(x)) # Remove text \" (OA)\" after decimal number\n\n df['ModifiedDateTime'] = upload_dt # append modified date\n\n columns = ['Product', 'Tool', 'Cycle', 'Site', 'Procure By', 'PSIG', 'Type', 'IPN', 'Supplier Name',\n 'Supplier Part Number', 'OA Description', 'Quantity', 'UOM', 'RDD', 'CND', 'Subcategory',\n 'Repairable', 'Fund Type', 'Forecasted Spends', 'OA Unit Price', 'EMS Lead Time',\n 'CPA Month', 'Fund Loaded', 'Status', 'Forecast Line Item', 'Remark', 'CRO Flag',\n 'CRO Checkpoint', 'CRO Quarter', 'Common Product Name', 'Category', 'Product Segment',\n 'Module', 'ModifiedDateTime']\n\n # # Debugging - uncomment the following two lines if you face an upload error and need to determine the number of characters in a column\n # print(df.dtypes)\n # map_columns(table, df, sql_columns=columns)\n\n # Insert data into SQL database table\n insert_succeeded, error_msg = uploadDFtoSQL(table=table, data=df, columns=columns, categorical=['Material'], truncate=False, driver=\"{ODBC Driver 17 for SQL Server}\")\n log(insert_succeeded, project_name=project_name, data_area=data_area, row_count=df.shape[0], error_msg=error_msg)\n if insert_succeeded:\n print('Successfully inserted {0} records into {1}'.format(df.shape[0], table))\n ##### END PSI Forecast #####\n\n ##### BEGIN MPE PSI Forecast #####\n # initialize variables\n sp_site = \"https://intel.sharepoint.com/sites/mpecollateralsforecast\"\n relative_url = \"/sites/mpecollateralsforecast/Shared Documents/General/Forecast and Readiness\"\n table = 'ats.MPE_PSI_Forecast'\n data_area = 'MPE PSI Forecast'\n\n # Load information about which PSI Forecast was last loaded to SQL database table\n query_succeeded, result, error_msg = getSQLCursorResult(\"\"\"SELECT CONCAT(LEFT(Intel_WW, 4), '.', RIGHT(Intel_WW, 2), '.', CASE WHEN day_of_ww_nbr < 10 THEN CONCAT('0', day_of_ww_nbr) ELSE day_of_ww_nbr END) AS [stamp]\n FROM dbo.Intel_Calendar\n WHERE clndr_dt = (SELECT MAX([ModifiedDateTime]) FROM {0})\"\"\".format(table)\n )\n if not query_succeeded:\n print(error_msg)\n log(False, project_name=project_name, data_area=data_area, error_msg=error_msg)\n else:\n try:\n last_loaded_stamp = result[0][0]\n except IndexError:\n today_datetime = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) # strip time from today's date\n dates_reverse_lookup = {value: key for key, value in dates.items()}\n last_loaded_stamp = dates_reverse_lookup[today_datetime] # get today's stamp from dates dict\n # last_loaded_stamp = '2022.45.02' # hardcode the last_loaded_stamp\n print('The last file stamp loaded into the database is: {0}'.format(last_loaded_stamp))\n\n sp_files = get_sharepoint_files(sp_site=sp_site, relative_url=relative_url)\n if not sp_files:\n error_msg = 'Unable to connect to SharePoint site: {0}'.format(sp_site)\n print(error_msg)\n log(False, project_name=project_name, data_area=data_area, error_msg=error_msg)\n\n # iterate over all files in the SharePoint Online folder\n for excel_file in sp_files:\n print('File name: {}'.format(excel_file.properties['ServerRelativeUrl']))\n\n stamp = excel_file.properties['Name'].split('_')[-1][:10]\n # print(stamp)\n if stamp > last_loaded_stamp: # determine if file is newer than the last one loaded into the SQL database table\n latest_file_name = excel_file.properties['Name']\n print('New file: {}'.format(latest_file_name))\n\n # Load Excel File from SharePoint Online into Pandas DataFrame\n latest_file_path = 'https://intel.sharepoint.com/:x:/r' + relative_url + '/' + latest_file_name\n df = loadExcelFile(file_path=latest_file_path, sheet_name='GSE Forecast', header_row=0)\n\n df.drop(['Cycle', 'RDD'], axis=1, errors='ignore', inplace=True) # Remove unused RDD year workweek column\n\n upload_dt = dates[stamp] # convert the stamp [Year].[Work Week].[Day of Work Week] into a real date\n # print('Uploaded on: {}'.format(upload_dt))\n df['ModifiedDateTime'] = upload_dt # append modified date\n\n columns = ['Product', 'Roadmap Segment', 'Module', 'Site', 'Procure By', 'PSIG', 'IPN', 'Supplier Part Number',\n 'Supplier Name', 'Part Description', 'Quantity', 'Supplier ID', 'UOM', 'RDD', 'Subcategory',\n 'ModifiedDateTime']\n\n # # Debugging - uncomment the following line of code if you face an upload error\n # map_columns(table, df, sql_columns=columns)\n\n insert_succeeded, error_msg = uploadDFtoSQL(table=table, data=df, columns=columns, categorical=['Material', 'Supplier Number'], truncate=False, driver=\"{ODBC Driver 17 for SQL Server}\")\n log(insert_succeeded, project_name=project_name, data_area=data_area, row_count=df.shape[0], error_msg=error_msg)\n if insert_succeeded:\n print('Successfully inserted {0} records into {1}'.format(df.shape[0], table))\n ##### END MPE PSI Forecast #####\n\n print(\"--- %s seconds ---\" % (time() - start_time))\n","repo_name":"abhishekagnihotri-dataanalytics/python-intel-work","sub_path":"ATS_SCCI_Procurement.py","file_name":"ATS_SCCI_Procurement.py","file_ext":"py","file_size_in_byte":21396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"18179700079","text":"from tkinter import *\nfrom tkinter import messagebox\n\nroot = Tk()\nroot.title('Sample-start')\nroot.size()\ninput_name = Label(root, text='Enter Number:')\ninput_name.grid(row=0, column=0)\n\nresult = Label(root, text='Result:')\nresult.grid(row=1, column=0)\n\ninput_text_box = Entry(root, width=25, font=25, borderwidth=2)\ninput_text_box.grid(row=0, column=1, columnspan=5, pady=8)\n\nresult_text_box = Entry(root, width=25, font=25, borderwidth=2)\nresult_text_box.grid(row=1, column=1, columnspan=5, pady=2)\n\ninfo_label = Label(root,\n text=\"This calculator will give Prime,Even|Odd,Factorial and Palindrome\", padx=20,\n pady=10).grid(row=2, column=0, columnspan=5)\n\n\n# -----BackUp Code-----\n\n\ndef clear_btn():\n input_text_box.delete(0, END)\n result_text_box.delete(0, END)\n\n\ndef even_odd():\n global num, num1\n num = input_text_box.get()\n result_text_box.delete(0, END)\n try:\n num1 = int(num)\n if num1 % 2 == 0:\n messagebox.showinfo('Result', f'''{num} is odd Number''')\n result_text_box.insert(0, f'''{num} is Even''')\n elif num1 % 2 != 0:\n messagebox.showinfo('Result', f'''{num} is odd Number''')\n result_text_box.insert(0, f'''{num} is odd''')\n else:\n result_text_box.insert(1, \"Enter Valid Number\")\n input_text_box.delete(0, END)\n except ValueError:\n result_text_box.insert(0, f'''Please enter valid number...''')\n\n\ndef fact_btn():\n x = input_text_box.get()\n result_text_box.delete(0, END)\n # global num\n try:\n num = int(x)\n fact = 1\n for i in range(1, num + 1):\n fact = fact * i\n if fact >= 200:\n messagebox.showinfo('Result', f'''Fact of {num} is {fact}''')\n else:\n result_text_box.insert(0, f'''Fact of {num} is {fact}''')\n except ValueError:\n result_text_box.insert(0, f'''Please Enter Valid Number''')\n\n\ndef prime_btn():\n x = input_text_box.get()\n result_text_box.delete(0, END)\n try:\n y = int(x)\n subprime = True\n z = 2\n while z <= y-1:\n if y % z == 0:\n subprime = False\n break\n z = z + 1\n if subprime:\n result_text_box.insert(0, f'''{y} is a prime number''')\n else:\n result_text_box.insert(0, f'''{y} is a not a prime number''')\n input_text_box.delete(0, END)\n except ValueError:\n result_text_box.insert(0, f'''Invalid Number''')\n # for i in range(z, y - 1):\n # if i % 2 == 0:\n # subprime = False\n # break\n\n\ndef palin_btn():\n pick_no = input_text_box.get()\n result_text_box.delete(0, END)\n try:\n pick_num = int(pick_no)\n temp = pick_num\n res = 0\n while pick_num > 0:\n last_num = pick_num % 10\n pick_num = pick_num // 10\n res = (res * 10) + last_num\n\n if res == temp:\n result_text_box.insert(0, f'''{temp} is palindrome number''')\n else:\n result_text_box.insert(0, f'''{temp} is not palindrome number''')\n input_text_box.delete(0, END)\n except ValueError:\n result_text_box.insert(0, f'''Please Enter Valid Number''')\n\n\nprime_button = Button(root, text='Prime', padx=20, pady=10, command=prime_btn)\nEven_odd_button = Button(root, text='Even_odd', padx=8, pady=10, command=even_odd)\nFact_button = Button(root, text='Fact', padx=26, pady=10, command=fact_btn)\npalindrome_button = Button(root, text='Palin', padx=23, pady=10, command=palin_btn)\nclear = Button(root, text='Clear', padx=23, pady=10, command=clear_btn)\n\nprime_button.grid(row=3, column=2)\nEven_odd_button.grid(row=4, column=1)\nclear.grid(row=4, column=2)\nFact_button.grid(row=4, column=3)\npalindrome_button.grid(row=5, column=2)\n\nroot.mainloop()\n","repo_name":"udayreddy026/Tkinter","sub_path":"Task.py","file_name":"Task.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"3263300304","text":"from django.shortcuts import render, get_object_or_404\n\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view,authentication_classes,permission_classes\n\nfrom .serializers import TodoSerializer \n\nfrom .models import Todo, User\n# Create your views here.\n\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication ])\n@permission_classes([IsAuthenticated])\ndef get_todo(request):\n user = request.user\n todos = user.todos.all()\n todosSerializer = TodoSerializer(instance=todos, many=True)\n\n return Response({\n 'todos': todosSerializer.data\n })\n \n\n\n\n\n@api_view(['POST'])\n@authentication_classes([TokenAuthentication ])\n@permission_classes([IsAuthenticated])\ndef create_todo(request):\n if request.method == \"POST\":\n user = request.user\n request.data['user'] = user.id\n todo_serializer = TodoSerializer(data = request.data)\n data = {}\n if todo_serializer.is_valid():\n newtodo = todo_serializer.save(user=user)\n data['id'] = newtodo.id\n data['user'] = newtodo.user.id\n data['title'] = newtodo.title\n data['completed'] = newtodo.completed\n else:\n data = todo_serializer.errors\n return Response(data)\n\n@api_view(['POST'])\n@authentication_classes([TokenAuthentication ])\n@permission_classes([IsAuthenticated]) \ndef update_todo(request,id):\n if request.method == \"POST\":\n user = request.user\n todo = get_object_or_404(Todo,pk=id, user=user)\n request.data['user'] = user.id\n request.data['title'] = todo.title\n todo_serializer = TodoSerializer(instance=todo, data=request.data)\n data = {}\n if(todo_serializer.is_valid()):\n todo_serializer.save()\n data = todo_serializer.data\n else:\n data = todo_serializer.errors\n return Response(data)\n \n\n@api_view(['DELETE'])\n@authentication_classes([TokenAuthentication ])\n@permission_classes([IsAuthenticated]) \ndef delete_todo(request,id):\n user = request.user\n todo = get_object_or_404(Todo, pk=id,user=user)\n if todo:\n todo.delete()\n else:\n return Response({'error':'detail not found'})\n return Response({'response': 'Deleted Successfully'})","repo_name":"twixour/instiapp","sub_path":"todo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"73287274511","text":"# 반복문으로 문제를 해결 할 때\nfrom pprint import pprint\n\narray = []\nn = 7\nfor i in range(n):\n for j in range(i + 1, n):\n for k in range(j + 1, n):\n for l in range(k + 1, n):\n array.append([i, j, k, l])\npprint(array[:5])\n\n\n# 재귀 함수로 문제를 해결 할 때\n\"\"\"\nn: 전체 원소의 수\npicked: 지금까지 고른 원소들의 번호\nto_pick: 더 고를 원소의 수\n\"\"\"\ndef pick(n, picked, toPick):\n # 기저 조건 : 더 고를 원소가 없을 때 배열에 담긴 수를 출력\n if toPick == 0:\n print(picked)\n return\n smallest = 0 if not picked else picked[-1] + 1\n for i in range(smallest, n):\n picked.append(i)\n pick(n, picked, toPick - 1)\n picked.pop(-1)\n\n\npick(7, [], 4)\n\n\n\"\"\"\n1. 반복문으로 문제를 해결 할 때\n > 고르는 숫자의 범위가 4개에서 5개로 변하면 for문을 추가해야 되고, 6개, 7개일 경우에도 계속 for문을 추가해야 됨\n > for문이 중첩된다면 코드는 복잡하고 길어지며, 근본적으로 동적인 코드를 구사하지 못함\n2. 재귀함수로 문제를 해결 할 때\n > 재귀함수를 통해 이러한 문제를 유연하고 간결하게 작성 할 수 있음\n > 위 코드에서는 원소들의 총 개수, 원소들을 담는 배열, 더 진행되야 할 횟수를 고려해야 함\n\"\"\"","repo_name":"CharmingCheol/python-algorithm","sub_path":"구종만 알고리즘 전략/06. 무식하게 풀기/6.2 n개의 원소 중 m개를 고르는 모든 조합을 찾는 알고리즘.py","file_name":"6.2 n개의 원소 중 m개를 고르는 모든 조합을 찾는 알고리즘.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"28725796659","text":"#-*- coding:utf-8 -*-\n\n\"\"\"\nThis file is part of OpenSesame.\n\nOpenSesame is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nOpenSesame is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with OpenSesame. If not, see .\n\"\"\"\n\nfrom libopensesame.py3compat import *\nimport os\nimport subprocess\nimport tempfile\nfrom libopensesame.exceptions import osexception\nfrom libopensesame.oslogging import oslogger\nfrom libqtopensesame.misc.config import cfg\nfrom libqtopensesame.runners import base_runner\nfrom qtpy import QtWidgets\nimport time\n\n\nclass external_runner(base_runner):\n\n\t\"\"\"Runs an experiment using opensesamerun.\"\"\"\n\n\tdef execute(self):\n\n\t\t\"\"\"See base_runner.execute().\"\"\"\n\n\t\t# Temporary file for the standard output and experiment\n\t\tself.stdout = tempfile.mktemp(suffix=u\".stdout\")\n\t\tif self.experiment.experiment_path is None:\n\t\t\treturn osexception(\n\t\t\t\tu'Please save your experiment first, before running it using '\n\t\t\t\tu'opensesamerun'\n\t\t\t)\n\t\tself.path = os.path.join(self.experiment.experiment_path,\n\t\t\t'.opensesamerun-tmp.osexp')\n\t\tself.experiment.save(self.path, True)\n\t\toslogger.debug(u\"experiment saved as '%s'\" % self.path)\n\t\t# Determine the name of the executable. The executable depends on the\n\t\t# platform, package, and Python version.\\\n\t\tif cfg.opensesamerun_exec == u'':\n\t\t\t# Is there a direct executable?\n\t\t\tif os.path.exists(u'opensesamerun.exe'):\n\t\t\t\tself.cmd = [u'opensesamerun.exe']\n\t\t\telif os.path.exists(u'opensesamerun.bat'):\n\t\t\t\tself.cmd = [u'opensesamerun.bat']\n\t\t\telif os.path.exists(u'opensesamerun'):\n\t\t\t\tself.cmd = [u'opensesamerun']\n\t\t\t# Or is there a Python interpreter and a script with a known name?\n\t\t\telif (\n\t\t\t\tos.path.exists(u'python.exe')\n\t\t\t\tand os.path.exists(os.path.join(u'Scripts', u'opensesamerun'))\n\t\t\t):\n\t\t\t\tself.cmd = [\n\t\t\t\t\tu'python.exe',\n\t\t\t\t\tos.path.join(u'Scripts', u'opensesamerun')\n\t\t\t\t]\n\t\t\telif (\n\t\t\t\tos.path.exists(u'python.exe')\n\t\t\t\tand os.path.exists(\n\t\t\t\t\tos.path.join(u'Scripts', u'opensesamerun-script.py')\n\t\t\t\t)\n\t\t\t):\n\t\t\t\tself.cmd = [\n\t\t\t\t\tu'python.exe',\n\t\t\t\t\tos.path.join(u'Scripts', u'opensesamerun-script.py')\n\t\t\t\t]\n\t\t\telse:\n\t\t\t\traise osexception(\n\t\t\t\t\tu'Failed to locate opensesamerun. Try selecting a '\n\t\t\t\t\tu'different runner under Preferences.'\n\t\t\t\t)\n\t\telse:\n\t\t\tself.cmd = cfg.opensesamerun_exec.split()\n\t\tself.cmd += [\n\t\t\tself.path,\n\t\t\tu\"--logfile=%s\" % self.experiment.logfile,\n\t\t\tu\"--subject=%s\" % self.experiment.var.subject_nr\n\t\t]\n\t\tif oslogger.debug_mode:\n\t\t\tself.cmd.append(u\"--debug\")\n\t\tif self.experiment.var.fullscreen == u'yes':\n\t\t\tself.cmd.append(u\"--fullscreen\")\n\t\toslogger.debug(u\"spawning opensesamerun as a separate process\")\n\t\t# Call opensesamerun and wait for the process to complete\n\t\ttry:\n\t\t\tp = subprocess.Popen(self.cmd, stdout=open(self.stdout, u\"w\"))\n\t\texcept Exception as e:\n\t\t\ttry:\n\t\t\t\tos.remove(self.path)\n\t\t\t\tos.remove(self.stdout)\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\treturn osexception(e)\n\t\t# Wait for OpenSesame run to complete, process events in the meantime,\n\t\t# to make sure that the new process is shown (otherwise it will crash\n\t\t# on Windows).\n\t\tretcode = None\n\t\twhile retcode is None:\n\t\t\tretcode = p.poll()\n\t\t\tQtWidgets.QApplication.processEvents()\n\t\t\ttime.sleep(1)\n\t\toslogger.debug(u\"opensesamerun returned %d\" % retcode)\n\t\tprint()\n\t\tprint(open(self.stdout, u\"r\").read())\n\t\tprint()\n\t\t# Clean up the temporary file\n\t\ttry:\n\t\t\tos.remove(self.path)\n\t\t\tos.remove(self.stdout)\n\t\texcept:\n\t\t\tpass\n\t\treturn None\n\n\tdef workspace_globals(self):\n\n\t\treturn {'logfile': self.experiment.logfile}\n","repo_name":"farheenkaifee/Sesam_Software1","sub_path":"libqtopensesame/runners/external_runner.py","file_name":"external_runner.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"10857659956","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom musicians.models import Musician\nfrom labels.models import Label\nfrom bands.models import Band\nfrom musiciansbands.models import MusicianBand\n\n\nclass MusicianToBandTests(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.user = get_user_model().objects.create_user(\n username='testuser1',\n password='testpass123',\n email='testuser1@email.com',\n )\n\n cls.musician = Musician.objects.create(\n name='Musician',\n full_name='John John',\n born='1978-03-18',\n died='1978-03-18',\n place_of_birth='NY, USA',\n bio='info about musician',\n added_by=cls.user\n )\n\n cls.label = Label.objects.create(\n name='2020',\n address='Warsaw',\n country='Poland',\n status=1,\n founding_year=2020,\n added_by=cls.user\n )\n\n cls.band = Band.objects.create(\n name='Band',\n country_of_origin='USA',\n location='Breslau',\n status=1,\n formed_in=2000,\n ended_in=2000,\n lyrical_themes='themes',\n current_label=cls.label,\n bio='bio',\n added_by=cls.user\n )\n\n cls.musiciantoband = MusicianBand.objects.create(\n musician=cls.musician,\n band=cls.band,\n year_from=2000,\n year_to=2000,\n role='guitarist'\n )\n\n def test_add_musician_to_band_view_for_logged_in_user(self):\n self.client.login(email='testuser1@email.com', password='testpass123')\n response = self.client.get(reverse('add_musician_to_band'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Add musician to band')\n self.assertNotContains(response, 'Not contain me')\n self.assertTemplateUsed(response, 'musiciansbands/create_form.html')\n\n def test_add_musician_to_band_view_for_logged_out_user(self):\n self.client.logout()\n response = self.client.get(reverse('add_musician_to_band'))\n self.assertEqual(response.status_code, 302)\n self.assertRedirects(\n response, f'{reverse(\"account_login\")}?next=/musiciantoband/add/'\n )\n response = self.client.get(\n f'{reverse(\"account_login\")}?next=/musiciantoband/add/'\n )\n self.assertContains(response, 'Log In')\n ","repo_name":"panpusto/music_base_v2","sub_path":"musiciansbands/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"83"} +{"seq_id":"35592352615","text":"'''\"\"print('---Desafio 38---')\nnumero1 = int(input('Primeiro valor:\\n->'))\nnumero2 = int(input('Segundo valor:\\n->'))\n\nif numero1 > numero2:\n print(f'O Primeiro valor {numero1} é o maior')\nelif numero1 < numero2:\n print(f'O Segundo valor {numero2} é o maior')\nelse:\n print(f'O dois valores são iguais')\n\"\"'''\ndef comparar_numeros():\n try:\n numero1 = int(input('Digite o primeiro valor: '))\n numero2 = int(input('Digite o segundo valor: '))\n\n if numero1 > numero2:\n resultado = f'O primeiro valor {numero1} é maior.'\n elif numero1 < numero2:\n resultado = f'O segundo valor {numero2} é maior.'\n else:\n resultado = 'Não existe valor maior, os dois são iguais.'\n\n return resultado\n\n except ValueError:\n return 'Erro: Digite números inteiros válidos.'\n except KeyboardInterrupt:\n return 'Programa encerrado pelo usuário.'\n\ndef main():\n print('---Desafio 38 (Avançado)---')\n resultado = comparar_numeros()\n print(resultado)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Caio893/Revisao-do-Exercivios-de-Python","sub_path":"Exercícios de Python/ex038.py","file_name":"ex038.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"48312611944","text":"#Minh-Nhat Do COP1000 Section 2213\n#prompt input of amount of coffee ordered by user\n#assign to variable coffee_ordered\n#assign constants to price of coffee by weight\n#FORTY_LBS, TWENTY_LBS, TEN_LBS, ONE_TO_NINE_LBS\n#assign constants to tax, shipping\n#TAX, SHIPPING\n#calculate price of coffee with elif statements\n#assign cost of coffee to variable, coffee_cost\n#print final sale details\n\n#assigning constants for price of coffee\nFORTY_LBS=7.50\nTWENTY_LBS=8.75\nTEN_LBS=10.00\nONE_TO_NINE_LBS=12.00\n#calculating price of coffee and assign to variable based on amount ordered\ncoffee_ordered=int(input('How many pounds of coffee are you ordering? '))\nif coffee_ordered>=40:\n coffee_cost=coffee_ordered*FORTY_LBS\n print('Cost of cofee: $',format(coffee_cost,'.2f'),sep='')\nelif coffee_ordered>=20:\n coffee_cost=coffee_ordered*TWENTY_LBS\n print('Cost of coffee: $',format(coffee_cost,'.2f'),sep='')\nelif coffee_ordered>=10:\n coffee_cost=coffee_ordered*TEN_LBS\n print('Cost of coffee: $',format(coffee_cost,'.2f'),sep='')\nelse:\n coffee_cost=coffee_ordered*ONE_TO_NINE_LBS\n print('Cost of coffee: $',format(coffee_cost,'.2f'),sep='')\n#assigning constants for tax and shipping\nTAX=0.07\nSHIPPING=1.00\n#calculate and display sales tax for the order\nsales_tax=coffee_cost*TAX\nprint('7% sales tax: $',format(sales_tax,'.2f'),sep='')\n#calculate shipping for the order\nif coffee_cost>150:\n shipping=coffee_ordered*0\n print('Shipping fee: $',format(shipping,'.2f'),sep='')\nelse:\n shipping=coffee_ordered*1\n print('Shipping fee: $',format(shipping,'.2f'),sep='')\n#display final total due\nprint('Total payable: $',format(coffee_cost+sales_tax+shipping,'.2f'))\n\n#Collaborators: None\n","repo_name":"natedo18/cop1000","sub_path":"Scripts/Chapter 3 Prep Assignment.py","file_name":"Chapter 3 Prep Assignment.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"42460637995","text":"from util import *\n\n\n@apply\ndef apply(self):\n ((Q, t), (((V, KT), i), (S[i], S[0], T))), (S[t], S[0], S[T]) = self.of(Lamda[sigmoid[Indexed] * Sum[Indexed[Symbol * Transpose[Softmax]]]])\n return Equal(self, sigmoid(Q) * ReducedSum(softmax(KT) * V.T))\n\n\n@prove\ndef prove(Eq):\n from axiom import algebra\n\n T, d = Symbol(integer=True, positive=True)\n i, t = Symbol(integer=True)\n Q, K, V = Symbol(shape=(T, d), real=True)\n Eq << apply(\n Lamda[t:T](sigmoid(Q[t]) * Sum[i:T](Indexed(softmax(K.T).T * V, i))))\n\n t = Symbol(domain=Range(T))\n Eq << algebra.eq.given.eq.getitem.apply(Eq[0], t)\n\n Eq << Eq[-1].this.lhs.apply(algebra.sum.to.reducedSum)\n\n #https://arxiv.org/pdf/2105.14103.pdf\n\n\nif __name__ == '__main__':\n run()\n# created on 2023-09-15\n","repo_name":"cosmosZhou/axiom","sub_path":"axiom/keras/lamda/softmax/to/reducedSum/softmax/transformer/attention_free.py","file_name":"attention_free.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"83"} +{"seq_id":"72163435791","text":"from pytest import fixture\nfrom selenium import webdriver\n\n\n@fixture(params=['chrome'], scope='class')\ndef init_driver(request):\n web_driver = webdriver.Chrome() if request.param == 'chrome' else webdriver.Firefox()\n request.cls.driver = web_driver\n yield\n web_driver.close()\n","repo_name":"dicarlomtz/books-fe","sub_path":"tests/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"39382586824","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n # Time complexity : O(m+n)\n # Space complexity : O(1)\n dummy = ListNode(0)\n carry = 0\n cur1 = l1\n cur2 = l2\n cur = dummy\n while cur1 and cur2 :\n cur_sum = cur1.val + cur2.val + carry\n value = cur_sum % 10\n carry = cur_sum // 10\n new_node = ListNode(value)\n cur.next = new_node\n cur = cur.next\n cur1 = cur1.next\n cur2 = cur2.next\n while cur1:\n cur_sum = cur1.val + carry\n value = cur_sum % 10\n carry = cur_sum // 10\n new_node = ListNode(value)\n cur.next = new_node\n cur = cur.next\n cur1 = cur1.next\n \n while cur2:\n cur_sum = cur2.val + carry\n value = cur_sum % 10\n carry = cur_sum // 10\n new_node = ListNode(value)\n cur.next = new_node\n cur = cur.next\n cur2 = cur2.next\n \n if carry:\n new_node = ListNode(carry)\n cur.next = new_node\n \n return dummy.next\n\n \n","repo_name":"Maheshdh/DSA","sub_path":"2: Add two numbers.py","file_name":"2: Add two numbers.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"83"} +{"seq_id":"34109479147","text":"from hr_analyzer import HrAnalyzer\nfrom pandas_data_collector import PandasDataCollector\nfrom statistics_renderer import StatisticsRenderer\n\n\ndef main():\n # Data collector collects data using pandas data collector implementation.\n data_collector = PandasDataCollector('archive/HR-Employee-Attrition.csv')\n data_collector.read_data()\n data_collector.print_raw_data()\n\n # Pass a data collector to an analyzer in order for it to load and transform data for further analysis.\n case_analyzer = HrAnalyzer(data_collector)\n case_analyzer.transform_dataset()\n\n # Additional operations to prepare the data for analysis.\n case_analyzer.drop_duplicates()\n\n # Set attributes to analyze.\n attribute_to_analyze_1 = 'Age'\n attribute_to_analyze_2 = 'DailyRate'\n attribute_to_analyze_3 = 'DistanceFromHome'\n attribute_to_analyze_4 = 'YearsAtCompany'\n attributes_to_analyze = [attribute_to_analyze_1, attribute_to_analyze_2,\n attribute_to_analyze_3, attribute_to_analyze_4]\n\n # Specific analyzers can retrieve statistics for specific attributes.\n average_statistics = case_analyzer.get_average_statistics(\n attributes_to_analyze)\n average_statistics.print_statistics_summary()\n\n renderer = StatisticsRenderer('blue', 3)\n\n # Set base analysis criteria.\n average_statistics.set_main_criteria(attribute_to_analyze_1)\n\n # Print base analysis attributes.\n average_statistics.print_statistics_data(attribute_to_analyze_3)\n\n # Specific analysis cases.\n\n age_to_pay_slice = average_statistics.get_statistics(\n attribute_to_analyze_2)\n renderer.draw_plot('Age', 'Average daily rate',\n 'Average daily rate for age', age_to_pay_slice)\n\n age_to_distance = average_statistics.get_statistics(attribute_to_analyze_3)\n renderer.draw_plot('Age', 'Average distance from home',\n 'Average distance from home for age', age_to_distance)\n\n # Switching base analysis criteria.\n\n average_statistics.set_main_criteria(attribute_to_analyze_4)\n\n average_statistics.print_statistics_data(\n attribute_to_analyze_4, ascending=True)\n\n years_to_pay = average_statistics.get_statistics(\n attribute_to_analyze_2, ascending=False)\n renderer.draw_plot('Years at the company', 'Average daily rate',\n 'Relation between years at the company and daily rate', years_to_pay)\n\n total_years_of_work = average_statistics.get_statistics_data_frame()[\n attribute_to_analyze_4].sum()\n print(f'Total years worked: {total_years_of_work}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"LuckyRads/Data-Analysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"1706099701","text":"\"\"\"\nThis program\n1. Randomly roll a pair of dice\n2. Add the values of the roll\n3. Ask the user to guess a number\n4. Compare the user's guess to the total value\n5. Decide a winner (the user or the program)\n6. Inform the user who the winner is\n\"\"\"\nfrom random import randint\nfrom time import sleep\ndef get_user_guess():\n user_guess = int(input(\"Guess the number: \"))\n return user_guess\ndef roll_dice(number_of_sides):\n first_roll = randint(1, number_of_sides)\n second_roll = randint(1, number_of_sides)\n max_val = number_of_sides * 2\n print(\"The maximum possible value is: \" + str(max_val))\n sleep(1)\n user_guess = get_user_guess()\n if user_guess > max_val:\n print(\"Your guess is higher than maxiumum value\")\n return\n else:\n print(\"Rolling\")\n sleep(2)\n print(\"The first value is: %d\" % first_roll)\n sleep(1)\n print(\"The second value is: %d\" % second_roll)\n sleep(1)\n total_roll = first_roll + second_roll\n print(\"Result is: %d\" % total_roll)\n sleep(1)\n if user_guess > total_roll:\n print(\"You are winner!\")\n return\nroll_dice(6)","repo_name":"JanSnobl/NumberGuess","sub_path":"NumberGuess.py","file_name":"NumberGuess.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40209697061","text":"from e3.env import Env\nfrom testsuite_support.builder_and_runner import BuilderAndRunner\n\nbnr = BuilderAndRunner()\n\nif 'windows' in Env().host.platform:\n is_win = True\nelse:\n is_win = False\n\nbnr.build('switches_attribute.gpr', args=['-p'])\n\nbnr.run(['./main'], output=\"run.out\")\n\nfor line in open(\"run.out\"):\n li = line[:-1]\n # Windows has a non case-sensitive filesystem, we add there on\n # attribute to match the linux expected output.\n if is_win and li == 'A: Switches [capital.adb] -> -g -gnata -g0':\n print('A: Switches [Capital.adb] -> -g -gnata')\n print(li)\n","repo_name":"AdaCore/gpr","sub_path":"testsuite/tests/switches-attribute/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"80"} +{"seq_id":"39221851232","text":"#!/usr/bin/env python\n# _\n# | (_)\n# __ _| |_ _ __ ___\n# / _` | | | '_ ` _ \\\n# | (_| | | | | | | | |\n# \\__, |_|_|_| |_| |_|\n# __/ |\n# |___/\n#\n#\n# A modern python framework for the web\n\n__author__ = \"Aras Can Akin\"\n\nfrom . import paths\npaths.configure()\n\nfrom termcolor import colored\n\nfrom glim.app import Glim\nfrom glim.utils import import_module\nfrom glim.command import CommandAdapter\n\nimport glim.commands\n\nimport traceback\nimport argparse\nimport os\nimport sys\n\ndescription = \"glim ~ a modern python framework for the web\"\n\n\ndef main():\n \"\"\"\n The single entry point to glim command line interface.Main method is called\n from pypi console_scripts key or by glim.py on root.This function\n initializes a new app given the glim commands and app commands if app\n exists.\n\n Usage\n -----\n $ python glim/cli.py start\n $ python glim.py start (on root folder)\n \"\"\"\n # register the global parser\n preparser = argparse.ArgumentParser(description=description,\n add_help=False)\n\n preparser.add_argument('--env', '-e', dest='env',\n default='development',\n help='choose application environment')\n\n # parse existing options\n namespace, extra = preparser.parse_known_args()\n env = namespace.env\n\n # register the subparsers\n parser = argparse.ArgumentParser(parents=[preparser],\n description=description,\n add_help=True)\n\n subparsers = parser.add_subparsers(title='commands', help='commands')\n\n # initialize a command adapter with subparsers\n commandadapter = CommandAdapter(subparsers)\n\n # register glim commands\n commandadapter.register(glim.commands)\n\n # register app commands\n appcommands = import_module('app.commands', pass_errors=True)\n commandadapter.register(appcommands)\n\n app = None\n\n if paths.app_exists() is False:\n # check if a new app is being created\n new = True if 'new' in extra else False\n\n if ('help' in extra) or ('--help' in extra) or ('-h' in extra):\n help = True\n else:\n help = False\n\n if help:\n parser.print_help()\n exit()\n else:\n app = make_app(env, commandadapter)\n\n args = parser.parse_args()\n\n command = commandadapter.match(args)\n commandadapter.dispatch(command, app)\n\ndef make_app(env, commandadapter=None):\n \"\"\"\n Function creates an app given environment\n \"\"\"\n mconfig = import_module('app.config.%s' % env, pass_errors=True)\n if mconfig is None and paths.app_exists():\n print(colored('Configuration for \"%s\" environment is not found' % env, 'red'))\n return None\n mstart = import_module('app.start')\n mroutes = import_module('app.routes')\n mcontrollers = import_module('app.controllers')\n before = mstart.before\n\n return Glim(commandadapter, mconfig, mroutes, mcontrollers, env, before)\n\nif __name__ == '__main__':\n main()\n","repo_name":"aacanakin/glim","sub_path":"glim/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"80"} +{"seq_id":"70582600259","text":"import cv2\r\nfrom pyzbar import pyzbar\r\n\r\ndef detect_qr_code():\r\n # Open the video stream from the webcam\r\n cap = cv2.VideoCapture(0)\r\n\r\n while True:\r\n # Read a frame from the video stream\r\n ret, frame = cap.read()\r\n\r\n # Convert the frame to grayscale\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n # Detect and decode QR codes\r\n qr_codes = pyzbar.decode(gray)\r\n\r\n # If QR code is detected, print the decoded information\r\n if qr_codes:\r\n print(\"Decoded Information:\")\r\n for qr_code in qr_codes:\r\n decoded_info = qr_code.data.decode(\"utf-8\")\r\n print(decoded_info)\r\n\r\n # Display the frame\r\n cv2.imshow(\"QR Code Detection\", frame)\r\n\r\n # Exit if 'q' key is pressed\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n # Release the video stream and close windows\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n\r\n# Call the function to detect QR codes from webcam\r\ndetect_qr_code()","repo_name":"MaN-PCKM/python","sub_path":"ReadQR.py","file_name":"ReadQR.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"30173331452","text":"import csv\nimport pprint\nfrom pathlib import Path\nfrom argparse import ArgumentParser\nimport sys\nimport tempfile\n\nfrom slack_handler import slack\n\ntry:\n import pyewf\n import pytsk3\n\n from slack_handler import ewf\nexcept ModuleNotFoundError as e:\n print(\"A module is not installed.\", e, file=sys.stderr)\n sys.exit(1)\n\n\ndef is_fs_directory(f):\n \"\"\"Check if an inode/addr is a filesystem directory.\"\"\"\n\n try:\n return f.info.meta.type == pytsk3.TSK_FS_META_TYPE_DIR\n except AttributeError:\n return False\n\n\ndef is_fs_regfile(f):\n \"\"\"Check if an inode/addr is a regular file.\"\"\"\n\n try:\n return f.info.meta.type == pytsk3.TSK_FS_META_TYPE_REG\n except AttributeError:\n return False\n\n\ndef processing(partition, directory, queue, parent_names):\n \"\"\"Iterate over all files recursively in a all directories and get\n the slack on each file (only regular files and not filesystem metadata\n file).\"\"\"\n\n queue.append(directory)\n\n for f in directory:\n # exclude none directories, current_dir, parent_dir and NTFS system dirs (such as $Extend)\n if f.info.name.name in [b\".\", b\"..\"]:\n continue\n elif f.info.name.name[0:1] == b\"$\":\n continue\n elif is_fs_directory(f):\n if arguments.verbose:\n print(f\"Current dir: {f.info.name.name}\")\n parent_names.append(f.info.name.name.decode(\"UTF-8\"))\n\n d = f.as_directory()\n # no recurse, to avoid circular loops:\n if d not in queue:\n processing(partition, d, queue, parent_names)\n\n elif is_fs_regfile(f):\n if arguments.verbose:\n print(f\"Getting file slack from: {f.info.name.name.decode('UTF-8')}\")\n s = get_slack(partition, f)\n if s is not None:\n s.set_s_dirs(parent_names)\n all_slacks.append(s)\n\n else:\n continue\n\n queue.pop(-1)\n parent_names.pop(-1)\n\n\ndef print_partition_table(partition_table):\n \"\"\"Print the partition table.\"\"\"\n\n print(\"\\naddr, desc, starts(start*512) len\")\n for partition in partition_table:\n # partition.addr : Represents the partition number\n # parition.desc: NTFS (0x07)- Reprents the partition description including the type flag for NTFS\n # partition.start: 128s - Represnts the starting sector of the partition\n # partition.start*512: (65536) - Represents the offset by multiplying the sector number where the partition starts by 512 bytes to calculate the absolute position within the image where the partition begins.\n # partition.len: 1042432 - Represents the length in sectors that makes up this partition. If you where to again multiply this number by 512 you would get 533,725,184 which is 509 MegaBytes (divide 533,725,184 by 1024 once to get kilobytes, twice to get megabytes) and is the size of the partition found within the image.\n # http://www.sleuthkit.org/sleuthkit/docs/api-docs/4.9.0/structTSK__VS__PART__INFO.html\n # FIXME not all time 512 !\n print(\n f\"{partition.addr}, {partition.desc}, {partition.start}s({partition.start*512}) {partition.len}\"\n )\n print()\n\n\ndef get_slack(partition, f):\n \"\"\"Return the file slack space of a single file.\"\"\"\n\n # walk all clusteres allocated by this file as in NTFS filesystem\n # each file has several attributes which can allocate multiple clusters.\n l_block = 0\n for attr in f:\n for run in attr:\n #  https://flatcap.org/linux-ntfs/ntfs/concepts/clusters.html\n # l_block : last block of the file\n l_block = run.addr + run.len - blocksize\n\n # file size (in bytes)\n size = f.info.meta.size\n\n # actual file data in the last block\n l_d_size = size % blocksize\n\n #  multiple just clusters (no slack)\n if l_d_size == 0:\n # TODO a dedicated test case to be added.\n return None\n else:\n # slack space size\n s_size = blocksize - l_d_size\n\n # force reading the slack of the file by providing the FLAG_SLACK\n # print(l_block, s_size, file=sys.stderr)\n data = f.read_random(\n l_block,\n s_size,\n pytsk3.TSK_FS_ATTR_TYPE_DEFAULT,\n -1,\n pytsk3.TSK_FS_FILE_READ_FLAG_SLACK,\n )\n\n # construct a slack object\n s = slack.slack(\n s_size=s_size,\n s_bytes=data,\n s_partition_addr=partition.addr,\n s_name=f.info.name.name,\n )\n return s\n\n\ndef main():\n\n # commands and arguments\n # argparse https://docs.python.org/3/library/argparse.html#module-argparse\n parser = ArgumentParser(description=\"Extract the file slack spaces.\")\n parser.add_argument(\"image\", metavar=\"disk image\", nargs=1, action=\"store\")\n parser.add_argument(\n \"-e\",\n \"--encoding\",\n default=\"\",\n help=\"Display slack space in LATIN-1 or Hex. Supported options 'latin-1', 'hex'.\",\n )\n parser.add_argument(\n \"-t\",\n \"--type\",\n required=True,\n help=\"Type of the disk image. Currently supported options 'raw' and 'ewf'.\",\n )\n parser.add_argument(\n \"-p\",\n \"--pprint\",\n action=\"store_true\",\n help=\"Pretty print all found file slack spaces.\",\n )\n\n # create a temporary dir for slacks\n tmpdir = tempfile.TemporaryDirectory(prefix=\"slacks_\")\n parser.add_argument(\n \"-d\",\n \"--dump\",\n action=\"store\",\n default=tmpdir.name,\n help=\"Dump file slack spaces of each file in raw format to a directory if specified, by default temporary dir.\",\n )\n parser.add_argument(\n \"-c\",\n \"--csv\",\n action=\"store\",\n default=None,\n help=\"Write file slacks information to a CSV file.\",\n )\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n action=\"store_true\",\n default=False,\n help=\"Control the verbosity of the output.\",\n )\n parser.add_argument(\"--version\", action=\"version\", version=\"v0.2.10\")\n\n global arguments\n arguments = parser.parse_args()\n\n global all_slacks\n all_slacks = []\n\n if arguments.image is not None:\n CWD = Path().cwd()\n if not CWD.joinpath(arguments.image[0]).exists():\n print(\n f\"The disk image '{arguments.image[0]}' is not found.\",\n file=sys.stderr,\n )\n sys.exit(1)\n\n # print versions\n print(\"SleuthKit lib version:\", pytsk3.TSK_VERSION_STR)\n print(\"Module pytsk3 version:\", pytsk3.get_version())\n print(\"Module pyewf version:\", pyewf.get_version())\n\n # open image\n if arguments.image is not None:\n if arguments.type == \"raw\":\n img_handler = pytsk3.Img_Info(arguments.image[0])\n elif arguments.type == \"ewf\":\n print(arguments.image)\n ewf_handle = pyewf.handle()\n filenames = pyewf.glob(arguments.image[0])\n ewf_handle.open(filenames)\n img_handler = ewf.ewf_Img_Info(ewf_handle)\n elif arguments.type == \"aff\":\n print(\"Not Supported Yet ! \", file=sys.stderr)\n sys.exit(1)\n elif arguments.type not in [\"raw\", \"ewf\"]:\n print(\"Not Supported Yet ! Only 'raw' and 'ewf'. \", file=sys.stderr)\n sys.exit(1)\n\n # open the image volume for the partitions within it\n try:\n partition_table = pytsk3.Volume_Info(img_handler)\n print_partition_table(partition_table)\n except OSError as e:\n # there is no Volume in the image.\n print(\n \"Maybe there is no Volume in the provided disk image.\\n\",\n e,\n file=sys.stderr,\n )\n else:\n for partition in partition_table:\n if b\"NTFS\" in partition.desc:\n # open the filesystem with offset set to the absolute offset of\n # the beginning of the NTFS partition.\n fs = pytsk3.FS_Info(img_handler, offset=(partition.start * 512))\n\n #  The Cluster Size (blocksize) can be chosen when the volume is formatted.\n global blocksize\n blocksize = fs.info.block_size\n print(\"NTFS Cluster size: \", blocksize, \"in bytes.\")\n\n # get the sector size\n global sector\n sector = fs.info.dev_bsize\n print(\"NTFS Sector size: \", sector, \"in bytes.\\n\")\n # open the directory node for recursiveness and enqueue all\n # directories in image fs from the root dir \"/\"\n queue_all_dirs = []\n directory = fs.open_dir(path=\"/\")\n\n processing(\n partition,\n directory=directory,\n queue=queue_all_dirs,\n parent_names=[\"/\"],\n )\n\n # pretty printing the all_slack files\n if arguments.pprint:\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(all_slacks)\n\n # writing out file slack spaces into seperate files located in 'slacks' directory\n if arguments.dump:\n if arguments.verbose:\n print(f\"{arguments.dump} is the temporary output dir for file slacks.\")\n\n for s in all_slacks:\n CWD = Path().cwd()\n SLACKS_DIR = CWD.joinpath(arguments.dump)\n SLACKS_DIR.mkdir(exist_ok=True)\n file_slack_name = SLACKS_DIR.joinpath(s.get_s_name())\n file_slack_name.write_bytes(s.get_s_bytes())\n\n # print slack bytes with encoding 'latin-1', 'hex'.\n if arguments.encoding is not None:\n for s in all_slacks:\n s_bytes = s.get_s_bytes()\n if arguments.encoding == \"latin-1\":\n print(s_bytes.decode(\"latin-1\"))\n elif arguments.encoding == \"hex\":\n print(s_bytes.hex())\n\n #  handle csv argument\n if arguments.csv is not None:\n csv_filename = arguments.csv\n if arguments.verbose:\n print(f\"Writing CSV report to '{arguments.csv}'.\")\n\n with open(csv_filename, \"w\", newline=\"\") as csvfile:\n fieldnames = [\n \"slack filename\",\n \"slack size\",\n \"partition address\",\n \"MD5\",\n \"SHA1\",\n \"parent dirs\",\n ]\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n writer.writeheader()\n for s in all_slacks:\n writer.writerow(\n {\n \"slack filename\": s.get_s_name(),\n \"slack size\": s.get_s_size(),\n \"partition address\": s.get_s_partition_addr(),\n \"MD5\": s.get_s_md5(),\n \"SHA1\": s.get_s_sha1(),\n \"parent dirs\": s.get_s_dirs(),\n }\n )\n\n tmpdir.cleanup()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Sim4n6/Slack_handler","sub_path":"slack_handler/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":11030,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"80"} +{"seq_id":"26479869992","text":"\"\"\" 46. Permutations\n\nQuestion:\n\n Given a collection of distinct integers, return all possible permutations.\n\n\"\"\"\n\nclass Solution:\n def permute(self, nums):\n result = []\n\n def backtrack(nums, path):\n if not nums:\n result.append(path)\n return\n for i in range(nums):\n backtrack(nums[:i] + nums[i+1:], path + [nums[i]])\n\n backtrack(nums, [])\n return result\n","repo_name":"jiinmoon/Algorithms_Review","sub_path":"Archives/Leet_Code/Old-Attempts/0046_Permutations.py","file_name":"0046_Permutations.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"35301359147","text":"import whisper\nfrom docx import Document\nfrom fpdf import FPDF\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom pyAudioAnalysis import audioSegmentation\n\n# Load model\nmodel = whisper.load_model(\"base\")\n\n# Load audio\naudio = whisper.load_audio(\"audio.mp3\")\naudio = whisper.pad_or_trim(audio) ## trims it to 30 seconds\n\n# Make log-Mel spectrogram and move to the same device as the model\nmel = whisper.log_mel_spectrogram(audio).to(model.device)\n\n# Detect the spoken language\n_, probs = model.detect_language(mel)\nprint(f\"Detected language: {max(probs, key=probs.get)}\")\n\n# Perform speaker diarization\ndef perform_speaker_diarization(audio):\n # Convert audio to mono and resample to 8 kHz\n mono_audio = whisper.to_mono(audio)\n resampled_audio = whisper.resample(mono_audio, 8000)\n\n # Perform speaker diarization using pyAudioAnalysis\n segments = audioSegmentation.speaker_diarization(resampled_audio)\n\n # Retrieve the transcriptions and speaker information\n transcriptions = []\n for segment in segments:\n start_time, end_time, speaker_label = segment\n transcript = whisper.decode(model, mel[:, int(start_time * 100):int(end_time * 100)]).text\n transcriptions.append((speaker_label, transcript))\n\n return transcriptions\n\n# Call the function to perform speaker diarization\ntranscriptions = perform_speaker_diarization(audio) ## replace audio with the audio name file\n\ndocument = Document()\nfor speaker_label, transcript in transcriptions:\n document.add_paragraph(f\"Speaker {speaker_label}: {transcript}\")\n\n# Decode the audio\noptions = whisper.DecodingOptions()\nresult = whisper.decode(model, mel, options)\n\n# Print the recognized text\nprint(result.text)\n\n# Generate transcription file\nfirst_name = input(\"Enter participant's first name: \")\nlast_name = input(\"Enter participant's last name: \")\nweek_number = int(input(\"Enter participant's interview week number: \"))\n\ntranscription_name_word = f\"{first_name}{last_name} Week {week_number}.docx\"\ntranscription_name_pdf = f\"{first_name}{last_name} Week {week_number}.pdf\"\n\n# Save the recognized text to as a Word document\n\ndocument = Document()\ndocument.save(transcription_name_word)\nprint(f\"Transcription saved as {transcription_name_word} Word document.\")\n\n# Save the recognized text to as a PDF document\n\npdf = FPDF()\npdf.add_page()\npdf.set_font(\"Arial\", size=12)\npdf.cell(0, 10, result.text)\npdf.output(pdf_name)\nprint(f\"Transcription saved as {transcription_name_pdf} PDF document.\")\n\n# Upload transcription to Google Drive\n\ngauth = GoogleAuth()\ndrive = GoogleDrive(gauth)\nfile1 = drive.CreateFile({'title': transcription_name_word})\nfile1.SetContentFile(transcription_name_word)\nfile1.Upload()\nprint(f\"Transcription saved to Google Drive as {transcription_name_word}.\")\n\nfile2 = drive.CreateFile({'title': transcription_name_pdf})\nfile2.SetContentFile(transcription_name_pdf)\nfile2.Upload()\nprint(f\"Transcription saved to Google Drive as {transcription_name_pdf}.\")\n","repo_name":"taylorylee/thematic-transcription","sub_path":"transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5412298214","text":"'''\nIt is for loading price in backtest or live mode.\n'''\nimport pandas as pd\nimport sys\nimport os\nsys.path.append(os.path.join(os.getcwd().split('xtraderbacktest')[0],'xtraderbacktest') )\nimport modules.other.sys_conf_loader as sys_conf_loader\nimport modules.other.logg\nimport logging\n\n\n\n'''\nLoad price.\nsymbol = symbol name\nfr = from what time in format %Y-%m-%d %H:%M:%S\nto = from what time in format %Y-%m-%d %H:%M:%S\nmode = live or backtest\n'''\ndef load_ticks(symbol,fr,to):\n result = _load_tick_backtest(symbol,fr,to)\n return result\n\ndef _load_tick_backtest(symbol,fr,to):\n # First construct the cache file name\n # The file name should be in this format XAUUSD_2020-01-02-01-01-00_2020-01-02-02-23-59_price.pickle\n file_name = symbol + '_' + str(fr).replace(':','-').replace(' ','-') + '_' + str(to).replace(':','-').replace(' ','-') + \"_tick.pickle\"\n # Then check whether it is in the cache\n file_path_dir = sys_conf_loader.get_sys_path() + \"/data/__cache__/\"\n # if the __cache__ folder does not exist then create it\n if sys.platform.startswith('linux') == False:\n file_path_dir = file_path_dir.replace('/','\\\\')\n if os.path.isdir(file_path_dir) is False:\n os.mkdir(file_path_dir)\n\n # if the pickle does not exist in folder then create it \n file_path_dir = os.path.join(file_path_dir,\"ticks\")\n if sys.platform.startswith('linux') == False:\n file_path_dir = file_path_dir.replace('/','\\\\')\n if os.path.isdir(file_path_dir) is False:\n os.mkdir(file_path_dir)\n\n # abs location \n abs_path = os.path.join(file_path_dir,file_name) # Here repalce : with - because of naming rule reason\n if sys.platform.startswith('linux') == False:\n abs_path = abs_path.replace('/','\\\\')\n\n result = None\n # if there is cache file then load it locally\n if os.path.isfile(abs_path) is True:\n # read it form local file \n logging.info('Loding file ' + file_name + ' Locally')\n df = pd.read_pickle(abs_path)\n result = df.T.to_dict().values()\n\n else:\n # Otherwise try to load it from remote storage if the plugin is on\n sys_conf = sys_conf_loader.get_sys_conf()\n if(sys_conf[\"backtest_conf\"][\"tick_remote_cache\"][\"is_on\"] == True):\n remote_stroage_type = sys_conf[\"backtest_conf\"][\"tick_remote_cache\"][\"type\"]\n file_path_remote = sys_conf[\"backtest_conf\"][\"tick_remote_cache\"][\"path\"]\n if remote_stroage_type == \"s3\":\n import modules.remote_storage.s3 as s3\n df = s3.dataframe_read(file_name,file_path_remote,abs_path)\n elif remote_stroage_type == \"oss\":\n import modules.remote_storage.oss as oss\n df = oss.dataframe_read(file_name,file_path_remote,abs_path)\n elif remote_stroage_type == \"ftp\":\n import modules.remote_storage.ftp as ftp\n df = ftp.dataframe_read(file_name,file_path_remote,abs_path)\n if df is not None:\n result = df.T.to_dict().values()\n if result is None:\n # if the remote storage does not have the cache then load it from the local price storage.\n result,df = _load_local_tick_storage(symbol,fr,to)\n # Save it to cache\n df.to_pickle(abs_path)\n\n # post it into remote storage\n if(sys_conf[\"backtest_conf\"][\"tick_remote_cache\"][\"is_on\"] == True):\n remote_stroage_type = sys_conf[\"backtest_conf\"][\"tick_remote_cache\"][\"type\"]\n file_path_remote = sys_conf[\"backtest_conf\"][\"tick_remote_cache\"][\"path\"]\n if remote_stroage_type == \"s3\":\n s3.dataframe_write(file_name,file_path_remote,df)\n elif remote_stroage_type == \"oss\":\n oss.dataframe_write(file_name,file_path_remote,df)\n pass\n elif remote_stroage_type == \"ftp\":\n ftp.dataframe_write(file_name,file_path_remote,df)\n pass\n return result\n\ndef _load_local_tick_storage(symbol,fr,to):\n abs_project_path = sys_conf_loader.get_sys_path() \n price_folder = abs_project_path + \"/data/ticks/\"\n abs_location = price_folder + symbol + \".csv\"\n if sys.platform.startswith('linux') == False:\n abs_location = abs_location.replace('/','\\\\')\n df = pd.read_csv(abs_location).fillna(0)\n df[\"date\"] = pd.to_datetime(df[\"date\"])\n df[\"symbol\"] = symbol\n result = df[(df[\"date\"] >= pd.to_datetime(fr)) & (df[\"date\"] <= pd.to_datetime(to))].copy()\n result[\"date\"] = result[\"date\"].dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n result_dict = result.T.to_dict().values()\n return result_dict,result\n\n\nif __name__ == '__main__':\n import modules.other.logg \n import logging\n #print(_load_local_tick_storage(\"AAPL\",\"2019-10-28 09:41:00\",\"2019-10-28 10:03:00\"))\n print(load_ticks(\"AAPL\",\"2019-10-28 09:41:00\",\"2019-10-28 10:03:00\"))\n pass","repo_name":"AlexLJC/xtraderbacktest","sub_path":"modules/price_engine/tick_loader.py","file_name":"tick_loader.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"80"} +{"seq_id":"27888240920","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport asyncio, websockets, pickle\n\nimport seed_handler\nfrom reality import World\n\n# Human eyes operate at 60fps -> 60 perceives/sec * 60 sec/min * 60 min/hour = 216000 perceives/hour\nPERCEIVES_PER_HOUR = 21600 # decreased for performance reasons\n\nclass Memory:\n '''\n Encodes an object with a diminishing salience connected to other memories.\n '''\n def __init__(self, object, salience:float):\n self.object = object\n self.salience = salience\n self.age = 0\n self.base_salience = salience\n self.connections = {}\n \n def connect(self, memory, strength:float) -> None:\n '''\n Connects other Memory to this Memory with a provided strength.\n ---\n memory: other Memory to connect to this Memory\n strength: strength of connection between this Memory and the provided memory\n '''\n if memory not in self.connections:\n self.connections[memory] = 0\n self.connections[memory] += strength\n\n def get_strength(self, memory):\n '''\n Returns the strength of the connection from this Memory to other Memory.\n '''\n return self.connections[memory]\n\n def __str__(self):\n return f'{self.object}'\n\n def __repr__(self):\n return f'{self.object}:{round(self.salience, 4)}'\n \n def __hash__(self):\n return hash(id(self.object))\n\n def __eq__(self, __o: object) -> bool:\n if type(__o) is not Memory:\n return False\n return __o.object is self.object\n\n def decay_function(age:float) -> float:\n '''\n Returns percentage left of memory based on memory age, modeling decay.\n Based on Jiang-Shedd hourly memory decay approximation.\n '''\n age_in_hours = age/PERCEIVES_PER_HOUR\n if age_in_hours < 1:\n return np.e**(-0.7*age_in_hours)\n else:\n return np.e**(-0.7*age_in_hours**(1/6))\n\nclass VisualMemory(Memory):\n def __init__(self, object, salience:float):\n super(object, salience)\n \nclass AudioMemory(Memory):\n def __init__(self, object, salience:float):\n super(object, salience)\n \n\nclass Mind:\n '''\n Holds the memories of a Person and allows them to intelligently function.\n '''\n def __init__(self, capacity:float, att_span:float, stm_thresh:float):\n '''\n capacity: space available for memories in long term memory\n att_span: attention span for focus, float between [0, 1]\n stm_thresh: threshold for a memory to stay in short term memory\n '''\n assert att_span >= 0 and att_span <= 1\n\n self.capacity = capacity\n self.att_span = att_span\n self.stm_thresh = stm_thresh\n self.focus = [None, None] # [object, distance]\n self.ltm = set() # long term memory\n self.stm = set() # short term memory (more salient)\n\n def set_focus(self, perceiving:list, horizon:float):\n '''\n Moves focus based on attention span and distance of percepts from Person\n ---\n perceiving: list of perceived objects in environment with relative distances\n horizon: max perceivable distance from Person\n '''\n # attention span determines whether focus on last object continues\n p = np.random.uniform()\n if p <= self.att_span:\n # focus stays on last object\n for percept in perceiving:\n if percept[0] is self.focus[0]:\n # last object still perceived\n self.focus = percept # object remains same, its distance updates\n return\n # changes focus to something nearby (items farther from horizon more likely)\n reverse_dists = 0\n for percept in perceiving:\n dist = percept[1]\n reverse_dists += horizon - dist\n gaze = np.random.uniform(0, reverse_dists)\n for percept in perceiving:\n reverse_dists -= horizon - percept[1]\n if gaze >= reverse_dists:\n self.focus = percept\n return\n\n def memorize(self, perceiving:list, horizon:float, world):\n '''\n Encode focus into memory, associating surrounding percepts with it\n ---\n perceiving: list of perceived objects in environment with relative distances\n horizon: max perceivable distance from Person\n '''\n memory = self.deep_remember(self.focus[0])\n salience_mutation = abs(np.random.normal(0, 0.5))\n salience = np.e**((horizon/2 - self.focus[1]) * salience_mutation)\n\n if not memory: # focus is not an existing memory\n memory = Memory(self.focus[0], salience)\n else: # focus is an existing memory\n memory.salience += salience\n memory.base_salience = memory.salience # reset the base salience for the decay function\n self.contextualize(memory, perceiving, world)\n self.ltm.add(memory)\n \n def contextualize(self, core_memory:Memory, perceiving:list, world) -> None:\n '''\n Connects Memory with the perceived Memories around it in short term memory\n ---\n core_memory: memory to have perceiving objects' memories connected to\n perceiving: list of perceived objects in environment with relative distances\n '''\n for percept in perceiving:\n memory = self.shallow_remember(percept[0])\n if not memory: # percept not a memory in short term memory\n continue\n if memory is core_memory:\n continue\n dist = world.get_dist_between(core_memory.object, memory.object)\n core_memory.connect(memory, strength=dist)\n\n def move_memories(self) -> None:\n '''\n Decays memories and moves outdated memories to or from short term memory.\n '''\n # decay memories\n for memory in self.ltm:\n memory.age += 1\n memory.salience = memory.base_salience * Memory.decay_function(memory.age)\n # remove insufficiently salient memories from short term memory\n temp = self.stm.copy()\n for memory in self.stm:\n if memory.salience < self.stm_thresh:\n temp.remove(memory)\n self.stm = temp\n # add sufficiently salient memories to short term memory\n for memory in self.ltm:\n if memory.salience >= self.stm_thresh:\n self.stm.add(memory)\n\n def shallow_remember(self, object) -> Memory:\n '''\n Returns memory if the object is a memory in short term memory\n '''\n for memory in self.stm:\n if memory.object is object:\n return memory\n return None\n \n def deep_remember(self, object) -> Memory:\n '''\n Returns memory if the object is a memory in long term memory\n '''\n for memory in self.ltm:\n if memory.object is object:\n return memory\n return None\n \n def get_action(self):\n memory = self.deep_remember(self.focus[0])\n # TODO: How do they decided how to take an action???\n # movement, speaking, doing???\n\n\n def show_network(self, name:str) -> None:\n '''\n Display the long term memory network as a directed graph.\n ---\n name: name of Person\n '''\n edges = []\n edges_labels = {}\n disconnected_nodes = []\n for memory in self.ltm:\n connected = False\n for connection in memory.connections:\n edges.append((memory, connection))\n edges_labels[(memory, connection)] = round(memory.get_strength(connection), 3)\n connected = True\n if not connected:\n disconnected_nodes.append(memory)\n\n G = nx.DiGraph()\n G.add_edges_from(edges)\n G.add_nodes_from(disconnected_nodes)\n saliences = [memory.salience for memory in G.nodes]\n node_multiplier = int('1' + ('0' * (5 - len(str(int(max(saliences)))))))\n node_sizes = [s * node_multiplier for s in saliences] # scales the nodes according to saliences\n pos = nx.spring_layout(G)\n nx.draw_networkx(G, pos, arrows=True, with_labels=True, node_size=node_sizes)\n nx.draw_networkx_edge_labels(G, pos, edge_labels=edges_labels, font_color='red')\n plt.title(f'{name} memory network')\n print(f'\\n{name} memory network contents')\n print(' connections:', edges)\n print(' singletons:', disconnected_nodes)\n plt.show()\n\n\nclass Person:\n '''\n A person perceives objects in its environment, forms memories,\n converses with other Persons.\n '''\n counter = 0\n names = ['grant', 'ethan', 'jennifer', 'brent', 'braun', 'kevin', 'claudia', 'brian', 'dane', 'hunter', 'clinton', 'ashley']\n def __init__(self, parent=None):\n '''\n Constructs mind of Person and sets biophysiological facts.\n ---\n parent: the Person(s) passing traits to this Person\n '''\n seed = seed_handler.load_seed()\n np.random.seed(seed)\n\n self.alive = True\n self.age = 0\n self.perceiving = [] # objects Person perceives\n self.horizon = 3 # distance Person can see\n self.name = Person.names[Person.counter]\n Person.counter += 1\n\n # construct mind\n capacity = np.random.normal(10, 2)\n att_span = np.random.normal(0.5, 0.2)\n stm_thresh = abs(np.random.normal(1, 0.25))\n if parent:\n capacity_mutation = np.random.normal(0, 1)\n att_span_mutation = np.random.normal(0, 0.05)\n stm_thresh_mutation = np.random.normal(0, 0.05)\n capacity = parent.mind.capacity + capacity_mutation\n att_span = parent.mind.att_span + att_span_mutation\n stm_thresh = parent.mind.stm_threh + stm_thresh_mutation\n if att_span > 1: att_span = 1\n elif att_span < 0: att_span = 0\n self.mind = Mind(capacity, att_span, stm_thresh)\n\n self.mouth = Mouth()\n \n seed_handler.save_seed(seed+1)\n \n def perceive(self, world:World) -> None:\n self.perceiving = world.get_nearby_from_object(self, self.horizon)\n self.mind.set_focus(self.perceiving, self.horizon)\n self.mind.memorize(self.perceiving, self.horizon, world)\n self.mind.move_memories()\n self.age += 1\n \n def act(self, world:World) -> None:\n # self.mind.get_action()\n self.speak(world)\n\n def speak(self, world:World) -> None:\n '''\n Person sometimes speaks from memory, other times speaks randomly.\n '''\n # random speech, params by rohan\n seed = seed_handler.load_seed()\n np.random.seed(seed)\n sound = self.mouth.speak(tongue={\"index\": np.random.uniform(0,35), \"diameter\": np.random.uniform(0,6)},\n constriction={\"index\": np.random.uniform(2,50), \"diameter\": np.random.uniform(-1,4)},\n timeout=np.random.uniform(0.2,3),\n intensity=np.random.uniform(0.3,1),\n tenseness=np.random.uniform(0,1),\n frequency=np.random.uniform(20,1000))\n\n world.attribute_sound(self, sound)\n\n seed_handler.save_seed(seed+1)\n \n \n def show_network(self) -> None:\n self.mind.show_network(self.name)\n \n def stats(self, world:World):\n print(self)\n print(f' age: {self.age}')\n print(f' coords: {world.get_coords(self)}')\n print(f' horizon: {self.horizon}')\n print(f' capacity: {self.mind.capacity}')\n print(f' attention span: {self.mind.att_span}')\n print(f' focus: {self.mind.focus}')\n print(f' perceiving: {self.perceiving}')\n\n def __str__(self):\n return self.name\n def __repr__(self):\n return str(self)\n\nclass Sound:\n def __init__(self, directory:str, properties:tuple) -> None:\n '''\n filename: wave file path\n properties: settings\n '''\n self.directory = directory\n self.name = directory.split('/')[1]\n self.properties = properties\n self.volume = properties[3] # intensity used as volume for now\n # get sound wave from pickle\n with (open(f'{directory}/{self.name}.pickle', 'rb')) as openfile:\n self.wave = np.asarray(pickle.load(openfile))\n \n def __str__(self):\n return 's:' + self.name[:8]\n def __repr__(self):\n return str(self)\n \n def compare(sound1:object, sound2:object) -> None:\n # This looks like an ideal application for the cross correlation function, \n # which will show the correlation between the two waveforms for every time offset between the two. \n # This is done by first removing the mean from each waveform, \n # and then multiplying the two resulting zero-mean waveforms together element by element and summing the result, \n # repeating for each possible sample shift between the waveforms. \n # These results can be scaled by the product of the standard deviation of the two waveforms, \n # which would normalize the result similar to what is done in the Pearson correlation coefficient.\n pass\n\nclass Mouth:\n '''\n Capable of holding all parameters of a phone.\n '''\n def __init__(self):\n self.tongue = {\"index\": 0, \"diameter\": 0}\n self.constriction = {\"index\": 0, \"diameter\": 0}\n self.timeout = 0\n self.intensity = 0\n self.tenseness = 0\n self.frequency = 0\n self.duration = 1\n\n def speak(self, tongue:float, constriction:float, timeout:float, \n intensity:float, tenseness:float, frequency:float, human_audible:bool=False) -> Sound:\n '''\n Prepares the mouth to speak with provided parameters and returns file of sound location.\n ---\n human_audible: plays sound if True\n '''\n self.tongue = tongue\n self.constriction = constriction\n self.timeout = timeout\n self.intensity = intensity\n self.tenseness = tenseness\n self.frequency = frequency\n\n async def send_socket(mouth: Mouth):\n async with websockets.connect(\"ws://localhost:5678\") as websocket:\n await websocket.send(f\"M:{mouth}\")\n new_message = await websocket.recv()\n if new_message[0:2] != 'F:':\n new_sound = await websocket.recv()\n print(new_sound[2:])\n return Sound(new_sound[2:], (self.tongue, \n self.constriction, self.timeout, \n self.intensity, self.tenseness,\n self.frequency, self.duration)\n )\n\n loop = asyncio.get_event_loop()\n coroutine = send_socket(self)\n sound = loop.run_until_complete(coroutine)\n return sound\n\n def __str__(self):\n return f'{self.tongue[\"index\"]}|{self.tongue[\"diameter\"]}| \\\n {self.constriction[\"index\"]}|{self.constriction[\"diameter\"]}|\\\n {self.duration}|{self.timeout}|{self.intensity}|\\\n {self.tenseness}|{self.frequency}'\n\n\n# dist = abs(np.random.normal(0, 0.5, size=100))\n# plt.hist(dist)\n# plt.show()","repo_name":"eshedd/petri-language","sub_path":"v2/anthrop.py","file_name":"anthrop.py","file_ext":"py","file_size_in_byte":15408,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"31861244577","text":"import math\r\n#strings, int and float are immutable ie. \r\nstring1 = \"Fridah Cheboi\"\r\nprint(string1.__len__())\r\n# What did you say classes are?\r\n# I have learnt something really interesting today\r\nprint(string1.index(\"F\")) #gives value error when character is not found\r\nprint(string1.find(\"K\")) #returns value error when character in not found\r\nprint(string1[1])\r\nprint(string1[0:5])#Slicing does not include the end index\r\nstring2 = string1.replace(\"F\",\"B\")\r\nnumber1 = 10\r\nfloat1 = 0.1\r\nbool = True \r\nbool2 = False \r\n\r\n#lists are immutable ie. values can be changed on the same variable\r\nlist1 = [1,2,3,4,5]\r\nme = [\"Brilliant\",\"Blessed\",\"Brave\",\"Breaking even\"]\r\nprint(me[0:2])\r\nme.append(\"Great\")\r\nme.extend([\"Awesome\",\"Best of all time!!!\"])\r\nprint(me)\r\nlist1.insert(0, \"There's me\")\r\nprint(list1)\r\n#dictionaries\r\nmap1 = {\"a\":\"Zero\", \"b\":\"One\", \"c\":\"Two\", \"d\":\"Three\"}\r\nprint(map1[\"a\"])\r\n\r\n#A tuple is immutable\r\ntuple1 = (1,2,3,4,5,6)\r\n\r\n#type conversion\r\nentry = int(input(\"Please enter number\"))\r\nprint(entry + 5)\r\n\r\n#Order of operations\r\n#Division: To find the total number 0f hours, minutes and seconds in 50000 seconds\r\nnum = 50000\r\nhours = num//3600\r\nrem = num%3600\r\nminutes = rem// 360\r\nseconds = rem%360\r\nprint(hours, minutes, seconds)\r\n#Decision making: if, elif, else \r\n","repo_name":"FRIDAHCHEBOI01/TestCrash","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"1252915395","text":"import discord\r\nfrom Commands.CommandHandler import CommandDeclaration, CommandHandler\r\nfrom SelfMusicBot import SelfMusicBot\r\n\r\n@CommandDeclaration(\"remove\", CommandHandler(\"Removes a song from the queue\"))\r\nasync def cmd_remove(instance : SelfMusicBot, \r\n message : discord.message.Message, \r\n channel : discord.channel.TextChannel, \r\n guild : discord.guild.Guild,\r\n args : list[str]):\r\n if len(args) < 1 or not args[0].isdigit():\r\n await message.reply(\":information_source: remove \")\r\n return\r\n\r\n song_number = int(args[0])\r\n if song_number < 0 or song_number > (len(instance.music_queue) - 1):\r\n await message.reply(f\":x: Song with the number {song_number} is not in the queue range\")\r\n return\r\n \r\n del instance.music_queue[song_number]\r\n await message.add_reaction(\"✅\")","repo_name":"vlOd2/SelfMusicBot","sub_path":"Commands/Remove.py","file_name":"Remove.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"24617895030","text":"class Perceptron:\n\n def __init__(self):\n self.salida = 0\n self.pesos = []\n self.entradas = []\n self.error = []\n self.correccion = 0\n self.valor_esperado = 0\n self.umbral = 0.0\n self.tasa_aprendizaje = 0.1\n\n def preguntar(self, pregunta):\n self.pensarPerceptron(pregunta)\n print('la salida para ',pregunta, ' es ', self.salida)\n return self.salida\n\n def pensarPerceptron(self, entradas):\n print('pensando..')\n if self.productoEscalar(entradas, self.pesos) > self.umbral:\n self.salida = 1\n else:\n self.salida = 0\n\n def setUmbral(self,umbral):\n self.umbral = umbral\n \n def setTasaAprendizaje(self, tasa_aprendizaje):\n self.tasa_aprendizaje = tasa_aprendizaje\n \n def setEntradas(self, entradas, valor_esperado):\n n = len(entradas)\n self.entradas = entradas\n self.valor_esperado = valor_esperado\n self.error.clear()\n self.pesos.clear()\n #self.umbral = self.valor_esperado\n for x in range(n):\n self.pesos.append(0)\n self.error.append(0)\n #self.entrenar()\n\n def productoEscalar(self, entradas, pesos):\n res = 0\n for x, w in zip(self.entradas, self.pesos):\n res += x * w\n print('producto escalar ', res)\n return res\n \n def entrenar(self):\n interaciones = 0\n top = 20\n\n while True:\n #if self.productoEscalar(self.entradas, self.pesos) > self.umbral:\n # self.salida = 1\n #else:\n # self.salida = 0\n self.pensarPerceptron(self.entradas)\n print('comparando salida ', self.salida, ' con valor esperado ', self.valor_esperado)\n if self.salida != self.valor_esperado:\n print('no son iguales...')\n self.error = self.valor_esperado - self.salida\n self.correccion = self.tasa_aprendizaje * self.error\n print('error ', self.error, ' correccion ', self.correccion)\n i = 0\n print('calculando nuevos pesos...')\n for d in self.entradas: \n w = 0\n w = (d * self.correccion) + self.pesos[0]\n print('valor del peso ', w)\n self.pesos[i] = w\n else:\n print('Entrenado con ', interaciones, ' interacciones, pesos finales:')\n print(self.pesos)\n break\n \n interaciones += 1\n if interaciones > top:\n top += top\n print('se han realizado ', interaciones, ' interacciones desea salir pres x')\n r = input()\n if r == 'x':\n print('valores de entrada')\n print(self.entradas)\n print('valor esperado')\n print(self.valor_esperado)\n print('ultima salida del Perceptron')\n print(self.salida)\n print('ultima tabla de pesos')\n print(self.pesos)\n break\n \n \n\n \n\n\n\n","repo_name":"milojarez/laboratorios","sub_path":"perceptronv0.py","file_name":"perceptronv0.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"22817827726","text":"import PySimpleGUI as sg\n\n# Criar as janelas e estilos(layout)\n\n\ndef janela_login():\n sg.theme('Reddit')\n layout = [\n [sg.Text('Digite seu nome:')],\n [sg.Input()],\n [sg.Button('Continuar')]\n ]\n return sg.Window('Login', layout=layout, finalize=True)\n\n\ndef janela_endereco():\n sg.theme('Reddit')\n layout = [\n [sg.Text('Digite seu endereço:')],\n [sg.Input()],\n [sg.Button('Retornar'), sg.Button('Continuar')],\n ]\n return sg.Window('Endereço', layout=layout, finalize=True)\n\n\ndef janela_pedido():\n sg.theme('Reddit')\n layout = [\n [sg.Text('Faça seu pedido:')],\n [sg.Checkbox('Pizza de Peperone', key='pizza1'), sg.Checkbox(\n 'Pizza de Frango c/ Catupiry', key='pizza2')],\n [sg.Button('Retornar'), sg.Button('Fazer pedido')],\n ]\n return sg.Window('Montar Pedido', layout=layout, finalize=True)\n\n\n# Criar as janelas iniciais\n\njanela1, janela2, janela3 = janela_login(), None, None\n\n# Criar um loop de leitura de eventos\nwhile True:\n\n window, event, values = sg.read_all_windows()\n\n # Fechar janela\n\n if window == janela1 and event == sg.WIN_CLOSED:\n break\n if window == janela2 and event == sg.WIN_CLOSED:\n break\n if window == janela3 and event == sg.WIN_CLOSED:\n break\n # Ir para a próxima janela\n\n if window == janela1 and event == 'Continuar':\n janela2 = janela_endereco()\n janela1.hide()\n\n elif window == janela2 and event == 'Continuar':\n janela3 = janela_pedido()\n janela2.hide()\n\n # Voltar a janela anterior\n\n if window == janela3 and event == 'Retornar':\n janela3.hide()\n janela2.un_hide()\n elif window == janela2 and event == 'Retornar':\n janela2.hide()\n janela1.un_hide()\n\n# Lógicas de o que deve acontecer ao clicar nos botões\n\n if window == janela3 and event == 'Fazer pedido':\n if values['pizza1'] == True and values['pizza2'] == True:\n sg.popup(\n 'Foram solicitados uma Pizza de Peperone e uma Pizza de Frango c/ Catupiry')\n elif values['pizza1'] == True:\n sg.popup('Foi solicitado uma Pizza de Peperone')\n elif values['pizza2'] == True:\n sg.popup('Foi solicitado uma Pizza de Frango c/ Catupiry')\n","repo_name":"MarcosLenilson/PROJETOS-EM-PYTHON","sub_path":"Sistema Pizzaria/pedido.py","file_name":"pedido.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"19442025590","text":"\nimport numpy as np\nfrom numba import jit\nfrom PIL import Image\n\n# numba makes first convert slow but all others faster\n\n@jit(nopython=True)\ndef convertpixeltograyscale(array, x, y):\n\tpixelval = np.sum(array[y, x, 0:3])/3\n\t# print(np.array([pixelval, pixelval, pixelval, array[y, x, 3]]))\n\treturn np.array([pixelval, pixelval, pixelval, 255])\n\n@jit(nopython=True)\ndef adjustcolor(array, x, y, coloradjustment):\n\treturn np.add(array[y, x], coloradjustment)\n\ndef getthumbnail(imgarray):\n\tthumb = Image.fromarray(imgarray)\n\tthumb.thumbnail((64, thumb.height * (64/thumb.width)),Image.Resampling.LANCZOS)\n\tthumbarray = np.array(thumb)\n\treturn thumbarray\n\n\n@jit(nopython=True)\ndef converttograyscale(array):\n\tgrayscalearray = np.zeros((array.shape[0], array.shape[1], 4))\n\n # loop over each pixel in the original image\n # and store the calculated pixel in the new array\n\tfor y in range(len(array)):\n\t\tfor x in range(len(array[0])):\n\t\t\tgrayscalearray[y, x] = convertpixeltograyscale(array, x, y)\n\n\tgrayscalearray = grayscalearray.astype('uint8')\n\n\treturn grayscalearray\n\n@jit(nopython=True)\ndef shiftcolor(array, coloradjustment):\n\tshiftcolorarray = np.zeros(array.shape)\n\n # loop over each pixel in the original image\n # and store the calculated pixel in the new array\n\tfor y in range(len(array)):\n\t\tfor x in range(len(array[0])):\n\t\t\tshiftcolorarray[y, x] = adjustcolor(array, x, y, coloradjustment)\n\n\tshiftcolorarray = shiftcolorarray.astype('uint8')\n\n\treturn shiftcolorarray\n","repo_name":"alexcoder04/image-edit","sub_path":"imedit/backend/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"8892951091","text":"from datetime import datetime, timedelta\nfrom data import db_utils as db\n\nclass Reminder:\n \n def __init__(self) -> None:\n self.reminder_id = \"\"\n self.user_id = \"\"\n self.reminder = \"\"\n self.reminder_message = \"\"\n self.target_id = \"\"\n self.db = db.Database()\n \n \n def _reminder_init(self, reminder, user_id, reminder_id, reminder_message, target_id):\n self.reminder_id = reminder_id\n self.user_id = user_id\n self.reminder = reminder\n self.reminder_message = reminder_message\n self.target_id = target_id\n \n \n def get_datetime(self,raw_time):\n \"\"\"Get the datetime from the raw time (h, m, d and hh:mm)\n\n Args:\n raw_time (str): the raw time eg: 1h 2m 3d 12:19\n\n Returns:\n tuple/bool: tuple with final_date and output_msg if the time is valid, bool if the time is invalid\n \"\"\"\n \n current_datetime = datetime.now()\n output_msg = \"\"\n print(\"Time:\" + raw_time)\n if \"d\" in raw_time:\n time = raw_time.replace(\"d\", \"\")\n final_date = current_datetime + timedelta(days=float(time))\n output_msg = f\"Set the reminder for {time} days?\"\n elif \"h\" in raw_time:\n time = raw_time.replace(\"h\", \"\")\n final_date = current_datetime + timedelta(hours=float(time))\n output_msg = f\"Set the reminder for {time} hours?\"\n elif \"m\" in raw_time:\n time = raw_time.replace(\"m\", \"\")\n final_date = current_datetime + timedelta(minutes=float(time))\n output_msg = \"Set the reminder for {time} minutes?\"\n elif \":\" in raw_time:\n time = raw_time.split(\":\")\n if int(time[0]) <= datetime.now().hour & int(time[1]) < datetime.now().minute:\n final_date = current_datetime.replace(days=1,hour=int(time[0]), minute=int(time[1]), second=0, microsecond=0)\n output_msg = f\"Set the reminder for tommorrow at {time[0]}hour and {time[1]}minute?\"\n else:\n final_date = current_datetime.replace(hour=int(time[0]), minute=int(time[1]), second=0, microsecond=0)\n output_msg = f\"Set the reminder for today at {time[0]} hour and {time[1]} minutes?\"\n else:\n return False\n return final_date, output_msg\n \n \n\n def datetime_to_str(self,datetime):\n \"\"\"Convert a datetime to a string\n\n Args:\n datetime (datetime): the datetime\n\n Returns:\n str: the string datetime\n \"\"\"\n return datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n \n def str_to_datetime(self,string_date):\n \"\"\"Convert a string to a datetime\n\n Args:\n datetime (str): the string datetime\n\n Returns:\n datetime: the datetime\n \"\"\"\n return datetime.strptime(string_date, \"%Y-%m-%d %H:%M:%S\")\n\n \n def add(self):\n \"\"\"Add the reminder to the database\n \"\"\"\n self.db.add(self.reminder_id, self.user_id, self.reminder, self.reminder_message, self.target_id)\n \n \n def gen_id(self):\n \"\"\"Generate a random id with utcnow\n\n Returns:\n str: The id\n \"\"\"\n return datetime.utcnow().strftime(\"%Y%m%d%H%M%S\")\n ","repo_name":"officialbishowb/reminder_bot","sub_path":"model/reminder_utils.py","file_name":"reminder_utils.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"25601767722","text":"from iap.common.repository import exceptions as ex\n\n\ndef data_aggr_processor(proc_data):\n aggr = DataAggregate(proc_data, dates_souce='weekly', \n dates_target='monthly')\n\n\nclass DataAggregate:\n dates_source = ''\n dates_target = ''\n\n def __init__(self, data, sum_rules, map_rules, **kwargs):\n '''\n Args: \n - data (obligatory)\n - source dates type(dates_source): daily, weekly, monthly, etc.\n - target dates type(dates_target): weekly, monthly, year, etc.\n '''\n if data is None:\n raise ex.EmptyInputsError('No data to work with')\n self.data = data\n self.sum_rules = sum_rules\n self.map_rules = map_rules\n for key, val in kwargs.items():\n if key == 'dates_source':\n self.dates_source = val\n if key == 'dates_target':\n self.dates_target = val\n self.sum_func_map = {'average': self.__average_sum,\n 'sum': self.__simple_sum}\n\n @staticmethod\n def meta_map_by_rules(data, map_rules):\n for row in data:\n for rule in map_rules:\n # Looking for rules match\n is_matched = True\n for meta_name, val in rule['in'].items():\n if row['meta'][meta_name] != val:\n is_matched = False\n break\n if is_matched:\n # Write updated info\n for meta_name, val in rule['out'].items():\n row['meta'][meta_name] = val\n return data\n\n def sum_by_meta(self):\n new_output = []\n new_row = self.data_sum_by_rules(\n [self.data[1], self.data[2], self.data[3]], self.sum_rules)\n new_output.append({'meta': self.data[1]['meta'],\n 'dates': self.data[1]['dates'], 'data': new_row})\n return new_output\n\n def data_sum_by_rules(self, data_rows, sum_rules):\n output = {}\n # Read data col names\n for col_name, value in data_rows[0]['data'].items():\n col_found = False\n # All data rows must have rules for sum\n for rule_item in sum_rules:\n if rule_item['Name'].lower() == col_name.lower():\n rule_name = rule_item['FactScale'].lower()\n col_found = True\n if rule_name in self.sum_func_map:\n sum_method = self.sum_func_map[rule_name]\n else:\n raise ex.EmptyInputsError('No function match to the\\\n sum method')\n break\n if not col_found:\n raise ex.EmptyInputsError('No sum rule fot the data column ' \n + str(col_name))\n # sum all rows that has col_name\n sum_data = []\n for row in data_rows:\n data_value = row['data'][col_name]\n sum_data.append(data_value)\n result = sum_method(sum_data)\n output[col_name] = result\n return output\n\n def __average_sum(self, sum_data):\n '''\n sum_data - list of numeric data\n if val is string - return 'N/A' as sum result\n '''\n sum = 0.0\n counter = 0\n for val in sum_data:\n if type(val) is str:\n return 'N/A'\n counter = counter + 1\n sum = sum + val\n if sum == 0 or counter == 0:\n result = 0\n else:\n result = sum/counter\n return result\n\n def __simple_sum(self, sum_data):\n '''\n sum_data - list of numeric data\n if val is string - return 'N/A' as sum result\n '''\n sum = 0.0\n for val in sum_data:\n if type(val) is str:\n return 'N/A'\n sum = sum + val\n return sum\n","repo_name":"4iStanUSer/_dev","sub_path":"iap/data_loading/loading_lib/jj_aggr_map.py","file_name":"jj_aggr_map.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"72310889858","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport pytest\n\nfrom tests.helpers import get_package\n\n\nif TYPE_CHECKING:\n from poetry.poetry import Poetry\n from tests.helpers import TestRepository\n from tests.types import CommandTesterFactory\n from tests.types import FixtureDirGetter\n from tests.types import ProjectFactory\n\n\n@pytest.fixture\ndef poetry_with_outdated_lockfile(\n project_factory: ProjectFactory, fixture_dir: FixtureDirGetter\n) -> Poetry:\n source = fixture_dir(\"outdated_lock\")\n\n return project_factory(\n name=\"foobar\",\n pyproject_content=(source / \"pyproject.toml\").read_text(encoding=\"utf-8\"),\n poetry_lock_content=(source / \"poetry.lock\").read_text(encoding=\"utf-8\"),\n )\n\n\n@pytest.mark.parametrize(\n \"command\",\n [\n \"--dry-run\",\n \"docker --dry-run\",\n ],\n)\ndef test_update_with_dry_run_keep_files_intact(\n command: str,\n poetry_with_outdated_lockfile: Poetry,\n repo: TestRepository,\n command_tester_factory: CommandTesterFactory,\n) -> None:\n tester = command_tester_factory(\"update\", poetry=poetry_with_outdated_lockfile)\n\n original_pyproject_content = poetry_with_outdated_lockfile.file.read()\n original_lockfile_content = poetry_with_outdated_lockfile._locker.lock_data\n\n repo.add_package(get_package(\"docker\", \"4.3.0\"))\n repo.add_package(get_package(\"docker\", \"4.3.1\"))\n\n tester.execute(command)\n\n assert poetry_with_outdated_lockfile.file.read() == original_pyproject_content\n assert poetry_with_outdated_lockfile._locker.lock_data == original_lockfile_content\n\n\n@pytest.mark.parametrize(\n (\"command\", \"expected\"),\n [\n (\"\", True),\n (\"--dry-run\", True),\n (\"--lock\", False),\n ],\n)\ndef test_update_prints_operations(\n command: str,\n expected: bool,\n poetry_with_outdated_lockfile: Poetry,\n repo: TestRepository,\n command_tester_factory: CommandTesterFactory,\n) -> None:\n tester = command_tester_factory(\"update\", poetry=poetry_with_outdated_lockfile)\n\n repo.add_package(get_package(\"docker\", \"4.3.0\"))\n repo.add_package(get_package(\"docker\", \"4.3.1\"))\n\n tester.execute(command)\n output = tester.io.fetch_output()\n\n assert (\"Package operations:\" in output) is expected\n assert (\"Installing docker (4.3.1)\" in output) is expected\n","repo_name":"python-poetry/poetry","sub_path":"tests/console/commands/test_update.py","file_name":"test_update.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":27476,"dataset":"github-code","pt":"80"} +{"seq_id":"17080571338","text":"from fastV2 import FlappyGame\nfrom random import random\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport gym\nimport cv2\nfrom QNetwork import Agent\n\nif __name__ == \"__main__\":\n tf.compat.v1.disable_eager_execution()\n env = FlappyGame()\n lr = 0.7\n n_games = 25000\n agent = Agent(gamma=0.9, epsilon=1.0, lr=lr, input_dims=(4,), action_dim=2, mem_size=1000000, batch_size=1024,\n epsilon_end=0.01, epsilon_dec=1e-5)\n agent.epsilon = 0.2\n # if (os.path.exists(agent.model_file)):\n # agent.load_model()\n # agent.epsilon = 0.2\n # agent.eps_min = 0.01\n # print (\"Loaded model from \", agent.model_file)\n\n # Initialize scores and epsilon history\n scores = []\n eps_hist = []\n for i in range(n_games):\n done = False\n observation = env.reset()\n total_reward = 0\n while not done:\n action = agent.choose_action(observation)\n observation_, reward, done, time, score = env.step(action)\n total_reward += reward\n agent.store_transition(observation, action, reward, observation_, done)\n observation = observation_\n \n agent.updateQ()\n eps_hist.append(agent.epsilon)\n scores.append(env.score)\n\n avg_score = np.mean(scores[-100:])\n max_score = np.max(scores[-100:])\n if (i % 100 == 0):\n print ('episode: ', i, '| score %.2f' % env.score, \n '| average score %.2f' % avg_score,\n '| reward for episode: ', total_reward,\n '| epsilon %.2f' % agent.epsilon,\n '| mem_cntr', agent.mem_cntr,\n '| max_score', max_score)\n \n # print (\"Saving model to'\", agent.model_file, \"'. Please wait...\")\n agent.save()\n print (\"Saved Models\")\n # plt.title(\"Cost vs Batches\")\n # plt.show()\n\n \n\n","repo_name":"sriharivishnu/FlappyBird-RL","sub_path":"WIP/mainV2.py","file_name":"mainV2.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"4582193804","text":"# Napisz program, który do pliku o nazwie data.csv zapisze następującą listę list:\n# [[10,'a1', 1], [12,'a2', 3], [14, 'a3', 5], [16, 'a4', 7], [18, 'a5', 9]]\n\nimport csv\nlista_list = [[10,'a1', 1], [12,'a2', 3], [14, 'a3', 5], [16, 'a4', 7], [18, 'a5', 9]]\ndata = open('data.csv','a',newline='')\noutputWriter = csv.writer(data)\nfor lista in lista_list:\n outputWriter.writerow(lista) \n\ndata.close()","repo_name":"nowak-j/python-first-exercises","sub_path":"zapis-listy-list-do-csv.py","file_name":"zapis-listy-list-do-csv.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"71034036100","text":"from mayavi import mlab\nimport numpy as np\n\nlines = [[0, 2, 3, 4, 0, 1, 6, 7, 8, 1, 10, 11, 12, 1, 14, 15, 16, 1, 18, 19, 20],\n [2, 3, 4, 5, 1, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]]\n\ndef plot_hand_pose(pose_xyz, filename):\n # Create a mayavi window\n #mlab.close(2)\n mlab.figure(2,size=(600,600))\n mlab.clf()\n\n # draw hand joints\n mlab.points3d(pose_xyz[:, 0], pose_xyz[:, 1], pose_xyz[:, 2], scale_factor=0.04, color=(0, 0, 1), mode='sphere',\n opacity=1)\n # draw bones\n for i in range(len(lines[0])):\n x = lines[0][i]\n y = lines[1][i]\n mlab.plot3d([pose_xyz[x, 0], pose_xyz[y, 0]], [pose_xyz[x, 1], pose_xyz[y, 1]],\n [pose_xyz[x, 2], pose_xyz[y, 2]], line_width=1.0, color=(1, 0, 0), tube_radius=0.008)\n\n # Export the model to X3D and WRL\n # mlab.savefig('{}/png_result_{}.png'.format(result_dir, file_basename))\n mlab.savefig(filename)\n\n mlab.show()\n\nif __name__ == \"__main__\":\n i = 18773\n pose = np.loadtxt('visualization/vae/vae_pose_{}.txt'.format(i))\n pose_gt = np.loadtxt('visualization/vae/vae_pose_{}_gt.txt'.format(i))\n plot_hand_pose(pose, 'visualization/vae/vae_pose_{}.x3d'.format(i))\n plot_hand_pose(pose_gt, 'visualization/vae/vae_pose_{}_gt.x3d'.format(i))","repo_name":"xinghaochen/MFA-Net","sub_path":"src/vis_util.py","file_name":"vis_util.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"10328023044","text":"import os\nimport pandas as pd\nimport aiohttp\nimport asyncio\n\nopenstreetmap_url_basepath = \"http://nominatim.openstreetmap.org/reverse\"\nbase_lat_lon_file_path = \"C:\\\\Users\\\\Gabri\\\\lat-lon.csv\"\nnew_lat_lon_file_path = \"C:\\\\Users\\\\Gabri\\\\new-lat-lon.csv\"\n\n\nasync def findCityByCoordinates(session, latitude, longitude):\n parameters = {\n 'format': 'json',\n 'lat': str(latitude),\n 'lon': str(longitude)\n }\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0\"\n }\n async with session.get(openstreetmap_url_basepath, params=parameters, headers=headers) as response:\n return await response.json(content_type=None) if response.status == 200 else None\n\ndef getCityFromResponse(data):\n address = data.get('address', {})\n return address.get('city') or address.get('town', '---')\n\nasync def addCityToCsv(session, tuple, lat_lon_csv):\n response_data = await findCityByCoordinates(session, tuple[2], tuple[3])\n city = getCityFromResponse(response_data) if response_data is not None else \"---\"\n lat_lon_csv.at[tuple.Index, \"city\"] = city\n lat_lon_csv.to_csv(new_lat_lon_file_path, header=True, index=False)\n print(tuple.Index)\n\n\nasync def addCityToCsvWithSemaphore(session, tuple, lat_lon_csv, semaphore):\n async with semaphore:\n await addCityToCsv(session, tuple, lat_lon_csv)\n\n\nasync def main():\n if os.path.exists(new_lat_lon_file_path):\n os.remove(new_lat_lon_file_path)\n\n data = pd.read_excel(\"quì ci va il percorso del file, MI RACCOMANDO FRA I DOPPI APICI\")\n lat_lon_csv = pd.read_csv(base_lat_lon_file_path)\n lat_lon_csv[\"city\"] = None\n\n semaphore = asyncio.Semaphore(10) # Limite delle connessioni parallele\n\n async with aiohttp.ClientSession(\n timeout=aiohttp.ClientTimeout(total=300),\n connector=aiohttp.TCPConnector(limit=10)\n ) as session:\n tasks = [addCityToCsvWithSemaphore(session, t, lat_lon_csv, semaphore) for t in lat_lon_csv.itertuples()]\n await asyncio.gather(*tasks)\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())","repo_name":"Panemiele/AriaPlus","sub_path":"utils/reverseGeocoding/asyncCoordinatesToCities.py","file_name":"asyncCoordinatesToCities.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"46004573162","text":"from unidecode import unidecode\n\n\ntext = \"Björn, Łukasz and Σωκράτης.\"\n\nprint(unidecode(text))\n\nimport sqlite3\nimport pandas as pd\n# Create your connection.\ncnx = sqlite3.connect('fpa-database-fix.db')\n\ndf_transfer = pd.read_sql_query(\"SELECT * FROM players_transfermarkt\", cnx)\nprint(df_transfer)\n\ndf_fpl = pd.read_sql_query(\"SELECT * FROM players\", cnx)\n\ncounter = 0\nfor index_transfer, row_transfer in df_transfer.iterrows():\n for index_fpl, row_fpl in df_fpl.iterrows():\n if unidecode(row_transfer[\"player_name\"]) == unidecode(row_fpl[\"first_name\"] + \" \" +row_fpl[\"second_name\"]):\n print(\"******\")\n print(row_transfer)\n print(counter)\n counter = counter+1\n\n # print(row[\"c1\"], row[\"c2\"])\n","repo_name":"Shomrey/football-progres-analysis","sub_path":"Database/data_merge.py","file_name":"data_merge.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"36427893396","text":"class Promedio:\r\n def hallar_promedio(self):\r\n a=[4,5,9,7,8,30]\r\n suma=0\r\n prom=0\r\n for i in a:\r\n suma=suma+i\r\n prom=suma/len(a)\r\n print(\"El promedio del vector es: \"+str(prom))\r\npromedio=Promedio()\r\npromedio.hallar_promedio()","repo_name":"Cristian-3450/estructura_de_datos","sub_path":"practicas de vectores (Tarea 2)/ejercicio_3.py","file_name":"ejercicio_3.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39939739509","text":"def get_pairs(arr, num):\n if len(arr) < 2:\n return 'No'\n else:\n for i in range(len(arr)-1):\n for j in range(i+1, len(arr)):\n if int(arr[i])*int(arr[j]) == num:\n return 'Yes'\n return 'No'\n\n\nresult = []\nfor i in range(int(input())):\n number = int(input().split()[1])\n array = input().split()\n result.append(get_pairs(array, number))\nfor i in range(len(result)):\n print(result[i])","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2392/60676/242221.py","file_name":"242221.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"39987018949","text":"num=int(input())\nl=[]\nans=[]\nfor i in range(num):\n s=input()\n l.append(s)\n# print(list)\nfor i in range(num):\n temple=list(l[i])\n set_=set(temple)\n if len(temple)==len(set_):\n ans.append(1)\n else:\n ans.append(0)\nprint(\"\\n\".join(str(i) for i in ans))","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2559/60622/237314.py","file_name":"237314.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"35859006816","text":"import numpy as np\nimport pandas as pd\nfrom numpy.random import randn\n\nnp.random.seed(101)\n\n# col1 col2 col3\n# 0 1 444 abc\n# 1 2 555 def\n# 2 3 666 ghi\n# 3 4 444 xyz\ndf = pd.DataFrame({'col1': [1, 2, 3, None],\n 'col2': [444, 555, 666, 444],\n 'col3': ['abc', 'def', 'ghi', 'xyz']})\n\n# Returns the 5 first rows\ndf.head()\n\n# Returns the unique values in col2\n# [444 555 666]\ndf['col2'].unique()\n\n# Number of unique numbers\n# 3\ndf['col2'].nunique()\n\n# Counts the number of times each values appears\n# 444 2\n# 555 1\n# 666 1\ndf['col2'].value_counts()\n\n# col1 col2 col3\n# 3 4 444 xyz\ncol1_sup_2_and_col2_eq_444 = df[(df['col1'] > 2) & (df['col2'] == 444)]\n\n# 0 False\n# 1 False\n# 2 True\n# 3 True\nbool_values = df['col1'] > 2\n\n\ndef times2(x):\n return x*2\n\n\n# Apply a function to a column\n# 0 2\n# 1 4\n# 2 6\n# 3 8\ndf['col1'].apply(times2)\n\n# 0 3\n# 1 3\n# 2 3\n# 3 3\ndf['col3'].apply(len)\n\n\n# 0 888\n# 1 1110\n# 2 1332\n# 3 888\ndf['col2'].apply(lambda x: x*2)\n\n# Index(['col1', 'col2', 'col3'], dtype='object')\ncolumns_index = df.columns\n\n# RangeIndex(start=0, stop=4, step=1)\nrows_index = df.index\n\n# Sort the dataframe thanks to col2\n# col1 col2 col3\n# 0 1 444 abc\n# 3 4 444 xyz\n# 1 2 555 def\n# 2 3 666 ghi\ndd = df.sort_values(by='col2')\n\n# col1\n# 0 False\n# 1 False\n# 2 False\n# 3 True\ntmpdf = pd.DataFrame({'col1': [1, 2, 3, None]})\nisnull = tmpdf.isnull()\n\n\ndata = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', ],\n 'B': ['one', 'one', 'two', 'two', 'one', 'one'],\n 'C': ['x', 'y', 'x', 'y', 'x', 'y'],\n 'D': [1, 3, 2, 5, 4, 1], })\n\n# A B C D\n# 0 foo one x 1\n# 1 foo one y 3\n# 2 foo two x 2\n# 3 bar two y 5\n# 4 bar one x 4\n# 5 bar one y 1\ndf = pd.DataFrame(data)\n\n# The values are the D column\n# The index are the A and B column\n# My actual columns are defined by the C column\n# C x y\n# A B \n# bar one 4.0 1.0\n# two NaN 5.0\n# foo one 1.0 3.0\n# two 2.0 NaN\npivot = df.pivot_table(values='D', index=['A', 'B'], columns=['C'])\nprint(pivot)","repo_name":"freefromix/dataScienceTheory","sub_path":"machineLearningTheory/myPandas/.ipynb_checkpoints/8_operations-checkpoint.py","file_name":"8_operations-checkpoint.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"20255602730","text":"from utils import *\nfrom DA_params import DA_Params\nfrom keras import backend as K\nimport tensorflow as tf\nfrom keras.losses import binary_crossentropy\n\n\n\ndef species_gen(params):\n\t# This generator returns the species-background data for 1 batch.\n\n\t# Each species' worth of data will be 1/3 of the total batchsize\n\tbatchfrac = params.batchsize / 3\n\t# We mask the binding labels for all species data\n\t# (so the binding classifier model half does not train on this info)\n\tdummy_binding_labels = np.array([-1 for _ in xrange(batchfrac * 2)])\n\tdummy_binding_labels = np.reshape(dummy_binding_labels, (batchfrac * 2, 1))\n\n\t# Load 1 generator each for the source and target species\n\tsource_gen = iu.get_generator(params.sourcetrainfile, batchfrac, True) \n\ttarget_gen = iu.get_generator(params.targettrainfile, batchfrac, True) \n\t\n\twhile True:\n\t\tsource_batch = next(source_gen)\n\t\ttarget_batch = next(target_gen)\n\n\t\tif params.chromsize > 0: # legacy code from when accessability was part of model input\n\t\t\tseqs = np.concatenate((source_batch[0][0], target_batch[0][0]))\n\t\t\taccessibility = np.concatenate((source_batch[0][1], target_batch[0][1]))\n\t\t\tmodel_input = [seqs, accessibility]\n\t\telse:\n\t\t\t# concatenate the data from the two species\n\t\t\tseqs = np.concatenate((source_batch[0], target_batch[0]))\n\t\t\tmodel_input = seqs\n\n\t\t# create the labels vector for the species discriminator\n\t\tspecies_labels = np.array([0 for _ in xrange(batchfrac)] + [1 for _ in xrange(batchfrac)])\n\t\tspecies_labels = np.reshape(species_labels, (batchfrac * 2, 1))\n\n\t\tyield model_input, dummy_binding_labels, species_labels\n\n\n\ndef binding_gen(params):\n\t# This generator returns the data used to train the binding classifier for 1 batch.\n\n\t# Binding data will make up 1/3 of the total batch (rest is species-background data)\n\tbatchfrac = params.batchsize / 3\n\t# The species discriminator does not train on this data, so we mask the labels\n\tdummy_species_labels = np.reshape(np.array([-1 for _ in xrange(batchfrac)]), (batchfrac, 1))\n\t\n\t# 1 generator each for bound and unbound examples (each fetches 1/2 a batch)\n\tpos_gen = iu.get_generator(params.bindingtrainposfile, int(batchfrac / 2), True) \n\tneg_gen = iu.get_generator(params.bindingtrainnegfile, int(batchfrac / 2), True)\n\t\n\twhile True:\n\t\tpos_examples = next(pos_gen)\n\t\tneg_examples = next(neg_gen)\n\t\t\n\t\t# concatenate sequences and labels vectors\n\t\tseqs = np.concatenate((pos_examples[0], neg_examples[0]))\n\t\tlabels = np.concatenate((pos_examples[1], neg_examples[1]))\n\n\t\t# shuffle (not necessary)\n\t\tshuffle_order = np.arange(seqs.shape[0])\n\t\tnp.random.shuffle(shuffle_order)\n\n\t\tseqs = seqs[shuffle_order, :, :]\n\t\tlabels = labels[shuffle_order]\n\n\t\tyield seqs, labels, dummy_species_labels\n\n\n\ndef get_training_gen(params):\n\t# This generator returns all the data needed each batch to train the model,\n\t# for both the binding classifier and species discriminator tasks.\n\n\t# Species discriminator data generator:\n\tspeciesdisc_gen = species_gen(params)\n\t# Binding classifier data generator:\n\tbindclass_gen = binding_gen(params)\n\n\twhile True:\n\t\t# fetch data from the two generators for this batch\n\t\tspeciesdisc_input, speciesdisc_bind_labels, speciesdisc_species_labels = next(speciesdisc_gen)\n\t\tbindclass_input, bindclass_bind_labels, bindclass_species_labels = next(bindclass_gen)\n\n\t\tif params.chromsize > 0: # legacy code from when accessibility was a possible model input\n\t\t\tseqs = np.concatenate((bindclass_input[0], speciesdisc_input[0]))\n\t\t\tacc = np.concatenate((bindclass_input[1], speciesdisc_input[1]))\n\t\t\tinput = [seqs, acc]\n\t\telse:\n\t\t\t# concatenate the data from both generators together\n\t\t\tinput = np.concatenate((bindclass_input, speciesdisc_input))\n\n\t\t# concatenate label vectors together\n\t\tbind_labels = np.concatenate((bindclass_bind_labels, speciesdisc_bind_labels))\n\t\tspecies_labels = np.concatenate((bindclass_species_labels, speciesdisc_species_labels))\n\n\t\tyield input, {\"classifier\" : bind_labels, \"discriminator\" : species_labels}\n\n\ndef get_val_gen(params, labels = False, target_data = True):\n\t# This generator returns a batch of sequences to validate/test the model on each yield.\n\t# If \"labels\" is True, what's returned will be a tuple of arrays: (sequences, binding labels)\n\t# By default, labels is False and only sequences are returned\n\t# If \"target_data\" is True, data will be fetched from the target (non-training) species\n\t# Otherwise, data will be fetched from the source (training) species\n\n\t# using dummy species labels here -- we only really care about evaluating binding task performance\n\tdummy_species_labels = np.reshape(np.array([-1 for _ in xrange(params.valbatchsize)]), (params.valbatchsize, 1))\n\n\tif target_data:\n\t\tgen = iu.get_generator(params.targetvalfile, params.valbatchsize, labels)\n\telse:\n\t\tgen = iu.get_generator(params.sourcevalfile, params.valbatchsize, labels)\n\t\n\twhile True:\n\t\tbatch = next(gen)\n\t\tif labels:\n\t\t\tyield batch[0], {\"classifier\" : batch[1], \"discriminator\" : dummy_species_labels}\n\t\telse:\n\t\t\tyield batch\n\n\ndef custom_loss(y_true, y_pred):\n\t# The model will be trained using this loss function, which is identical to normal BCE\n\t# except when the label for an example is -1, that example is masked out for that task.\n\t# This allows for examples to only impact loss backpropagation for one of the two tasks.\n\ty_pred = tf.boolean_mask(y_pred, tf.not_equal(y_true, -1))\n\ty_true = tf.boolean_mask(y_true, tf.not_equal(y_true, -1))\n\treturn binary_crossentropy(y_true, y_pred)\n\n\n\ndef DA_model(params):\n # Here we specify the architecture of the domain-adaptive model.\n # See DA_params.py for specific parameters values used here.\n\n seq_input = Input(shape = (params.seqlen, 4, ), name = 'seq')\n seq = Conv1D(params.convfilters, params.filtersize, padding = \"same\")(seq_input)\n seq = Activation('relu')(seq)\n seq = MaxPooling1D(padding = \"same\", strides = params.strides, pool_size = params.pool_size)(seq)\n\n classifier = LSTM(params.lstmnodes)(seq)\n classifier = Dense(params.dl1nodes)(classifier)\n classifier = Activation('relu')(classifier)\n classifier = Dense(params.dl2nodes, activation = 'sigmoid')(classifier)\n\n discriminator = Reshape((params.get_reshape_size(), ))(seq)\n discriminator = flipGradientTF.GradientReversal(params.lamb)(discriminator)\n discriminator = Dense(params.dl1nodes)(discriminator)\n discriminator = Activation('relu')(discriminator)\n discriminator = Dense(params.dl2nodes, activation = 'sigmoid')(discriminator)\n disc_result = Dense(1, activation = 'sigmoid', name = \"discriminator\")(discriminator)\n\n if params.chromsize > 0: # legacy code from when accessibility was possible model input\n acc_input = Input(shape = (params.chromsize, ), name = 'accessibility')\n acc = Dense(1, activation = 'sigmoid')(acc_input)\n merge_classifier = concatenate([classifier, acc])\n class_result = Dense(1, activation = 'sigmoid', name = \"classifier\")(merge_classifier)\n inputs = [seq_input, acc_input]\n else:\n class_result = Dense(1, activation = 'sigmoid', name = \"classifier\")(classifier)\n inputs = seq_input\n\n model = Model(inputs = inputs, outputs = [class_result, disc_result])\n return model\n\n\n\n","repo_name":"seqcode/multispecies-domain-adaptation","sub_path":"model_training/old/DA_utils.py","file_name":"DA_utils.py","file_ext":"py","file_size_in_byte":7202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"3683098968","text":"\"\"\"\nfind int returns True if num is a perfect square else False.\ncannot use sqrt\n\"\"\"\n\ndef isPerfectSquare(self, num: int) -> bool:\n if num < 2:\n return True\n left, right = 2, num // 2\n\n while left <= right:\n x = left + (right - left) // 2\n guess_squared = x * x\n if guess_squared == num:\n return True\n elif guess_squared > num:\n right = x - 1\n else:\n left = x + 1\n return True\n # Time complexity : O(logN).\n\n\"\"\"\nNewton's Method\n\n\n\n# Take num / 2 as a seed.\n\n# While x * x > num, compute the next guess using Newton's method: x = (x+num//x)//2\n# num//x as tangent of function f(x) = x^2-num\n\n# Return x * x == num\n\n\"\"\"\n\ndef isNewtonPerfectSquare(self, num: int) -> bool:\n if num < 2:\n return True\n x = num // 2\n while x * x > num:\n x = (x + num // x) // 2\n return x * x == True\n\n# Time complexity :O(logN) because guess sequence converges quadratically.\n\n\n\n","repo_name":"Blossomyyh/leetcode","sub_path":"PerfectSquares.py","file_name":"PerfectSquares.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"39209557929","text":"import sys\r\nimport json\r\nimport os\r\nfrom PVCInfo.device_manager import DeviceManager\r\nfrom .instances import InstanceFactory\r\nfrom Helpers.Configuration import Configuration\r\nfrom Environmentals.env_condition_cache_manager import EnvironmentConditionCacheManager\r\nfrom Environmentals.env_condition_cache_manager import EnvironmentConditionCache\r\n\r\n\r\nclass ItuffTokenHelper():\r\n\r\n def __init__(self):\r\n self.device_manager = DeviceManager.getInstance()\r\n self.api = InstanceFactory.getInstance().get_fusion_instance()\r\n pass\r\n\r\n def upload_ituff_data(self):\r\n try:\r\n print(\"Uploading collected ituff data\")\r\n screen_output = Configuration.getInstance().get_config_value('general','BOOTSCRIPT_OUTPUT')\r\n\r\n print(screen_output)\r\n screen_data = ''\r\n if os.path.exists(screen_output):\r\n print(\"Got screen out put info file at {}\".format(screen_output))\r\n with open(screen_output, 'r') as file:\r\n screen_data = file.read()\r\n\r\n self.upload_screening_info(screen_data)\r\n self.upload_IFWI_Details()\r\n \r\n except Exception as e:\r\n print(\"Failed to upload ituff data {}\".format(e))\r\n return \"Passed\"\r\n\r\n def upload_IFWI_Details(self):\r\n try:\r\n pvc_ifwi = Configuration.getInstance().get_config_value('lcbeconfigs','LCBE0_BIOS_PATH')\r\n self.api.misc_data.add_misc_data_to_run_result('PVC_IFWI',pvc_ifwi)\r\n except Exception as ex:\r\n print(\"Failed to update IFWI information to ituff: {}\".format(ex))\r\n \r\n def upload_screening_info(self, screening_output):\r\n self.api.ituff_log(\"PPVScreenInfo\", str(screening_output))\r\n cacheManager = EnvironmentConditionCacheManager()\r\n cache = cacheManager.read_environment_condition_cache()\r\n if not cache.REPORTED_DSS:\r\n return\r\n \r\n self.api.dff.add_dff_data('QDF', cache.TESTED_QDF)\r\n self.api.dff.add_dff_data('FREQ', cache.BOOT_FREQUENCY)\r\n \r\n for tile in range(2):\r\n if str(tile) in cache.REPORTED_DSS:\r\n if cache.REPORTED_DSS[str(tile)]:\r\n hex_value = hex(int(cache.REPORTED_DSS[str(tile)],2))\r\n print(\"Updating ituff data for tile {} DSS :- {}\".format(tile, hex_value))\r\n self.api.dff.add_dff_data('GTEN{}'.format(tile), hex_value)","repo_name":"arunvalliyil/PVC_PPV_CMV","sub_path":"PythonScripts/Helpers/ituff_helper.py","file_name":"ituff_helper.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"43543613118","text":"from datetime import datetime, timedelta\nfrom .models import Intervention\n\n\ndef get_all_interventions_serializer():\n \"\"\"\n Get all interventions data and serialize to JSON format.\n \"\"\"\n all_inter = Intervention.objects.all().order_by('create_at')\n data = []\n for inter in all_inter:\n splited_date = inter.date.isoformat().split('-')\n f_date = f\"{splited_date[2]}/{splited_date[1]}/{splited_date[0]}\"\n\n s_datetime = inter.create_at + timedelta(hours=2)\n s_datetime = s_datetime.isoformat(timespec='minutes').split('T')\n c_date = s_datetime[0].split('-')\n c_time = s_datetime[1].split('+')[0]\n c_f_date = f\"{c_date[2]}/{c_date[1]}/{c_date[0]}\"\n d = {\n \"pk\": inter.pk,\n \"label\": inter.label,\n \"description\": inter.description,\n \"agent_name\": inter.agent_name,\n \"city\": inter.city,\n \"create_at\": f\"{c_f_date} à {c_time}\",\n \"date\": f_date,\n \"status\": inter.status,\n \"edit\": inter.edit\n }\n if datetime.now().date() > inter.date:\n inter.status = \"Terminé\"\n inter.edit = False\n inter.save()\n d['status'] = \"Terminé\"\n d['edit'] = False\n data.append(d)\n return data\n\n\ndef serialize_inter(inter_obj):\n \"\"\"\n Serialize one intervention for send data with JSON format.\n inter_obj : Intervention model instance\n \"\"\"\n splited_date = inter_obj.date.isoformat().split('-')\n f_date = f\"{splited_date[2]}/{splited_date[1]}/{splited_date[0]}\"\n\n s_datetime = inter_obj.create_at\n s_datetime = s_datetime.isoformat(timespec='minutes').split('T')\n c_date = s_datetime[0].split('-')\n c_time = s_datetime[1].split('+')[0]\n c_f_date = f\"{c_date[2]}/{c_date[1]}/{c_date[0]}\"\n data = {\n \"pk\": inter_obj.pk,\n \"label\": inter_obj.label,\n \"description\": inter_obj.description,\n \"agent_name\": inter_obj.agent_name,\n \"city\": inter_obj.city,\n \"create_at\": f\"{c_f_date} à {c_time}\",\n \"date\": f_date,\n \"status\": inter_obj.status,\n \"edit\": inter_obj.edit\n }\n return data\n","repo_name":"riderflo85/ticketingNautilux","sub_path":"ticket/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"34885460757","text":"from django.conf import settings\nfrom django.db import models\n\nfrom users.models import User\n\nNULLABLE = {'null': True, 'blank': True}\n\n\nclass Course(models.Model):\n title = models.CharField(max_length=50, verbose_name='название')\n preview = models.ImageField(upload_to=\"previews/\", verbose_name=\"превью\", **NULLABLE)\n description = models.TextField(verbose_name='описание')\n\n lessons = models.ManyToManyField('Lesson', verbose_name='урок')\n\n owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, **NULLABLE)\n\n def __str__(self):\n return f'{self.title}'\n\n class Meta:\n verbose_name = \"курс\"\n verbose_name_plural = \"курсы\"\n\n\nclass Lesson(models.Model):\n title = models.CharField(max_length=50, verbose_name='название')\n description = models.TextField(verbose_name='описание')\n preview = models.ImageField(upload_to=\"previews/\", verbose_name=\"превью\", **NULLABLE)\n video_link = models.URLField(verbose_name=\"ссылка на видео\", **NULLABLE)\n\n owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, **NULLABLE)\n\n def __str__(self):\n return f'{self.title}'\n\n class Meta:\n verbose_name = \"урок\"\n verbose_name_plural = \"уроки\"\n\n\nclass Payment(models.Model):\n PAYMENT_METHOD = [\n (\"cash\", \"наличные\"),\n (\"bank_transfer\", \"перевод\"),\n ]\n\n user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='пользователь')\n payment_date = models.DateField(auto_now_add=True, verbose_name='дата оплаты')\n paid_course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name=\"payments\",\n verbose_name='оплаченный курс', **NULLABLE)\n paid_lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name=\"payments\",\n verbose_name='оплаченный урок', **NULLABLE)\n amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='сумма оплаты')\n payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD, verbose_name='способ оплаты')\n\n def __str__(self):\n return f\"{self.user}: {self.payment_date} - {self.amount} - {self.payment_method}\"\n\n class Meta:\n verbose_name = \"платеж\"\n verbose_name_plural = \"платежи\"\n\n\nclass Subscription(models.Model):\n course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name='Курс', **NULLABLE)\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Пользователь',\n **NULLABLE)\n\n subscribed = models.BooleanField(default=True, verbose_name='Подписка')\n\n def __str__(self):\n return f'{self.course} {self.user} ({self.subscribed})'\n\n class Meta:\n verbose_name = 'Подписка'\n verbose_name_plural = 'Подписки'\n","repo_name":"Yaaaaaata/DRF_DZ","sub_path":"classes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"20348566435","text":"from math import prod\n\n\ndef greater(args):\n return 1 if args[0] > args[1] else 0\n\n\ndef lesser(args):\n return 1 if args[0] < args[1] else 0\n\n\ndef middling(args):\n return 1 if args[0] == args[1] else 0\n\n\nclass Decoder:\n\n OP_MAP = {\n 0: sum,\n 1: prod,\n 2: min,\n 3: max,\n 5: greater,\n 6: lesser,\n 7: middling,\n } # Evil is evil, Stregobor\n HEX_MAP = {\n \"0\": \"0000\",\n \"1\": \"0001\",\n \"2\": \"0010\",\n \"3\": \"0011\",\n \"4\": \"0100\",\n \"5\": \"0101\",\n \"6\": \"0110\",\n \"7\": \"0111\",\n \"8\": \"1000\",\n \"9\": \"1001\",\n \"A\": \"1010\",\n \"B\": \"1011\",\n \"C\": \"1100\",\n \"D\": \"1101\",\n \"E\": \"1110\",\n \"F\": \"1111\",\n }\n\n def __init__(self, hex_string):\n self.hex_string = hex_string\n self.bin_string = self.hex_to_binary()\n self.total_bits = len(self.bin_string)\n self.version_sum = 0\n _, values = self.decode_by_bits(self.bin_string, self.total_bits)\n self.value = values[0]\n\n def hex_to_binary(self):\n bin_string = \"\"\n for char in self.hex_string:\n bin_string += Decoder.HEX_MAP[char]\n return bin_string\n\n def decode_by_bits(self, bin_string, total_bits):\n index = 0\n values = []\n while index < (total_bits - 7):\n packet_type = \"lit\" if bin_string[index + 3 : index + 6] == \"100\" else \"op\"\n if packet_type == \"lit\":\n bits_used, value = self.decode_literal(bin_string[index:])\n else:\n bits_used, value = self.decode_operator(bin_string[index:])\n index += bits_used\n values.append(value)\n return total_bits, values\n\n def decode_by_packets(self, bin_string, total_packets):\n index = 0\n packets = 0\n values = []\n while packets < total_packets:\n packet_type = \"lit\" if bin_string[index + 3 : index + 6] == \"100\" else \"op\"\n if packet_type == \"lit\":\n bits_used, value = self.decode_literal(bin_string[index:])\n else:\n bits_used, value = self.decode_operator(bin_string[index:])\n packets += 1\n index += bits_used\n values.append(value)\n return index, values\n\n def decode_literal(self, new_string):\n version = int(new_string[:3], 2)\n self.version_sum += version\n val_string = \"\"\n idx = 6\n while new_string[idx] == \"1\":\n val_string += new_string[idx + 1 : idx + 5]\n idx += 5\n val_string += new_string[idx + 1 : idx + 5]\n val = int(val_string, 2)\n idx += 5\n return idx, val # return number of bits to advance\n\n def decode_operator(self, new_string):\n version = int(new_string[:3], 2)\n op_type = int(new_string[3:6], 2)\n operator = Decoder.OP_MAP[op_type]\n self.version_sum += version\n operator_class = \"BITS\" if new_string[6] == \"0\" else \"PACKETS\"\n if operator_class == \"BITS\":\n nested_bits = int(new_string[7:22], 2)\n bits_used, values = self.decode_by_bits(new_string[22:], nested_bits)\n bits_used += 22\n else: # operator_class == \"PACKETS\"\n sub_packets = int(new_string[7:18], 2)\n bits_used, values = self.decode_by_packets(new_string[18:], sub_packets)\n bits_used += 18\n value = operator(values)\n return bits_used, value\n\n\nwith open(\"2021/res/in16.txt\") as file:\n puzzle_input, pt1_tests, pt2_tests = file.read().split(\"\\n\\n\")\n\npt1_tests = [\n (test.split(\" \")[0], int(test.split(\" \")[1])) for test in pt1_tests.split(\"\\n\")\n]\npt2_tests = [\n (test.split(\" \")[0], int(test.split(\" \")[1])) for test in pt2_tests.split(\"\\n\")\n]\n\nfor i, test in enumerate(pt1_tests):\n hex_string, expected_sum = test\n d = Decoder(hex_string)\n if d.version_sum != expected_sum:\n print(\n f\"Part 1 test # {i + 1} failed: expected {expected_sum}, got {d.version_sum}\"\n )\n exit()\nprint(\"All Part 1 tests passing\")\n\nfor i, test in enumerate(pt2_tests):\n hex_string, expected_val = test\n d = Decoder(hex_string)\n if d.value != expected_val:\n print(\n f\"Part 1 test # {i + 1} failed: expected {expected_sum}, got {d.version_sum}\"\n )\n exit()\nprint(\"All Part 2 tests passing\")\n\npuzzle_decoder = Decoder(puzzle_input)\n\npt1 = puzzle_decoder.version_sum\npt2 = puzzle_decoder.value\nprint(\"Part 1 solution: \", pt1)\nprint(\"Part 2 solution: \", pt2)\n","repo_name":"spencer-zepelin/AoC","sub_path":"2021/src/q16.py","file_name":"q16.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"3683408318","text":"def isBadVersion(param):\n return False\n\n\nclass Solution:\n\n def firstBadVersion(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n low = 1\n high = n\n if isBadVersion(1):\n return 1\n while low <= high:\n mid = low + (high-low)//2\n if isBadVersion(mid) and not isBadVersion(mid-1):\n return mid\n elif not isBadVersion(mid):\n low = mid+1\n else:\n high = mid-1\n return -1\n\n \"\"\"\n We can check with a linear scan.\n sum in compare\n \n \"\"\"\n def numsJewelsLinerStones(self, J: str, S: str):\n return sum(s in J for s in S)\n\n \"\"\"\n set in Python\n Time Complexity:O(J.length+S.length))\n \"\"\"\n def numsJewelsInStones(self, J: str, S: str):\n Jset = set(J)\n return sum(s in Jset for s in S)\n\nif __name__ == \"__main__\":\n print(\"hello word\")","repo_name":"Blossomyyh/leetcode","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"73392950017","text":"import xml.etree.ElementTree as ET\n\ntree = ET.ElementTree(file='0022.xml')\n\n# root = tree.getroot()\n\n# for elem in tree.iter(tag='GeoNE'):\n# print(elem.tag, elem.attrib)\n\nfor elem in tree.iterfind('AnnotationSet/Annotation[@Type=\"GeoNE\"]'):\n print(elem.tag, elem.attrib)\n","repo_name":"leeguandong/DL-data-processing-methods","sub_path":"NLP/XML/NER.py","file_name":"NER.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"80"} +{"seq_id":"44749830639","text":"from collections import namedtuple\nimport json\nimport requests\nfrom datetime import datetime\nfrom requests.auth import HTTPBasicAuth\n\nCommit = namedtuple(\n \"Commit\", \"commit_id repo comment author_name author_email author_date committer_name committer_email committer_date\")\nChange = namedtuple(\"Change\", \"commit_id path change_type\")\n\n\nclass AZDOGit():\n BASE_URL_FORMAT = 'https://dev.azure.com/{}/{}/_apis/git'\n PAGE_SIZE = 50\n\n def __init__(self, org, project, token):\n self.org = org\n self.project = project\n self.token = token\n self.base_url = self.BASE_URL_FORMAT.format(org, project)\n\n def repos(self, filter=None):\n url = f'{self.base_url}/repositories?api-version=7.0'\n response = self.__get_data(url)\n data = response['value']\n if filter:\n return [r['name'] for r in data if filter.lower() in r['name'].lower()]\n else:\n return [r['name'] for r in data]\n\n def commits(self, repo, date_from=None):\n hasMore = True\n skip = 0\n url = self.__get_url(repo, self.PAGE_SIZE, skip, date_from)\n while hasMore:\n data = self.__get_data(url)\n item_count = data['count']\n if item_count > 0:\n for commit in data['value']:\n yield self.__parse_commit_data(repo, commit)\n skip += item_count\n url = self.__get_url(repo, self.PAGE_SIZE, skip, date_from)\n else:\n hasMore = False\n\n def changes(self, repo, commit_id):\n url = f'{self.base_url}/repositories/{repo}/commits/{commit_id}/changes'\n data = self.__get_data(url)\n return [\n Change(commit_id=cr['item']['commitId'], path=cr['item']\n ['path'], change_type=cr['changeType'])\n for cr in data['changes']\n if cr['item']['gitObjectType'] == 'blob']\n\n def __get_url(self, repo, pagesize, skip, since):\n url = f'{self.base_url}/repositories/{repo}/commits?api-version=7.0&$top={pagesize}&$skip={skip}&searchCriteria.showOldestCommitsFirst=true'\n if since:\n formatted_date = datetime.strftime(since, '%Y-%m-%dT%H:%M:%SZ')\n url = f'{url}&searchCriteria.fromDate={formatted_date}'\n return url\n\n def __get_data(self, url):\n response = requests.get(url, auth=HTTPBasicAuth('user', self.token))\n if response.status_code != 200:\n raise Exception(\n f'Got Status Code {response.status_code}. Message: {response.reason}')\n return json.loads(response.content.decode('utf-8'))\n\n def __parse_commit_data(self, repo, ci):\n id = ci['commitId']\n comment = ci['comment']\n author = ci['author']\n author_name = author['name']\n author_email = author['email']\n author_date = self.__clean_date_string(author['date'])\n committer = ci['committer']\n committer_name = committer['name']\n committer_email = committer['email']\n committer_date = self.__clean_date_string(committer['date'])\n return Commit(id, repo, comment, author_name, author_email, author_date, committer_name, committer_email, committer_date)\n\n def __clean_date_string(self, date_string):\n return \" \".join(date_string.split('T'))[:-1]\n","repo_name":"slmcmahon/git2sqlite","sub_path":"app/azdo_git.py","file_name":"azdo_git.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"74155812099","text":"from mlProject2.constants import *\nfrom mlProject2.utils.common import read_yaml, create_directories\nfrom mlProject2.entity.config_entity import (DataIngestionConfig, \n DataValidationConfig, \n DataTransformationConfig,\n ModelTrainerConfig,\n ModelEvaluationConfig)\n\n\n\n\nclass ConfigurationManager:\n def __init__(\n self,\n config_filepath = CONFIG_FILE_PATH,\n params_filepath = PARAMS_FILE_PATH,\n schema_filepath = SCHEMA_FILE_PATH):\n\n self.config = read_yaml(config_filepath)\n self.params = read_yaml(params_filepath)\n self.schema = read_yaml(schema_filepath)\n\n create_directories([self.config.artifacts_root])\n\n def get_data_ingestion_config(self) -> DataIngestionConfig:\n config = self.config.data_ingestion # storing the data_ingestion config into into variable config\n\n create_directories([config.root_dir]) # create root directory for the variable config \n\n # Returning the data type as defined in the DataIngestionCofig in the entity\n# # reading one by one from the config variable and storing them to assigned variables like root_dir, source_URL etc. \n\n\n data_ingestion_config = DataIngestionConfig(\n root_dir=config.root_dir,\n source_URL=config.source_URL,\n local_data_file=config.local_data_file,\n unzip_dir=config.unzip_dir \n )\n\n return data_ingestion_config\n \n def get_data_validation_config(self) -> DataValidationConfig:\n config = self.config.data_validation # storing the data_ingestion config into into variable config\n schema = self.schema.COLUMNS\n\n create_directories([config.root_dir]) # create root directory for the variable config \n\n # Returning the data type as defined in the DataIngestionCofig in the entity\n# # reading one by one from the config variable and storing them to assigned variables like root_dir, source_URL etc. \n\n\n data_ingestion_config = DataValidationConfig(\n root_dir= config.root_dir,\n STATUS_FILE= config.STATUS_FILE,\n unzip_data_dir= config.unzip_data_dir,\n all_schema= schema,\n \n )\n\n return data_ingestion_config\n \n\n def get_data_transformation_config(self) -> DataTransformationConfig:\n config = self.config.data_transformation # storing the data_ingestion config into into variable config\n\n create_directories([config.root_dir]) # create root directory for the variable config \n\n data_transformation_config = DataTransformationConfig(\n root_dir= config.root_dir,\n data_path= config.data_path,\n )\n\n return data_transformation_config\n \n\n def get_model_trainer_config(self) -> ModelTrainerConfig:\n config = self.config.model_trainer # storing the data_ingestion config into into variable config\n params = self.params.ElasticNet\n schema = self.schema.TARGET_COLUMN\n\n create_directories([config.root_dir]) # create root directory for the variable config \n\n model_trainer_config = ModelTrainerConfig(\n root_dir= config.root_dir,\n train_data_path = config.train_data_path,\n test_data_path= config.test_data_path,\n model_name= config.model_name,\n alpha= params.alpha,\n l1_ratio=params.l1_ratio,\n target_column=schema.name\n )\n\n return model_trainer_config\n \n\n def get_model_evaluation_config(self) -> ModelEvaluationConfig:\n config = self.config.model_evaluation # storing the data_ingestion config into into variable config\n params = self.params.ElasticNet\n schema = self.schema.TARGET_COLUMN\n\n create_directories([config.root_dir]) # create root directory for the variable config \n\n model_evaluation_config = ModelEvaluationConfig(\n root_dir= config.root_dir,\n test_data_path= config.test_data_path,\n \n \n model_path = config.model_path,\n all_params = params,\n metric_file_name = config.metric_file_name,\n target_column= schema.name\n )\n return model_evaluation_config\n \n\n","repo_name":"nlsrikanth7/mlproject2","sub_path":"src/mlProject2/config/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"}